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

创建Telegram Bot时遇NameError: name 'bot' is not defined错误求助

Telegram Bot 报错:NameError: name 'bot' is not defined 解决方法

你遇到的NameError: name 'bot' is not defined错误,根源是代码只导入了telebot库,但未创建bot实例就直接使用bot变量。

修正要点:

  • 必须先用从Telegram BotFather获取的令牌(即你存在环境变量Example中的值)初始化telebot.TeleBot对象,将其赋值给bot变量
  • 原代码中message_handler的参数写错了,应为复数形式commands,而非command,这个错误会导致命令无法被识别触发

修正后的完整代码:

import os
import telebot

my_secret = os.environ['Example']
# 关键步骤:创建Bot实例
bot = telebot.TeleBot(my_secret)

@bot.message_handler(commands=['Greet'])
def greet(message):
  bot.reply_to(message, "Hey! Hows it going?")

bot.polling()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 04:53:15