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

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:普通文本消息处理逻辑配置错误
    1. 普通文本不能用CommandHandler,该类仅用于处理/开头的命令,需要改用MessageHandler
    2. 你误将处理函数写为了start_command,实际应该调用你定义的handle_command
    3. 需要添加过滤条件排除命令消息,避免和前面的/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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 17:12:03