我正在尝试使用python创建自己的电报机器人,并从https://github.com/python-telegram-bot/python-telegram-bot/tree/master/examples开始学习示例。我使用了timerbot.py并尝试运行它,但是我做不到。我认为此示例中的代码适用于较旧版本的电报bot API。有人可以告诉我如何更改代码以使其正常工作吗?谢谢!
def start(update, context):
update.message.reply_text('Hi! Use /set <seconds> to set a timer')
def set_timer(update, context):
"""Add a job to the queue."""
chat_id = update.message.chat_id
try:
# args[0] should contain the time for the timer in seconds
due = int(context.args[0])
if due < 0:
update.message.reply_text('Sorry we can not go back to future!')
return
# Add job to queue
job = context.job_queue.run_once(alarm, due, context=chat_id)
context.chat_data['job'] = job
update.message.reply_text('Timer successfully set!')
except (IndexError, ValueError):
update.message.reply_text('Usage: /set <seconds>')
def main():
"""Run bot."""
# Create the Updater and pass it your bot's token.
# Make sure to set use_context=True to use the new context based callbacks
# Post version 12 this will no longer be necessary
updater = Updater("758270241:AAEGBeHzF5neiNRdnXrSirposzh71FID6yk")
# Get the dispatcher to register handlers
dp = updater.dispatcher
# on different commands - answer in Telegram
dp.add_handler(CommandHandler("start", start))
dp.add_handler(CommandHandler("help", start))
dp.add_handler(CommandHandler("set", set_timer,
pass_args=True,
pass_job_queue=True,
pass_chat_data=True))
如果我执行send / start到bot的操作,我会得到:
- telegram.ext.dispatcher - ERROR - An uncaught error was raised while processing the update
Traceback (most recent call last):
File "C:\Users\khrom\AppData\Local\Continuum\anaconda3\lib\site-packages\telegram\ext\dispatcher.py", line 279, in process_update
handler.handle_update(update, self)
File "C:\Users\khrom\AppData\Local\Continuum\anaconda3\lib\site-packages\telegram\ext\commandhandler.py", line 173, in handle_update
return self.callback(dispatcher.bot, update, **optional_args)
File "<ipython-input-5-e9f84220f47b>", line 36, in start
update.message.reply_text('Hi! Use /set <seconds> to set a timer')
AttributeError: 'Bot' object has no attribute 'message'
如果我执行/设置任何数字,那么我得到了:
- telegram.ext.dispatcher - ERROR - An uncaught error was raised while processing the update
Traceback (most recent call last):
File "C:\Users\khrom\AppData\Local\Continuum\anaconda3\lib\site-packages\telegram\ext\dispatcher.py", line 279, in process_update
handler.handle_update(update, self)
File "C:\Users\khrom\AppData\Local\Continuum\anaconda3\lib\site-packages\telegram\ext\commandhandler.py", line 173, in handle_update
return self.callback(dispatcher.bot, update, **optional_args)
TypeError: set_timer() got an unexpected keyword argument 'job_queue'