bots/new.go
Кобелев Андрей Андреевич cd31f2d96b init
2022-06-03 13:58:41 +03:00

84 lines
1.8 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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
}