Pycharm运行Telegram Bot提示Process finished with exit code 0却自动退出求助
问题排查与修复方案
代码运行后直接退出是三个基础错误共同导致的,逐一修复即可正常运行:
- 错误1:
main()函数调用缩进错误,没有在全局作用域执行
你当前的main()调用写在了def main()的函数内部缩进块中,程序运行时只会执行全局的print("Bot started..."),完全没有触发Bot初始化逻辑,执行完打印语句就直接退出。 - 错误2:调度器获取错误
你写的dp = Updater.dispatcher调用的是Updater类的静态属性,而你需要的是实例化得到的updater对象的调度器,应该改为dp = updater.dispatcher(首字母u小写)。 - 错误3:普通文本消息处理逻辑配置错误
- 普通文本不能用
CommandHandler,该类仅用于处理/开头的命令,需要改用MessageHandler - 你误将处理函数写为了
start_command,实际应该调用你定义的handle_command - 需要添加过滤条件排除命令消息,避免和前面的
/start//help命令冲突
- 普通文本不能用
修复后的完整代码如下:
import Constants as Keys from telegram.ext import * import Responses as R print("Bot started...") def start_command(update, context): update.message.reply_text('Type something to get started!') def help_command(update, context): update.message.reply_text('If you need help you should ask Google!') def handle_command(update, context): text = str(update.message.text).lower() response = R.sample_responses(text) update.message.reply_text(response) def error(update, context): print(f"Update {update} caused error {context.error}") def main(): updater = Updater(Keys.API_KEY, use_context=True) # 修复:取实例化后的updater的dispatcher dp = updater.dispatcher dp.add_handler(CommandHandler("start", start_command)) dp.add_handler(CommandHandler("help", help_command)) # 修复:改用MessageHandler处理普通文本,调用handle_command,排除命令消息 dp.add_handler(MessageHandler(Filters.text & ~Filters.command, handle_command)) dp.add_error_handler(error) updater.start_polling(10) updater.idle() # 修复:main()调用移到全局作用域 if __name__ == '__main__': main()
内容的提问来源于stack exchange,提问作者blackdevil
相关产品推荐
相关产品推荐

