0

This is my First Question on Stack Overflow, so please forgive me if I am asking something that is previously asked, But I need help in creation of a Telegram Bot using Python and libraries like (python-telegram-bot).

I looked through @gamee (Gaming Bot on Telegram) and was trying to make something similar, displaying customized ReplyKeyboardButtons in the form of a Gaming Menu like @gamee. Unfortunately I could only create the Static Buttons and cannot find / understand about CallbackQuery for the functioning of each of them like Transitioning from Main-Menu to Categories via the Category Button through the API Documentation.

[1]: So this is How My Main Menu Looks (ReplyKeyboardMarkup) https://i.sstatic.net/j7Tel.png

[2]: And this is what I want to Transition It via CATEGORIES https://i.sstatic.net/c5NFA.png

So Far I have displayed The Second Menu Image using the CommandHandler Function but I am unable to link it via CallbackQuery (I am aware of .answer() function but cannot Process how to use it).

from telegram import *
from telegram.ext import *
import requests, logging
from keys import API_KEY


# Display ReplyMarkup Keyboard for Start Menu
def games_main_menu(update, context):
    keyboard = [
      [KeyboardButton("Play Solo 👤", callback_data=""), KeyboardButton("Play With Friends 👥", callback_data="")],
      [KeyboardButton("CATEGORIES 🎮", callback_data="cat_button"), KeyboardButton("TRENDING LIST ⚡️", callback_data="trend_button")],
      [KeyboardButton("LAST PLAYED GAMES 🔄", callback_data="prev_played_button"), KeyboardButton("JOIN CHANNEL 🤑", url="")],
      [KeyboardButton("CONTACT SUPPORT 🛠", callback_data="")]
    ]
    reply_markup = ReplyKeyboardMarkup(keyboard, resize_keyboard=True)
    context.bot.send_message(chat_id = update.message.chat_id, text = """Alright 🏁 
How Would You Like to Begin: """, reply_markup = reply_markup)



# Display different Categories of Games Available to Play
def cat_list(update, context):
    keyboard = [
        [KeyboardButton("ACTION 🦹🏼‍♀️", callback_data=""), KeyboardButton("ADVENTURE ⛰", callback_data="")],
        [KeyboardButton("BOARD 🧩", callback_data=""), KeyboardButton("CARD 🃏", callback_data="")],
        [KeyboardButton("COMPETITIVE 🏆", callback_data=""), KeyboardButton("CASUAL 👨‍👩‍👦‍👦", callback_data="")],
        [KeyboardButton("GAMBLE 🎰", callback_data=""), KeyboardButton("PUZZLE 🤔", callback_data="")],
        [KeyboardButton("RACING 🏎", callback_data=""), KeyboardButton("SIMULATION 🚜", callback_data="")],
        [KeyboardButton("SPORT 🎳", callback_data=""), KeyboardButton("TRIVIA ❔", callback_data="")],
        [KeyboardButton("MAIN MENU 🔙", callback_data=games_main_menu)]
    ]
    reply_markup = ReplyKeyboardMarkup(keyboard, resize_keyboard=True)
    context.bot.send_message(chat_id=update.message.chat_id, text="""What Games Do You Like? 😍""", reply_markup=reply_markup)





# List the Commands Offered by Bot for the Users
def help_command(update, context):
    update.effective_chat.send_message("""List of Commands for your Guidance:
/start -> Verify Users for Gaming World
/games -> Enter Gaming World
/help -> Display Help Menu""")






if __name__ == '__main__':
    updater = Updater(token=API_KEY, use_context=True)
    dispatcher = updater.dispatcher

    dispatcher.add_handler(CommandHandler("games", games_main_menu))
    dispatcher.add_handler(CommandHandler("category", cat_list))

    updater.start_polling()
    updater.idle() 

These are just some parts relevant to my question and I assume there still might be things that I am doing wrong, or still do not understand why I have used them. Hence, any kind of help is highly appreciated !!

