【发布时间】:2019-08-11 21:01:31
【问题描述】:
我用python-telegram-bot 库在python 中编写了一个简单的电报机器人,它滚动一个n 面骰子并将结果返回给用户。
我的代码:
# Let's make a dice bot
import random
import time
from telegram.ext import Updater,CommandHandler,MessageHandler, Filters
from telegram import Update
updater = Updater(token='MY-TOKEN', use_context=True)
dispatcher = updater.dispatcher
# relevant function here:
def dice_roll(sides):
roll = random.randint(1,sides)
return roll
def dice(update, context):
result = dice_roll(int(context.args[0]))
lucky_dice = "You rolled a "+str(result)
context.bot.send_message(chat_id=update.message.chat_id, text=lucky_dice)
dice_handler = CommandHandler('rollDice', dice)
dispatcher.add_handler(dice_handler)
# Polling function here:
updater.start_polling(clean=True)
我想改进的地方
我现在不太喜欢用户与机器人交互的方式。要掷骰子,用户必须在命令参数中定义骰子的面数,如下所示:
$user: /rollDice 6
$bot: You rolled a 5
这并不是真正的用户友好,如果用户在参数中添加任何其他内容或只是忘记,它也容易出错。
相反,我希望机器人明确要求用户输入,如下所示:
$user: /rollDice
$bot: Please enter the number of sides, the die should have
$user: 6
$bot: You rolled a 5
我查看了force_reply,但我的主要问题是我不知道如何在处理函数中访问新的更新/消息。
如果我尝试这样的事情:
def dice(update, context):
context.bot.send_message(chat_id=update.message.chat_id, text="Please enter the number of sides, the die should have") # new line
result = dice_roll(int(context.args[0]))
lucky_dice = "You rolled a "+str(result)
context.bot.send_message(chat_id=update.message.chat_id, text=lucky_dice)
dice_handler = CommandHandler('rollDice', dice)
dispatcher.add_handler(dice_handler)
它并没有真正起作用,因为 a) 机器人并没有真正给用户时间回复(在这里添加 sleepstatement 似乎非常错误)并且 b) 它引用了原始的“命令消息”而不是在此期间发送的任何新消息。
感谢任何帮助。
【问题讨论】:
标签: python python-telegram-bot