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

TeleBot报错'list' object has no attribute 'id'(new_chat_members相关)求助

解决TeleBot发送新成员私信时的'list' object has no attribute 'id'错误

错误原因

message.new_chat_members是列表类型(支持多个用户同时入群的场景),你直接调用它的.id属性,而列表本身没有这个属性,所以触发了报错。你已经正确获取了第一个成员的first_name,但发送消息时没对应取该成员的ID。

修正后的代码

import telebot

bot = telebot.TeleBot('你的机器人token')

@bot.message_handler(content_types=["new_chat_members"])
def handler_new_member(message):
    # 遍历所有新入群成员,支持批量进群场景
    for new_member in message.new_chat_members:
        first_name = new_member.first_name
        # 给每个新成员发送私信
        bot.send_message(new_member.id, f"欢迎你,{first_name}!")

bot.infinity_polling()

关键修正点

  • 把message.new_chat_members.id改成new_member.id(如果只处理单个成员,也可以用message.new_chat_members[0].id)
  • 修正字符串格式化:用f-string让占位符替换更直观,确保成员名称能正确显示
  • 增加遍历逻辑,兼容多个用户同时入群的情况

额外注意事项

Telegram机器人无法主动给从未和机器人互动过的用户发私信,要是新成员之前没给机器人发过消息,私信可能发送失败。这种情况可以改成在群组内@成员发送欢迎消息。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 04:45:30