如何用tgbotapi实现Telegram频道ID获取功能(Go语言)
解决方案
核心思路
放弃startchannel链接的实现方式——它本身是为机器人加入频道的授权流程设计的,必然会限制仅显示用户管理的频道并提示添加机器人。要和@username_to_id_bot功能完全一致,可采用两种无需机器人加入频道的方案:
- 让用户转发目标频道的任意一条消息给机器人
- 让用户输入目标频道的用户名(格式如
@channel_username)
这两种方式仅要求用户能访问目标频道,无需管理员权限,也不需要机器人加入频道。
具体实现(基于telegram-bot-api/v5)
1. 发送带普通按钮的菜单消息
用ReplyKeyboardMarkup创建普通回复键盘,替代inline键盘:
package main import ( "fmt" "strings" tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" ) func main() { bot, err := tgbotapi.NewBotAPI("你的机器人Token") if err != nil { panic(err) } bot.Debug = true updateConfig := tgbotapi.NewUpdate(0) updateConfig.Timeout = 60 updates := bot.GetUpdatesChan(updateConfig) for update := range updates { if update.Message == nil { continue } // 触发/start时显示功能菜单 if update.Message.IsCommand() && update.Message.Command() == "start" { // 构造普通回复键盘 replyKeyboard := tgbotapi.NewReplyKeyboard( tgbotapi.NewKeyboardButtonRow( tgbotapi.NewKeyboardButton("转发频道消息获取ID"), tgbotapi.NewKeyboardButton("输入频道用户名获取ID"), ), ) replyKeyboard.OneTimeKeyboard = true // 点击后自动隐藏键盘 msg := tgbotapi.NewMessage(update.Message.Chat.ID, "请选择获取频道ID的方式:") msg.ReplyMarkup = replyKeyboard bot.Send(msg) continue } // 处理用户转发的频道消息 if update.Message.ForwardFromChat != nil { chatInfo := update.Message.ForwardFromChat resultText := fmt.Sprintf("频道ID:`%d`\n频道用户名:@%s", chatInfo.ID, chatInfo.UserName) msg := tgbotapi.NewMessage(update.Message.Chat.ID, resultText) msg.ParseMode = "MarkdownV2" bot.Send(msg) continue } // 处理用户输入的频道用户名 inputText := update.Message.Text if strings.HasPrefix(inputText, "@") { // 调用GetChat接口获取频道信息 chatConfig := tgbotapi.ChatConfig{ChatID: inputText} chatInfo, err := bot.GetChat(chatConfig) if err != nil { bot.Send(tgbotapi.NewMessage(update.Message.Chat.ID, "无法获取该频道信息,请确认用户名正确且你有权访问")) continue } resultText := fmt.Sprintf("频道ID:`%d`\n频道用户名:@%s", chatInfo.ID, chatInfo.UserName) msg := tgbotapi.NewMessage(update.Message.Chat.ID, resultText) msg.ParseMode = "MarkdownV2" bot.Send(msg) } } }
2. 关键细节说明
- 普通按钮实现:使用
ReplyKeyboardMarkup创建普通键盘,设置OneTimeKeyboard为true可让用户点击后自动隐藏键盘,优化交互体验。 - 转发消息取ID:用户转发频道消息时,
update.Message.ForwardFromChat会直接携带频道的完整信息,无需额外API调用即可提取ID。 - 用户名查询取ID:调用
GetChat接口传入带@前缀的频道用户名,Telegram会返回频道信息(包括ID),只要用户能访问该频道就能成功获取。 - 权限兼容:两种方案都不需要机器人加入频道,也不要求用户是频道管理员,完全匹配目标机器人的功能逻辑。
注意事项
- 确保机器人Token默认拥有
getChat权限(新建机器人均默认具备)。 - 需处理
GetChat的错误场景,比如用户名无效、私有频道无访问权限等,返回友好提示。
内容的提问来源于stack exchange,提问作者Wadjet
相关产品推荐
相关产品推荐

