我用python
库在python-telegram-bot
中编写了一个简单的电报机器人,该机器人滚动了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)机器人没有真正给用户时间回复(在此处添加sleep
语句似乎很不正确),并且b)它返回了原始的“命令消息”同时没有发送任何新消息。
感谢您的帮助。
答案 0 :(得分:1)
您可以使用ConversationHandler
来实现此目的,我在我的机器人上使用了类似的代码,该代码询问用户公交车号并回复时间表。大部分代码是从https://codeclimate.com/github/leandrotoledo/python-telegram-bot/examples/conversationbot.py/source
from telegram.ext import (Updater, CommandHandler, RegexHandler, ConversationHandler)
import random
# states
ROLLDICE = range(1)
def start(bot, update):
update.message.reply_text('Please enter the number of sides, the die should have')
return ROLLDICE
def cancel(bot, update):
update.message.reply_text('Bye! I hope we can talk again some day.')
return ConversationHandler.END
def rolldice(bot, update):
roll = random.randint(1, int(update.message.text))
update.message.reply_text('You rolled: ' + str(roll))
return ConversationHandler.END
def main():
updater = Updater(TOKEN)
dp = updater.dispatcher
conv_handler = ConversationHandler(
entry_points=[CommandHandler('start', start)],
states={ROLLDICE: [RegexHandler('^[0-9]+$', rolldice)]},
fallbacks=[CommandHandler('cancel', cancel)]
)
dp.add_handler(conv_handler)
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
输出:
/start
Please enter the number of sides, the die should have
6
You rolled: 2