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

CentOS7下Python3.8开发Telegram商店机器人遇NameError求助

问题解决
  • 错误原因:你写的if name == '__main__':里的name是错误写法,Python中判断脚本是否作为主程序运行的内置变量是__name__(前后各两个下划线),缺少下划线导致变量未定义,触发NameError。

  • 修正后的代码:

from telegram.ext import Updater, CommandHandler, MessageHandler, Filters

TOKEN = '***'

def start(update, context):
    message = f"Hello {update.message.from_user.first_name}, welcome to our shop! Please select a product from the list:\n"
    message += "1. Product 1\n"
    message += "2. Product 2\n"
    message += "3. Product 3\n"
    message += "4. Product 4\n"
    message += "5. Product 5\n"
    context.bot.send_message(chat_id=update.effective_chat.id, text=message)

def echo(update, context):
    context.bot.send_message(chat_id=update.effective_chat.id, text=update.message.text)

if __name__ == '__main__':
    updater = Updater(TOKEN, use_context=True)
    dp = updater.dispatcher
    dp.add_handler(CommandHandler('start', start))
    dp.add_handler(MessageHandler(Filters.text & (~Filters.command), echo))
    updater.start_polling()
    updater.idle()
  • 验证方法:修改代码后重新执行python3 bot.py,即可正常运行机器人。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 22:27:02