Code to chat between a Telegram Admin bot and a Telegram user bot does not work

43 Views Asked by At

I've developed a Telegram bot "mini app" that allows users to visit a website and open a "ticket" by entering text to explain their issue. Following this, a message "An admin will arrive soon" is sent to the user through the bot interface, and a Discord message is dispatched via a webhook to notify moderators that a new ticket has been created, including a command in the format /admin_start <user_id>. This is contained within a first file named "Ticket.py".

In a second file named "TelegramChat.py", as described below, the code implements a messaging system between users and administrators using two separate Telegram bots. This code is supposed to support three main functions:

#!/usr/bin/env python
# pylint: disable=unused-argument

from telegram import Update
from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes

# Configuration of bot tokens
USER_BOT_TOKEN = ""
ADMIN_BOT_TOKEN = ""

# Dictionary to track conversations: key = user ID, value = admin ID
conversations = {}

# Initialize applications for user and admin bots
user_bot_app = Application.builder().token(USER_BOT_TOKEN).build()
admin_bot_app = Application.builder().token(ADMIN_BOT_TOKEN).build()

async def admin_start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    """Admin initiates a conversation with a user."""
    if context.args:
        user_id = context.args[0]  # Assuming the command is "/admin_start <user_id>"
        admin_id = update.effective_user.id
        conversations[user_id] = str(admin_id)
        await context.bot.send_message(chat_id=admin_id, text=f"Connected with user {user_id}.")
        await context.bot.send_message(chat_id=user_id, text="An admin has joined the chat.")
    else:
        await update.message.reply_text("Please provide the user ID. Format: /admin_start <user_id>.")

async def handle_user_message(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    """Forward messages from users to their linked admin."""
    user_id = str(update.effective_user.id)
    if user_id in conversations:
        admin_id = conversations[user_id]
        await context.bot.send_message(chat_id=admin_id, text=f"Message from user {user_id}: {update.message.text}")
    else:
        await update.message.reply_text("Please wait, connecting you to an admin...")

async def handle_admin_message(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    """Forward messages from the admin to the linked user."""
    admin_id = str(update.effective_user.id)
    user_ids = [user_id for user_id, admin in conversations.items() if admin == admin_id]
    if user_ids:
        for user_id in user_ids:
            await context.bot.send_message(chat_id=user_id, text=f"Message from admin: {update.message.text}")

# Add handlers to the user bot
user_bot_app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_user_message))

# Add handlers to the admin bot
admin_bot_app.add_handler(CommandHandler("start", admin_start))
admin_bot_app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_admin_message))

if __name__ == "__main__":
    # Run the bots in polling mode
    user_bot_app.run_polling()
    admin_bot_app.run_polling()
  1. For Administrators: A command /admin_start <user_id> allows an administrator to initiate a conversation with a user. The administrator's ID is then recorded in the conversations dictionary with the user's ID as the key.

  2. Messages from Users: When a user sends a message, if a conversation has been established with an administrator (verified in the conversations dictionary), the message is forwarded to that administrator.

  3. Messages from Administrators: When an administrator sends a message, it is forwarded to all users linked to this administrator in the conversations dictionary.

However, the command /admin_start <user_id> does not work and does not allow the initiation of conversation between the user and the admin. I expected that when the admin uses the command "/admin_start <user_id>", a connection would be created allowing the exchange of messages between the admin and the user via Telegram bots. However, nothing happens on the admin side, the user side, or in the logs.

Could anyone help diagnose why the /admin_start <user_id> command isn't initiating the conversation as expected?

Also, to test the code, I created a file named "CombinedBot.py" that combines Ticket.py and TelegramChat.py. I've already had issues of type 'telegram.error.Conflict', but now I no longer have them. The part from "Ticket.py" works correctly, but the chat part does not.

0

There are 0 best solutions below