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

调用daily()时出现缺少必填参数'self'错误的技术求助

问题排查与修复

错误原因分析

出现daily() missing 1 required positional argument: 'self'的核心原因:

  • JobQueue是类,你直接调用了类的run_repeating方法,而这个方法是实例方法,必须通过JobQueue的实例来调用,不能直接用类名调用。否则Python会把调用时的第一个参数当作self(实例本身),但你没传实例,就会报缺失self的错误。
  • 另外你的daily函数参数、callback_verse的参数都不兼容定时任务的回调要求,需要一并调整。

修复步骤与代码

1. 改用bot内置的job_queue实例

python-telegram-bot库中的bot对象已经内置了job_queue实例,直接用它调用run_repeating即可,不需要手动实例化JobQueue。

2. 调整函数参数适配版本

  • 若使用python-telegram-bot v13及以上版本,被@bot.message_handler装饰的函数需要接收update和context两个参数;定时任务的回调函数也需要接收这两个参数。
  • 若使用v12及以下版本,函数参数为bot和update,定时任务回调参数为bot和job。

修复后的完整代码示例(v13+)

import requests
from bs4 import BeautifulSoup as bs
from telegram.ext import Updater, CommandHandler

# 初始化bot(替换成你的token)
updater = Updater(token='你的机器人token', use_context=True)
bot = updater.bot

@bot.message_handler(commands=['remind'])
def callback_verse(update, context):
    chat_id = update.effective_chat.id
    r = requests.get("http://russian-poetry.ru/Random.php").text
    soup = bs(r, "html.parser")
    m = soup.find("title").text
    b = soup.find("pre").text
    msg = m + b
    bot.send_message(chat_id, text=msg, parse_mode='html')

@bot.message_handler(commands=['daily'])
def daily(update, context):
    # 使用bot内置的job_queue实例添加定时任务
    context.job_queue.run_repeating(
        callback=callback_verse, 
        interval=10,  # 推送间隔(单位:秒,按需修改)
        first=0,
        context=update.effective_chat.id
    )
    bot.send_message(update.effective_chat.id, text="每日诗歌推送已启动!")

# 启动机器人
updater.start_polling()
updater.idle()

适配v12及以下版本的代码

import requests
from bs4 import BeautifulSoup as bs
from telegram.ext import Updater, CommandHandler

updater = Updater(token='你的机器人token')
bot = updater.bot

@bot.message_handler(commands=['remind'])
def callback_verse(bot, update):
    chat_id = update.message.chat.id
    r = requests.get("http://russian-poetry.ru/Random.php").text
    soup = bs(r, "html.parser")
    m = soup.find("title").text
    b = soup.find("pre").text
    msg = m + b
    bot.send_message(chat_id, text=msg, parse_mode='html')

@bot.message_handler(commands=['daily'])
def daily(bot, update):
    bot.job_queue.run_repeating(
        callback=callback_verse,
        interval=10,
        first=0,
        context=update.message.chat.id
    )
    bot.send_message(update.message.chat.id, text="每日诗歌推送已启动!")

updater.start_polling()
updater.idle()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 17:53:31