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
相关产品推荐
相关产品推荐

