| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980 |
- package telegram
- import (
- "app/commons/config"
- "app/commons/core"
- tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
- )
- var bot *tgbotapi.BotAPI
- // InitBot 初始化 Telegram Bot
- func InitBot() error {
- telegramConfig := config.EnvConf().Telegram
- if telegramConfig == nil {
- core.Log.Warn("Telegram 配置未找到,跳过 Bot 初始化")
- return nil
- }
- if telegramConfig.BotToken == "" || telegramConfig.BotToken == "YOUR_BOT_TOKEN_HERE" {
- core.Log.Warn("Telegram Bot Token 未配置,跳过 Bot 初始化")
- return nil
- }
- b, err := tgbotapi.NewBotAPI(telegramConfig.BotToken)
- if err != nil {
- core.Log.Errorf("初始化 Telegram Bot 失败: %v", err)
- return err
- }
- b.Debug = telegramConfig.Debug
- bot = b
- core.Log.Infof("✅ Telegram Bot 初始化成功: @%s", bot.Self.UserName)
- return nil
- }
- // GetBot 获取 Bot 实例
- func GetBot() *tgbotapi.BotAPI {
- return bot
- }
- // IsEnabled 检查 Bot 是否启用
- func IsEnabled() bool {
- return bot != nil
- }
- // StartPolling 开始轮询消息
- func StartPolling() {
- if !IsEnabled() {
- core.Log.Warn("Telegram Bot 未启用,跳过消息轮询")
- return
- }
- core.Log.Info("🚀 启动 Telegram Bot 消息轮询...")
- u := tgbotapi.NewUpdate(0)
- u.Timeout = 60
- updates := bot.GetUpdatesChan(u)
- for update := range updates {
- // 异步处理消息,避免阻塞
- go handleUpdate(update)
- }
- }
- // handleUpdate 处理更新
- func handleUpdate(update tgbotapi.Update) {
- defer func() {
- if r := recover(); r != nil {
- core.Log.Errorf("处理消息时发生错误: %v", r)
- }
- }()
- if update.Message != nil {
- HandleMessage(update.Message)
- } else if update.CallbackQuery != nil {
- HandleCallback(update.CallbackQuery)
- }
- }
|