如何 运行 分离 Python Telegram Bot 的实例?

How to run separate instances of a Python Telegram Bot?

目前,我已经创建了一个 Python 机器人,其中包含可以按下以将订单添加到订单列表的按钮,如下所示:

Sample of the Telebot's Buttons and the List

我的机器人在不同的聊天组中,聊天 1 和聊天 2。当我在聊天 1 中按下按钮添加订单时,订单也会添加到聊天 2 中。

如何分离机器人的实例,以便在聊天 1 中添加订单不会影响聊天 2 的订单列表?

数据代码:

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)

您可以使用此代码:

#!/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()

一般问题是您将内容存储在 order_list 中,这似乎是某种全局变量。 Vad Sims 的回答已经给出了重要提示,即您应该在 每个聊天 的基础上存储数据,以区分为聊天 1 存储的数据和为聊天 2 存储的数据。当您使用 python-telegram-bot 库,我建议使用内置功能 context.chat_data。请查看此 wiki page 了解更多详情。


免责声明:我目前是 python-telgeram-bot.

的维护者