XDPlatypus
XDPlatypus

Reputation: 23

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)

Upvotes: 1

Views: 2273

Answers (2)

CallMeStag
CallMeStag

Reputation: 7060

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.

Upvotes: 3

Vad Sim
Vad Sim

Reputation: 314

You can use this code:

#!/usr/bin/env python
# pylint: disable=C0116
# This program is dedicated to the public domain under the CC0 license.

"""
Basic example for a bot that uses inline keyboards. For an in-depth explanation, check out
 https://git.io/JOmFw.
"""
import logging

from telegram import InlineKeyboardButton, InlineKeyboardMarkup, Update
from telegram.ext import Updater, CommandHandler, CallbackQueryHandler, CallbackContext

logging.basicConfig(
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO
)
logger = logging.getLogger(__name__)

chats = {}


def start(update: Update, _: CallbackContext) -> None:
    if update.message.chat.id not in chats:
        chats[update.message.chat.id] = []
    keyboard = [
        [
            InlineKeyboardButton("Option 1", callback_data='1'),
            InlineKeyboardButton("Option 2", callback_data='2'),
        ],
        [InlineKeyboardButton("Option 3", callback_data='3')],
    ]

    reply_markup = InlineKeyboardMarkup(keyboard)

    txt = ''.join(chats[update.message.chat.id])

    update.message.reply_text(txt, reply_markup=reply_markup)


def button(update: Update, _: CallbackContext) -> None:
    query = update.callback_query

    # CallbackQueries need to be answered, even if no notification to the user is needed
    # Some clients may have trouble otherwise. See https://core.telegram.org/bots/api#callbackquery
    query.answer()
    if query.from_user.id not in chats:
        chats[query.from_user.id] = []
    chats[query.chat.id].append(query.data)

    query.edit_message_text(text=f"Selected option: {query.data}")


def help_command(update: Update, _: CallbackContext) -> None:
    update.message.reply_text("Use /start to test this bot.")


def main() -> None:
    # Create the Updater and pass it your bot's token.
    updater = Updater("TOKEN")

    updater.dispatcher.add_handler(CommandHandler('start', start))
    updater.dispatcher.add_handler(CallbackQueryHandler(button))
    updater.dispatcher.add_handler(CommandHandler('help', help_command))

    # Start the Bot
    updater.start_polling()

    # Run the bot until the user presses Ctrl-C or the process receives SIGINT,
    # SIGTERM or SIGABRT
    updater.idle()


if __name__ == '__main__':
    main()

Upvotes: 0

Related Questions