1 Answer 1

1

I would try without the written commands, like /help and /categories, and do everything with InlineKeyboardButton.

I just wrote this for you, so you have a template and something to start with:

import telegram
from telegram.ext import Updater, CommandHandler, ConversationHandler, CallbackQueryHandler, CallbackContext, PicklePersistence
from telegram import InlineKeyboardMarkup, InlineKeyboardButton, Update
import requests, logging
from keys import API_KEY

logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
                     level=logging.DEBUG)

#Buttons
b1 = "Play Solo 👤"
b2 = "CATEGORIES 🎮"
b3 = "LAST PLAYED GAMES 🔄"
b4 = "JOIN CHANNEL 🤑"
b5 = "Play With Friends 👥"
b6 = "TRENDING LIST ⚡️"
b7 = "CONTACT SUPPORT 🛠"
b8 = "ACTION 🦹🏼‍♀️"
b9 = "ADVENTURE ⛰"
b10 = "BOARD 🧩"
b11 = "CARD 🃏"
b12 = "COMPETITIVE 🏆"
b13 = "CASUAL 👨‍👩‍👦‍👦"
b14 = "GAMBLE 🎰"
b15 = "PUZZLE 🤔"
b16 = "RACING 🏎"
b17 = "SIMULATION 🚜"
b18 = "SPORT 🎳"
b19 = "TRIVIA ❔"
b20 = "MAIN MENU 🔙"

#States
LEVEL1, LEVEL2 = range(2)

#Menus
SOLO, CATEGORY, LAST_PLAYED, JOIN, FRIENDS, TRENDING, SUPPORT = range(7)

ACTION, ADVENTURE, BOARD, CARD, COMPETITIVE, CASUAL, GAMBLE, PUZZLE, RACING, SIMULATION, SPORT, TRIVIA, BACK = range(13)

def games_main_menu(update: Update, context: CallbackContext):
   global userId
   userId = str(update.message.from_user.username)
   update.message.reply_text("WELCOME *{}*.\nEnjoy your time here!\n".format(userId.upper()), parse_mode=telegram.ParseMode.MARKDOWN)
   button1 = InlineKeyboardButton(
        b1, callback_data=str(SOLO)
   )
   button2 = InlineKeyboardButton(
        b2, callback_data=str(CATEGORY)
   )
   button3 = InlineKeyboardButton(
        b3, callback_data=str(LAST_PLAYED)
   )
   button4 = InlineKeyboardButton(
        b4, callback_data=str(JOIN)
   )
   button5 = InlineKeyboardButton(
        b5, callback_data=str(FRIENDS)
   )
   button6 = InlineKeyboardButton(
        b6, callback_data=str(TRENDING)
   )
   button7 = InlineKeyboardButton(
        b7, callback_data=str(SUPPORT)
   )

   message = "Alright 🏁.\nHow Would You Like to Begin: "

   update.message.reply_text(
            text = message, parse_mode=telegram.ParseMode.MARKDOWN,
            reply_markup = InlineKeyboardMarkup([
                [button1, button2],
                [button3, button4],
                [button5, button6],
                [button7]
            ])
        )
   return LEVEL2

def start_over(update: Update, context: CallbackContext):
   query = update.callback_query
   query.answer()
   button1 = InlineKeyboardButton(
        b1, callback_data=str(SOLO)
   )
   button2 = InlineKeyboardButton(
        b2, callback_data=str(CATEGORY)
   )
   button3 = InlineKeyboardButton(
        b3, callback_data=str(LAST_PLAYED)
   )
   button4 = InlineKeyboardButton(
        b4, callback_data=str(JOIN)
   )
   button5 = InlineKeyboardButton(
        b5, callback_data=str(FRIENDS)
   )
   button6 = InlineKeyboardButton(
        b6, callback_data=str(TRENDING)
   )
   button7 = InlineKeyboardButton(
        b7, callback_data=str(SUPPORT)
   )

   message = "Alright 🏁.\nHow Would You Like to Begin: "
   query.edit_message_text(
            text = message, parse_mode=telegram.ParseMode.MARKDOWN,
            reply_markup = InlineKeyboardMarkup([
                [button1, button2],
                [button3, button4],
                [button5, button6],
                [button7]
            ])
        )
   return LEVEL2


