Skip to content

Commit

Permalink
Discord bot Hori
Browse files Browse the repository at this point in the history
  • Loading branch information
xjl0 committed Feb 20, 2023
0 parents commit 38ce744
Show file tree
Hide file tree
Showing 10 changed files with 1,031 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
.env
.idea
config.yaml
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2022 Joel56ru

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
35 changes: 35 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@

# Discord Бот Hori

- Автоматически приветствует
- Ставит реакцию на ссылки youtube и coub для рейтинга
- Получает текущие праздники с [сайта](https://kakoysegodnyaprazdnik.ru)
- Получает последнюю новость с [сайта](https://shikimori.one)
- Вычисляет время просмотра серий
- Автоматически переводит сообщения на русский язык
- Отправляет в чат ссылку на новое созданное мероприятие (событие) сервера
## Настройка бота

Настройка config.yaml

```yaml
discord:
codeinvite: "Код приглашения на сервер"
helloemote: "ID эмоции сервера"
lasted: ID последней новости Шики
mainchannel: "ID основного чата"
mediachannel: "ID медиа чата"
newschannel: "ID чата новостей"
testchannel: "ID чата для тестов"
```
Для работы бота необходимо [создать приложение](https://discord.com/developers/applications) на сайте discord
Настройка .env
```env
DGU_TOKEN=Токен приложения
```
## Команды

- календарь
- Сколько по времени 1 серия? (Сколько по времени 12 серий?)
- бот жив?
40 changes: 40 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
module discordbotgo

go 1.19

require (
github.com/PuerkitoBio/goquery v1.8.1
github.com/bas24/googletranslatefree v0.0.0-20220326200502-05ed9e639439
github.com/bwmarrin/discordgo v0.27.0
github.com/go-telegram-bot-api/telegram-bot-api/v5 v5.5.1
github.com/joho/godotenv v1.5.1
github.com/pemistahl/lingua-go v1.3.3
github.com/sirupsen/logrus v1.9.0
)

require (
github.com/andybalholm/cascadia v1.3.1 // indirect
github.com/fsnotify/fsnotify v1.6.0 // indirect
github.com/gorilla/websocket v1.4.2 // indirect
github.com/hashicorp/hcl v1.0.0 // indirect
github.com/magiconair/properties v1.8.7 // indirect
github.com/mitchellh/mapstructure v1.5.0 // indirect
github.com/pelletier/go-toml/v2 v2.0.6 // indirect
github.com/robertkrimen/otto v0.2.1 // indirect
github.com/shopspring/decimal v1.3.1 // indirect
github.com/spf13/afero v1.9.3 // indirect
github.com/spf13/cast v1.5.0 // indirect
github.com/spf13/jwalterweatherman v1.1.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/spf13/viper v1.15.0 // indirect
github.com/subosito/gotenv v1.4.2 // indirect
golang.org/x/crypto v0.0.0-20220525230936-793ad666bf5e // indirect
golang.org/x/exp v0.0.0-20221106115401-f9659909a136 // indirect
golang.org/x/net v0.7.0 // indirect
golang.org/x/sys v0.5.0 // indirect
golang.org/x/text v0.7.0 // indirect
google.golang.org/protobuf v1.28.1 // indirect
gopkg.in/ini.v1 v1.67.0 // indirect
gopkg.in/sourcemap.v1 v1.0.5 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
523 changes: 523 additions & 0 deletions go.sum

Large diffs are not rendered by default.

41 changes: 41 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package main

import (
"discordbotgo/pkg/discord"
"github.com/joho/godotenv"
"github.com/sirupsen/logrus"
"github.com/spf13/viper"
"log"
"os"
"os/signal"
"syscall"
)

func main() {
if err := godotenv.Load(); err != nil {
logrus.Fatalf("error loading env variables: %s", err.Error())
}
if err := initConfig(); err != nil {
log.Fatalf("Error init config file: %s", err.Error())
}

dBot := discord.NewDBot(os.Getenv("DGU_TOKEN"))
if err := dBot.Start(); err != nil {
log.Fatal(err)
}
defer dBot.Stop()

go dBot.HandlerGetNews()
go dBot.HandlerGetHoliday()

c := make(chan os.Signal)
signal.Notify(c, syscall.SIGINT, syscall.SIGTERM, os.Interrupt, os.Kill)
<-c
}

func initConfig() error {
viper.SetConfigType("yaml")
viper.SetConfigName("config")
viper.AddConfigPath(".")
return viper.ReadInConfig()
}
38 changes: 38 additions & 0 deletions pkg/calendar/calendar.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package calendar

import (
"github.com/PuerkitoBio/goquery"
"net/http"
"strings"
)

func CalendarReq() (string, error) {
client := &http.Client{}
req, err := http.NewRequest("GET", "https://kakoysegodnyaprazdnik.ru/", nil)
if err != nil {
return "", err
}
req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.54 Safari/537.36")
res, err := client.Do(req)
defer res.Body.Close()
if res.StatusCode != 200 {
return res.Status, nil
}
doc, err := goquery.NewDocumentFromReader(res.Body)
if err != nil {
return "", err
}
var result string
count := 0
doc.Find(".listing .listing_wr .main").Each(func(i int, s *goquery.Selection) {
if count < 20 {
text := s.Find("span").First().Text()
text = strings.Replace(text, "США", ":flag_um:", 1)
text = strings.Replace(text, "Япония", ":flag_jp:", 1)
result += ":small_blue_diamond: " + text + "\n"
}
count++
})
result = "**Праздники сегодня**\n" + result
return result, nil
}
67 changes: 67 additions & 0 deletions pkg/discord/discord.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
package discord

import (
"discordbotgo/pkg/calendar"
"github.com/bwmarrin/discordgo"
"github.com/spf13/viper"
"log"
"time"
)

type DBot struct {
token string
testChannel string
mainChannel string
codeInvite string
dg *discordgo.Session
m *discordgo.MessageCreate
}

func NewDBot(token string) *DBot {
return &DBot{token: token}
}

func (b *DBot) Start() error {
session, err := discordgo.New("Bot " + b.token)
if err != nil {
return err
}

b.dg = session

b.dg.AddHandler(eventCreate)
b.dg.AddHandler(isALife)
b.dg.AddHandler(message)

err = b.dg.Open()
if err != nil {
return err
}
log.Println("Bot is now running. Press CTRL-C to exit.")

return nil
}

func (b *DBot) HandlerGetNews() {
for range time.Tick(time.Minute * 10) {
sendNews(b.dg)
}
}

func (b *DBot) HandlerGetHoliday() {
newsChannel := viper.GetString("discord.newschannel")
testChannel := viper.GetString("discord.testchannel")
for range time.Tick(time.Hour) {
if time.Now().Hour() == 8 {
text, err := calendar.CalendarReq()
if err != nil {
b.dg.ChannelMessageSend(testChannel, err.Error())
}
b.dg.ChannelMessageSend(newsChannel, text)
}
}
}

func (b *DBot) Stop() error {
return b.dg.Close()
}
Loading

0 comments on commit 38ce744

Please sign in to comment.