bot.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package telegram
  2. import (
  3. "app/commons/config"
  4. "app/commons/core"
  5. tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
  6. )
  7. var bot *tgbotapi.BotAPI
  8. // InitBot 初始化 Telegram Bot
  9. func InitBot() error {
  10. telegramConfig := config.EnvConf().Telegram
  11. if telegramConfig == nil {
  12. core.Log.Warn("Telegram 配置未找到,跳过 Bot 初始化")
  13. return nil
  14. }
  15. if telegramConfig.BotToken == "" || telegramConfig.BotToken == "YOUR_BOT_TOKEN_HERE" {
  16. core.Log.Warn("Telegram Bot Token 未配置,跳过 Bot 初始化")
  17. return nil
  18. }
  19. b, err := tgbotapi.NewBotAPI(telegramConfig.BotToken)
  20. if err != nil {
  21. core.Log.Errorf("初始化 Telegram Bot 失败: %v", err)
  22. return err
  23. }
  24. b.Debug = telegramConfig.Debug
  25. bot = b
  26. core.Log.Infof("✅ Telegram Bot 初始化成功: @%s", bot.Self.UserName)
  27. return nil
  28. }
  29. // GetBot 获取 Bot 实例
  30. func GetBot() *tgbotapi.BotAPI {
  31. return bot
  32. }
  33. // IsEnabled 检查 Bot 是否启用
  34. func IsEnabled() bool {
  35. return bot != nil
  36. }
  37. // StartPolling 开始轮询消息
  38. func StartPolling() {
  39. if !IsEnabled() {
  40. core.Log.Warn("Telegram Bot 未启用,跳过消息轮询")
  41. return
  42. }
  43. core.Log.Info("🚀 启动 Telegram Bot 消息轮询...")
  44. u := tgbotapi.NewUpdate(0)
  45. u.Timeout = 60
  46. updates := bot.GetUpdatesChan(u)
  47. for update := range updates {
  48. // 异步处理消息,避免阻塞
  49. go handleUpdate(update)
  50. }
  51. }
  52. // handleUpdate 处理更新
  53. func handleUpdate(update tgbotapi.Update) {
  54. defer func() {
  55. if r := recover(); r != nil {
  56. core.Log.Errorf("处理消息时发生错误: %v", r)
  57. }
  58. }()
  59. if update.Message != nil {
  60. HandleMessage(update.Message)
  61. } else if update.CallbackQuery != nil {
  62. HandleCallback(update.CallbackQuery)
  63. }
  64. }