84 lines
1.8 KiB
Go
84 lines
1.8 KiB
Go
|
package bot
|
|||
|
|
|||
|
import (
|
|||
|
"fmt"
|
|||
|
"time"
|
|||
|
|
|||
|
"git.belvedersky.ru/common/db"
|
|||
|
"git.belvedersky.ru/common/logger"
|
|||
|
"git.belvedersky.ru/common/logger/service"
|
|||
|
"git.belvedersky.ru/common/tgbotapi"
|
|||
|
"gopkg.in/telebot.v3"
|
|||
|
)
|
|||
|
|
|||
|
// Cоздание бота
|
|||
|
func new(url string, cfg BotConfig) (bot *telebot.Bot, err error) {
|
|||
|
// client := &http.Client{Re}
|
|||
|
bot, err = telebot.NewBot(telebot.Settings{URL: "https://api.telegram.org", Token: cfg.Token}) //Client: client})
|
|||
|
if err != nil {
|
|||
|
return nil, err
|
|||
|
}
|
|||
|
if cfg.UseWebhook {
|
|||
|
bot.Poller = &telebot.Webhook{
|
|||
|
MaxConnections: 100,
|
|||
|
DropUpdates: true,
|
|||
|
Endpoint: &telebot.WebhookEndpoint{
|
|||
|
PublicURL: fmt.Sprintf("%s/api/webhook/%s/%s", url, bot.Me.Username, cfg.Token),
|
|||
|
},
|
|||
|
}
|
|||
|
} else {
|
|||
|
if err := bot.RemoveWebhook(true); err != nil {
|
|||
|
return nil, err
|
|||
|
}
|
|||
|
bot.Poller = &telebot.LongPoller{Timeout: 10 * time.Second}
|
|||
|
}
|
|||
|
|
|||
|
if err != nil {
|
|||
|
return nil, err
|
|||
|
}
|
|||
|
return bot, nil
|
|||
|
}
|
|||
|
|
|||
|
// Создание cервиса бота
|
|||
|
func New(cfg BotConfig, lg *logger.Logger, db *db.PostgresRepository) (b *Bot, err error) {
|
|||
|
|
|||
|
chatBot, err := new("https://test.belvedersky.ru", cfg)
|
|||
|
if err != nil {
|
|||
|
return nil, err
|
|||
|
}
|
|||
|
api, err := tgbotapi.NewBotAPI(cfg.Token)
|
|||
|
if err != nil {
|
|||
|
return nil, err
|
|||
|
}
|
|||
|
botLog := lg.Create(chatBot.Me.Username)
|
|||
|
bot := Bot{
|
|||
|
Config: cfg,
|
|||
|
Bot: chatBot,
|
|||
|
Api: api,
|
|||
|
Log: botLog,
|
|||
|
Msg: chatBot.Updates,
|
|||
|
}
|
|||
|
return &bot, nil
|
|||
|
}
|
|||
|
|
|||
|
// Старт бота
|
|||
|
func Start(b *Bot) (err error) {
|
|||
|
|
|||
|
if b.Config.UseWebhook {
|
|||
|
webhook, err := b.Bot.Webhook()
|
|||
|
if err != nil {
|
|||
|
return err
|
|||
|
}
|
|||
|
b.Log.Log.Println("Вебхук бота", webhook)
|
|||
|
}
|
|||
|
|
|||
|
defer func() {
|
|||
|
if err := recover(); err != nil {
|
|||
|
err = fmt.Errorf("%v", err)
|
|||
|
}
|
|||
|
}()
|
|||
|
b.Log.Print(service.LogStruct{Message: "Бот " + b.Bot.Me.Username + " запущен"})
|
|||
|
b.Bot.Start()
|
|||
|
return err
|
|||
|
}
|