I am trying to build a telegram bot to play games for my son. Basically, I want to get a response from the bot by using a command handler. when I request a command handler it should give me a random response from 2 different lists.
The game is predicting food dish name like "apple pie", apple will be in list 1 and pie will be in list 2 and the bot should get different values from the list and give a response as one message via command handler.
Will appreciate your guidance/help
Below is the python code:
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()
In this code you use a function called shuffleDish()
that creates a string containing two random words chosen from separated list and it's called from the commandhandler "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()