# Display different Categories of Games Available to Play
def cat_list(update: Update, context: CallbackContext):
   query = update.callback_query
   query.answer()
   button8 = InlineKeyboardButton(
       b8, callback_data=str(ACTION)
   )
   button9 = InlineKeyboardButton(
       b9, callback_data=str(ADVENTURE)
   )
   button10 = InlineKeyboardButton(
       b10, callback_data=str(BOARD)
   )
   button11 = InlineKeyboardButton(
       b11, callback_data=str(CARD)
   )
   button12 = InlineKeyboardButton(
       b12, callback_data=str(COMPETITIVE)
   )
   button13 = InlineKeyboardButton(
       b13, callback_data=str(CASUAL)
   )
   button14 = InlineKeyboardButton(
       b14, callback_data=str(GAMBLE)
   )
   button15 = InlineKeyboardButton(
       b15, callback_data=str(PUZZLE)
   )
   button16 = InlineKeyboardButton(
       b16, callback_data=str(RACING)
   )
   button17 = InlineKeyboardButton(
       b17, callback_data=str(SIMULATION)
   )
   button18 = InlineKeyboardButton(
       b18, callback_data=str(SPORT)
   )
   button19 = InlineKeyboardButton(
       b19, callback_data=str(TRIVIA)
   )
   button20 = InlineKeyboardButton(
       b20, callback_data=str(BACK)
   )

   message = "What Games Do You Like? 😍" 
   query.edit_message_text(
    text= message, parse_mode=telegram.ParseMode.MARKDOWN_V2,
    reply_markup = InlineKeyboardMarkup([
        [button8, button9, button10],
        [button11, button12, button13],
        [button14, button15, button16],
        [button17, button18, button19],
        [button20]
        ])
    )
   return LEVEL2
def solo(update: Update, context: CallbackContext):
   query = update.callback_query
   query.answer()
   button20 = InlineKeyboardButton(
      b20, callback_data=str(BACK)
   )
   message = "Solo playing"
   query.edit_message_text(
    text= message, parse_mode=telegram.ParseMode.MARKDOWN_V2,
    reply_markup = InlineKeyboardMarkup([
        [button20]
        ])
    )
   return LEVEL1

def last_played(update: Update, context: CallbackContext):
   query = update.callback_query
   query.answer()
   button20 = InlineKeyboardButton(
      b20, callback_data=str(BACK)
   )
   message = "Last Played"
   query.edit_message_text(
    text= message, parse_mode=telegram.ParseMode.MARKDOWN_V2,
    reply_markup = InlineKeyboardMarkup([
        [button20]
        ])
    )
   return LEVEL1


def join(update: Update, context: CallbackContext):
   query = update.callback_query
   query.answer()
   button20 = InlineKeyboardButton(
      b20, callback_data=str(BACK)
   )
   message = "Join"
   query.edit_message_text(
    text= message, parse_mode=telegram.ParseMode.MARKDOWN_V2,
    reply_markup = InlineKeyboardMarkup([
        [button20]
        ])
    )
   return LEVEL1


def friends(update: Update, context: CallbackContext):
   query = update.callback_query
   query.answer()
   button20 = InlineKeyboardButton(
      b20, callback_data=str(BACK)
   )
   message = "Friends"
   query.edit_message_text(
    text= message, parse_mode=telegram.ParseMode.MARKDOWN_V2,
    reply_markup = InlineKeyboardMarkup([
        [button20]
        ])
    )
   return LEVEL1


