Search code examples
pythonpython-3.xtelegramtelegram-botpython-telegram-bot

How to run separate instances of a Python Telegram Bot?


Currently, I have created a Python bot with buttons that can be pressed to add orders to a list of orders, as shown below:

Sample of the Telebot's Buttons and the List

My bot is in separate chat groups, Chat 1 and Chat 2. When I press a button to add the order in Chat 1, the order is also added in Chat 2.

How do I separate the instances of the bot such that adding orders in Chat 1 does not affect the order list of Chat 2?

Code for the data:

def button(update: Update, _: CallbackContext) -> None:
query = update.callback_query
query.answer()
result = ""
keyboard = []

if str(query.data) == 'macs':
    keyboard = [
    [InlineKeyboardButton("Filet o Fish", callback_data='fof')],
    [InlineKeyboardButton("Big Mac", callback_data='bm')],
    [InlineKeyboardButton("Back", callback_data='back')]
]
elif str(query.data) in ('ameens', 'Maggi Pattaya', 'Garlic Naan'):
    keyboard = [
    [InlineKeyboardButton("Maggi Pattaya", callback_data='Maggi Pattaya')],
    [InlineKeyboardButton("Garlic Naan", callback_data='Garlic Naan')],
    [InlineKeyboardButton("Back", callback_data='back')]
]
    if str(query.data) in ('Maggi Pattaya', 'Garlic Naan'):
        order_list.append(str(query.data))
        for order in order_list:
            result += '\n' + order

elif str(query.data) == 'back':
    keyboard = [
    [InlineKeyboardButton("Ameen's", callback_data='ameens')],
    [InlineKeyboardButton("Macs", callback_data='macs')]
] 
    if len(order_list) != 0:
        for order in order_list:
            result += '\n' + order
else:
    order_list.append(str(query.data))
    for order in order_list:
        result += order

reply_markup = InlineKeyboardMarkup(keyboard)

if str(query.data) == 'back':
    query.edit_message_text(text="Where would you like to order from?", reply_markup = reply_markup)
else: 
    #query.edit_message_text(text=f"Menu from {query.data}", reply_markup = reply_markup)
    query.edit_message_text(text=f"Orders: {result}", reply_markup = reply_markup)

Solution

  • The general problem is that you store things in order_list which appears to be some kind of global variable. Vad Sims answer already gives the important hint that you should store data on a per chat basis to distinguish between data stored for chat 1 and data stored for chat 2. As you're using the python-telegram-bot library, I suggest to use the built-in feature context.chat_data. Please have a look at this wiki page for more details.


    Disclaimer: I'm currently the maintainer of python-telgeram-bot.