You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用TeleBot API获取Telegram群聊成员遇报错,求解决方案

问题解决方法

第一个错误:AttributeError: 'TeleBot' object has no attribute 'get_chat_members'

你使用的pyTelegramBotAPI库中不存在无参的get_chat_members方法。Telegram API限制单次最多获取200个群成员,正确获取成员的方法是get_chat_members(chat_id, offset, limit),必须传入偏移量和数量参数来分页获取。

第二个错误:400 Bad Request: invalid user_id specified

这个错误是因为传入的chat_id格式错误:群聊的ID是负数(格式为-100xxxxxx),如果你的chat_id是正数,说明获取的是私聊ID而非群聊ID。可以先打印message.chat.id确认格式,确保是群聊的负数ID。

完整实现代码示例

import telebot

bot = telebot.TeleBot("你的机器人Token")

@bot.message_handler(commands=['call'])
def call_all_members(message):
    chat_id = message.chat.id
    # 验证是否为群聊
    if chat_id > 0:
        bot.reply_to(message, "此命令仅支持群聊使用")
        return
    
    all_members = []
    offset = 0
    limit = 200  # Telegram API单次最多返回200个成员
    
    while True:
        try:
            members = bot.get_chat_members(chat_id, offset, limit)
            if not members:
                break
            all_members.extend(members)
            offset += limit
        except Exception as e:
            print(f"获取成员失败: {e}")
            break
    
    # 构造提及消息(超级群可提及所有成员,普通群仅能提及在线成员)
    mention_content = "召唤全体成员:\n"
    for member in all_members:
        mention_content += f"[{member.user.first_name}](tg://user?id={member.user.id}) "
    
    bot.send_message(chat_id, mention_content, parse_mode='Markdown')

bot.polling()

关键注意事项

  • 机器人必须是群聊成员,且拥有查看成员列表的权限,否则会触发API权限错误。
  • 普通群聊中,机器人只能提及在线成员;超级群支持提及所有成员,包括离线用户。
  • 成员数量较多时,分页请求需注意频率,避免触发Telegram API限流机制。

内容的提问来源于stack exchange,提问作者Lemonnik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 13:03:35