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

TeleBot报错AttributeError:'str'对象无'message_handler'属性

问题分析与解决:Telegram机器人AttributeError错误

错误原因

你创建机器人实例的代码写错了:

bot = telebot.TeleBot = ('api')

这行代码犯了两个致命错误:

  • 把telebot.TeleBot这个类直接赋值成了字符串'api',破坏了类本身的定义
  • 同时bot变量也变成了这个字符串类型的值

字符串对象根本没有message_handler这个属性,所以运行时会抛出AttributeError: 'str' object has no attribute 'message_handler'。另外原代码中函数内部的代码没有正确缩进,也会导致语法错误。

修正后的代码

import telebot  
# 替换成你的真实API令牌,正确创建机器人实例
bot = telebot.TeleBot('你的API令牌') 

@bot.message_handler(content_types=['text'])
def get_text_messages(message):     
    if message.text == "hello":   
        bot.send_message(message.from_user.id, "hello")

bot.polling(none_stop=True, interval=0)

注意:要把'你的API令牌'替换成你从BotFather那里获取的真实令牌。

内容的提问来源于stack exchange,提问作者Данил Бакуров

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 22:54:18