bot.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. package telegram
  2. import (
  3. "log"
  4. tg "github.com/go-telegram-bot-api/telegram-bot-api"
  5. "github.com/nchursin/formtgbot/config"
  6. )
  7. var key = config.Get().Token
  8. var chats = config.Get().AdminChats
  9. var botInstance Bot
  10. type Bot struct {
  11. isReady bool
  12. Bot *tg.BotAPI
  13. }
  14. func GetBot() *Bot {
  15. if !botInstance.isReady {
  16. tgBot, err := tg.NewBotAPI(key)
  17. if err != nil {
  18. log.Panic(err)
  19. }
  20. tgBot.Debug = true
  21. log.Printf("Authorized on account %s", tgBot.Self.UserName)
  22. botInstance.Bot = tgBot
  23. botInstance.isReady = true
  24. }
  25. return &botInstance
  26. }
  27. func (bot *Bot) SendMessage(data Messageable) {
  28. message, format := data.Message()
  29. keyboard := data.FullKeyboard()
  30. log.Printf("[%s] %s", "message", message)
  31. for _, chatId := range chats {
  32. msg := tg.NewMessage(chatId, message)
  33. msg.ParseMode = format
  34. msg.ReplyMarkup = keyboard
  35. bot.Bot.Send(msg)
  36. }
  37. }
  38. func (bot *Bot) SendTextMessage(message string) {
  39. log.Printf("[%s] %s", "message", message)
  40. for _, chatId := range chats {
  41. msg := tg.NewMessage(chatId, message)
  42. log.Printf("[telegram]: sending message: %+v", msg)
  43. bot.Bot.Send(msg)
  44. }
  45. }
  46. func (bot *Bot) PostToChannel(data Postable) {
  47. message, format := data.Message()
  48. keyboard := data.ChannelKeyboard()
  49. log.Printf("[%s] %s", "message", message)
  50. msg := tg.NewMessageToChannel(config.Get().Channel, message)
  51. msg.ParseMode = format
  52. msg.ReplyMarkup = keyboard
  53. log.Printf("[telegram]: posting: %+v", msg)
  54. bot.Bot.Send(msg)
  55. }
  56. func (bot *Bot) ListenForUpdates() tg.UpdatesChannel {
  57. u := tg.NewUpdate(0)
  58. u.Timeout = 60
  59. updates, err := bot.Bot.GetUpdatesChan(u)
  60. if nil != err {
  61. panic(err)
  62. }
  63. return updates
  64. }