DB640/internal/telegram/telegram.go

103 lines
2.8 KiB
Go

package telegram
import (
"log"
"git.1750studios.com/ToddShepard/DB640/internal/config"
"git.1750studios.com/ToddShepard/DB640/internal/database"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api"
"github.com/jinzhu/gorm"
uuid "github.com/nu7hatch/gouuid"
)
// UpdateChan is telegram UpdatesChannel
type UpdateChan = tgbotapi.UpdatesChannel
var bot *tgbotapi.BotAPI
// Init initzializes the telegram bot
func Init() (err error) {
bot, err = tgbotapi.NewBotAPI(config.C.Telegram.APIKey)
if err != nil {
return
}
log.Printf("Authorized on account %s", bot.Self.UserName)
return
}
// GetChan returns the Telegram update channel
func GetChan() (UpdateChan, error) {
u := tgbotapi.NewUpdate(0)
u.Timeout = 60
return bot.GetUpdatesChan(u)
}
// DeInit deinitzialisizes the bot
func DeInit() {
bot.StopReceivingUpdates()
}
// SendReply sends a reply to the given update
func SendReply(reply string, update tgbotapi.Update) error {
var chat database.TGChat
chat.ID = update.Message.Chat.ID
if database.Db.First(&chat).Error != gorm.ErrRecordNotFound {
chat.FirstName = update.Message.Chat.FirstName
chat.LastName = update.Message.Chat.LastName
chat.UserName = update.Message.Chat.UserName
database.Db.Save(&chat)
} else {
chat.FirstName = update.Message.Chat.FirstName
chat.LastName = update.Message.Chat.LastName
chat.UserName = update.Message.Chat.UserName
database.Db.Create(&chat)
}
msg := tgbotapi.NewMessage(update.Message.Chat.ID, reply)
if _, err := bot.Send(msg); err != nil {
return err
}
return nil
}
// SendAll sends a message to all active users
func SendAll(msg string) {
log.Printf("[TELEGRAM] Sending to all chats: %s", msg)
var chats []database.TGChat
database.Db.Find(&chats)
for _, chat := range chats {
tgmsg := tgbotapi.NewMessage(chat.ID, msg)
if _, err := bot.Send(tgmsg); err != nil && err.Error() == "Forbidden: bot was blocked by the user" {
database.Db.Unscoped().Delete(&chat)
}
}
}
// DoInlineQuery does the inline query search and returns results
func DoInlineQuery(update tgbotapi.Update) {
var config tgbotapi.InlineConfig
var results []interface{}
var betriebsstellen []database.Betriebsstelle
config.InlineQueryID = update.InlineQuery.ID
config.Results = results
err := database.Db.Limit(50).Find(&betriebsstellen, "Code LIKE ?", update.InlineQuery.Query+"%").Error
if err != nil || len(betriebsstellen) == 0 {
bot.AnswerInlineQuery(config)
return
}
for _, bs := range betriebsstellen {
msg := bs.Code + ": " + bs.Name
id, _ := uuid.NewV4()
results = append(results, tgbotapi.NewInlineQueryResultArticle(id.String(), msg, msg))
}
config.Results = results
bot.AnswerInlineQuery(config)
log.Printf("[TELEGRAM Inline] %s: %s", update.InlineQuery.From.String(), update.InlineQuery.Query)
}