def trending(update: Update, context: CallbackContext):
   query = update.callback_query
   query.answer()
   button20 = InlineKeyboardButton(
      b20, callback_data=str(BACK)
   )
   message = "Trending"
   query.edit_message_text(
    text= message, parse_mode=telegram.ParseMode.MARKDOWN_V2,
    reply_markup = InlineKeyboardMarkup([
        [button20]
        ])
    )
   return LEVEL1


def support(update: Update, context: CallbackContext):
   query = update.callback_query
   query.answer()
   button20 = InlineKeyboardButton(
      b20, callback_data=str(BACK)
   )
   message = "Support"
   query.edit_message_text(
    text= message, parse_mode=telegram.ParseMode.MARKDOWN_V2,
    reply_markup = InlineKeyboardMarkup([
        [button20]
        ])
    )
   return LEVEL1




if __name__ == '__main__':
   updater = Updater(token=API_KEY, use_context=True)
   dispatcher = updater.dispatcher
   
   conv_handler = ConversationHandler(
      entry_points=[CommandHandler('start', games_main_menu)],
      states={
         LEVEL1: [
            CallbackQueryHandler(start_over, pattern=str(BACK))
         ],
         LEVEL2: [
            CallbackQueryHandler(start_over, pattern=str(BACK)),
            CallbackQueryHandler(cat_list, pattern=str(CATEGORY)),
            CallbackQueryHandler(last_played, pattern=str(LAST_PLAYED)),
            CallbackQueryHandler(friends, pattern=str(FRIENDS)),
            CallbackQueryHandler(join, pattern=str(JOIN)),
            CallbackQueryHandler(trending, pattern=str(TRENDING)),
            CallbackQueryHandler(support, pattern=str(SUPPORT)),
            CallbackQueryHandler(solo, pattern=str(SOLO)),
         ],
      },
      fallbacks=[CommandHandler('start_over', start_over)],
      allow_reentry=True,
   )
   
   dispatcher.add_handler(conv_handler)
   dispatcher.add_handler(CommandHandler('start', start_over))

   updater.start_polling()
   updater.idle() 

Now you just have to create the functions for every button. I created some for your main menu buttons, but they only send a message to the user, they can do whatever you want. If you want to create more nested menus, like another menu coming out from your "Trending list" for example, just add another STATE, like LEVEL3 to the list of states:

#States
LEVEL1, LEVEL2, LEVEL3 = range(3)
states={
         LEVEL1: [
            CallbackQueryHandler(start_over, pattern=str(BACK))
         ],
         LEVEL2: [
            CallbackQueryHandler(start_over, pattern=str(BACK)),
            CallbackQueryHandler(cat_list, pattern=str(CATEGORY)),
            CallbackQueryHandler(last_played, pattern=str(LAST_PLAYED)),
            CallbackQueryHandler(friends, pattern=str(FRIENDS)),
            CallbackQueryHandler(join, pattern=str(JOIN)),
            CallbackQueryHandler(trending, pattern=str(TRENDING)),
            CallbackQueryHandler(support, pattern=str(SUPPORT)),
            CallbackQueryHandler(solo, pattern=str(SOLO)),
         ],
         LEVEL3: [
            CallbackQueryHandles("YOUR_FUNCTION", pattern=str(WHATEVER)),
         ],
      },
      fallbacks=[CommandHandler('start_over', start_over)],
      allow_reentry=True,
   )

the new buttons, to the button lists:

#Buttons
b1 = "Play Solo 👤"
b2 = "CATEGORIES 🎮"
b3 = "LAST PLAYED GAMES 🔄"
...
b21 = "NEW Button"

and do the same I did for creating the categories menu in the main() function.

It would look something like this or this

Sign up to request clarification or add additional context in comments.

1 Comment

Hey @damiasroca, Thankyou for your wonderful efforts. I will surely look through your provided code and try my best in making the menu buttons functional. Apart from the InlineKeyboardButton, is there no other way to perform similar operations on ReplyKeyboardButtons !?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.