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

Telegram Bot执行命令时报错:TypeError: start()缺少job_queue参数

问题原因与修复方案

核心错误原因

你遇到的TypeError: start() missing 1 required positional argument: 'job_queue',是因为注册/start命令的CommandHandler没有开启pass_job_queue=True,导致Dispatcher调用start函数时无法传入job_queue参数。此外代码还有几处小问题会导致后续功能异常,一起修复如下:

具体修改点

  • 修复start命令的Handler配置:给start_handler添加pass_job_queue=True,让Dispatcher自动传入job_queue参数
  • 修复tasking函数的参数:job_queue.run_repeating会给回调函数传递一个Job实例,所以tasking需要接收这个参数
  • 修正echo函数的状态访问方式:用户数据是字典,要用user['status']代替user.status(字典不能用点语法访问键)
  • 修正echo函数的message_count判断逻辑:原来的message_count参数没有来源,应该用用户字典里的user['message_count']来判断

修改后的完整代码

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

logging.basicConfig(
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    level=logging.INFO)

logger = logging.getLogger(__name__)

users = {}


def start(bot, update, job_queue):
    logging.info("Received start!")
    chat_id = update.message.chat_id
    users[chat_id] = {
        'name': update.message.from_user.first_name,
        'status': 'idle',
        'tasks': list(),
        'schedule': 12,
        'message_count': 0}
    job_queue.run_repeating(tasking, 120)
    bot.send_message(
        chat_id=update.message.chat_id,
        text="Welcome! Please *do* talk to me, _F E L L O W \_ H U M A N_")


def tasking(job):  # 添加job参数
    pass


def schedule(bot, update, args, job_queue, chat_data):
    try:
        hour = int(args[0])
        bot.send_message(
            chat_id=update.message.chat_id,
            text="I'll contact you every day at {0} to decide".format(hour))
    except (IndexError, ValueError):
        bot.send_message(
            chat_id=update.message.chat_id,
            text="Usage /schedule <hour-of-day>")


def add_task(bot, update, args):
    try:
        if len(args) == 0:
            raise IndexError
        task = " ".join(args)
        user = users[update.message.chat_id]
        user['tasks'].append(task)
        bot.send_message(
            chat_id=update.message.chat_id,
            text="Added {}".format(task))
    except (IndexError):
        bot.send_message(
            chat_id=update.message.chat_id,
            text="Usage /add <task>")


def decide(bot, update, job_queue, chat_data):
    try:
        job = job_queue

    except (IndexError):
        bot.send_message(
            chat_id=update.message.chat_id,
            text="Usage /decide")


def echo(bot, update):  # 移除多余的message_count参数
    try:
        logger.info("Received message!")
        chat_id = update.message.chat_id
        if chat_id is None:
            return
        user = users.get(chat_id)
        if user is None:
            users[chat_id] = user = {
                'name': update.message.from_user.first_name,
                'status': 'idle',
                'tasks': list(),
                'schedule': 12,
                'message_count': 0}
        if user['status'] == 'idle':  # 改用字典键访问
            user['status'] = 'talking'
            if user['message_count'] == 0:  # 使用用户字典里的message_count
                bot.send_message(
                    chat_id=chat_id,
                    text=u"Welcome {name}! I'm going to be your assistant".format(**user))
                bot.send_message(
                    chat_id=chat_id,
                    text=u"How can I help you today?",
                    reply_markup=ReplyKeyboardMarkup(
                        [["Add task"], ["Nevermind"]], one_time_keyboard=True))
            user['message_count'] += 1
            return
        elif user['status'] == 'talking':  # 改用字典键访问
            if update.message.text.lower() == "add tasks":
                user['status'] = 'adding_task'
                bot.send_message(
                    chat_id=chat_id,
                    text=u"Let's add a task. What are your plans?")
        elif user['status'] == 'adding_task':  # 改用字典键访问
            if update.message.text.strip().lower() == "stop":
                user['status'] = 'talking'
                bot.send_message(
                    chat_id=chat_id,
                    text=u"Fair enough. Now what?",
                    reply_markup=ReplyKeyboardMarkup(
                        [["Add task"], ["Nevermind"]], one_time_keyboard=True))
            else:
                user['tasks'].append(update.message.text)
                bot.send_message(
                    chat_id=chat_id,
                    text=u"Done. To stop adding plans please say 'stop'")
    except Exception as exc:
        logger.error(exc)
        bot.send_message(chat_id=chat_id, text=u"Oops!")


updater = Updater(token='5410368947:AAGWC-iBwdSTkVBsT31oi1nqiewPlTzb7m0')
dispatcher = updater.dispatcher

# 给start_handler添加pass_job_queue=True
start_handler = CommandHandler('start', start, pass_job_queue=True)
task_handler = CommandHandler('add', add_task, pass_args=True)
schedule_handler = CommandHandler(
    'schedule', schedule, pass_args=True,
    pass_job_queue=True, pass_chat_data=True)
daily_handler = CommandHandler(
    'daily', decide, pass_job_queue=True, pass_chat_data=True)
echo_handler = MessageHandler(Filters.text, echo)

dispatcher.add_handler(start_handler)
dispatcher.add_handler(task_handler)
dispatcher.add_handler(schedule_handler)
dispatcher.add_handler(daily_handler)
dispatcher.add_handler(echo_handler)

if __name__ == '__main__':
    logger.info("Starting app")
    updater.start_polling()
    updater.idle()
    logger.info("Stopping app")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 19:24:10