python - 电报游戏机器人
问题描述
我正在尝试构建一个电报机器人来为我的儿子玩游戏。基本上,我想通过使用命令处理程序从机器人获得响应。当我请求命令处理程序时,它应该给我一个来自 2 个不同列表的随机响应。
游戏正在预测像“apple pie”这样的食物名称,apple 将在列表 1 中,而 pie 将在列表 2 中,机器人应该从列表中获取不同的值并通过命令处理程序以一条消息的形式给出响应。
将感谢您的指导/帮助
下面是python代码:
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
from telegram import error, update
import sys
import os
import random
import logging
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
def start(update, context):
"""Send a message when the command /start is issued."""
update.message.reply_text('Hello, play games!')
def shuffle2d(arr2d, rand_list=random):
"""Shuffes entries of 2-d array arr2d, preserving shape."""
reshape = []
data = []
iend = 0
for row in arr2d:
data.extend(row)
istart, iend = iend, iend+len(row)
reshape.append((istart, iend))
rand_list.shuffle(data)
return [data[istart:iend] for (istart,iend) in reshape]
def show(arr2d):
"""Shows rows of matrix (of strings) as space-separated rows."""
show ("\n".join(" ".join(row) for row in arr2d))
A = A.rand_list['APPLE, PUMKIN, STRAWBERRY, BANANA,CHOCOLATE']
B = B.rand_list['PIE, ICE-CREAM, CAKE,SHAKE']
arr2d = []
arr2d.append([A+(j) for j in range(1,B+1)])
show(shuffle2d(arr2d))
print(show)
return show
def play(update, context):
"""Send a message when the command /play is issued."""
update.message.reply_text(shuffle2d)
def main():
"""Start the 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("1XXXXXXX:XXXXXXXXXXXXXXXXXXY", use_context=True)
# 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("play", play))
# on noncommand i.e message - echo the message on Telegram
dp.add_handler(MessageHandler(Filters.text, play))
# Start the Bot
updater.start_polling()
# Run the bot until you press Ctrl-C or the process receives SIGINT,
# SIGTERM or SIGABRT. This should be used most of the time, since
# start_polling() is non-blocking and will stop the bot gracefully.
updater.idle()
if __name__ == '__main__':
main()
解决方案
在此代码中,您使用一个名为的函数,该函数shuffleDish()
创建一个包含从分隔列表中选择的两个随机单词的字符串,并从命令处理程序“play”中调用它
from telegram.ext import Updater, CommandHandler
from telegram import error, update
import random
import logging
logging.basicConfig(level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
def shuffleDish():
A = ['APPLE', 'PUMKIN', 'STRAWBERRY', 'BANANA', 'CHOCOLATE']
B = ['PIE', 'ICE-CREAM', 'CAKE', 'SHAKE']
dish = random.choice(A)+" "+random.choice(B)
return dish
def play(update, context):
update.message.reply_text(shuffleDish())
def error(update, context):
logger.warning('Update "%s" caused error "%s"', update, context.error)
def main():
updater = Updater(tgtoken, use_context=True)
dp = updater.dispatcher
dp.add_handler(CommandHandler("play", play))
dp.add_error_handler(error)
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
推荐阅读
- docker - 如何设置 Dockerfile 以使容器操作系统为 Ubuntu?
- microservices - 微服务中的分布式事务
- python - 在代理后面下载 gensim 模型
- css - 弹出覆盖的标题位置问题
- html - CSS calc() 不适用于 Office 365
- python - 使用 Flask 创建一个在 webapp 上切换语言的 GET 请求
- regex - 正则表达式可选子字符串
- django - Django ManytoManyField 添加功能不起作用
- asp.net-core - Teamcity 混合 .Net Core + .Net 框架解决方案
- mysql - 日期时间的 SQL 请求