1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Python] Unable for python telegram bot to execute commands and custom Webhook together

Discussão em 'Python' iniciado por Stack, Outubro 8, 2024.

  1. Stack

    Stack Membro Participativo

    trying to troubleshoot this for days and failing. The code below should have the telegram bot execute mint/process/start command, while also listening to Webhooks. These commands were working fine until I added the Flask server to listen to Webhooks. Can anyone please help?


    import asyncio
    import logging
    import os
    from dataclasses import dataclass
    from http import HTTPStatus

    import uvicorn
    from asgiref.wsgi import WsgiToAsgi
    from flask import Flask, Response, abort, request

    from telegram import Update
    from telegram.ext import (
    Application,
    CommandHandler,
    ContextTypes,
    CallbackContext
    )

    # Import your existing functions for Acme
    from acme.setWebHook import set_acme_webhook # Import the function to set Acme webhook
    from commands.mintLoyaltyCard import mint # Import the mint command handler
    from commands.process import process # Import the process command handler

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

    # Define configuration constants
    URL = os.getenv("REPLIT_APP_URL") # Use the REPLIT_APP_URL environment variable
    ADMIN_CHAT_ID = 123456 # Update this to your actual chat ID
    PORT = 80
    TOKEN = os.getenv("BOT_TOKEN") # Use the BOT_TOKEN environment variable
    if TOKEN is None:
    raise ValueError("BOT_TOKEN environment variable is not set.")

    @dataclass
    class AcmeOrderUpdate:
    """Dataclass to wrap an order update from Acme."""
    order_id: str
    status: str
    created_at: str
    transaction_hash: str
    execution_message: str
    intent_id: str
    user_id: str

    async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    """Display a message with instructions on how to use this bot."""
    if update.message: # Check if update contains a message
    await update.message.reply_html(text="The bot is running and listening to Acme updates.")
    else:
    logger.warning("Received an update without a message.")

    async def handle_acme_order(update: AcmeOrderUpdate, context: ContextTypes.DEFAULT_TYPE) -> None:
    """Handle Acme order updates."""
    logger.info(f"Received Acme order update: {update}")

    text = (
    f"New Acme order update:\n\n"
    f"<b>Order ID:</b> {update.order_id}\n"
    f"<b>Status:</b> {update.status}\n"
    f"<b>Created At:</b> {update.created_at}\n"
    f"<b>Blockchain Tx Hash:</b> {update.transaction_hash or 'N/A'}\n"
    f"<b>Intent ID:</b> {update.intent_id}\n"
    f"<b>User ID:</b> {update.user_id}\n"
    )
    await context.bot.send_message(chat_id=ADMIN_CHAT_ID, text=text, parse_mode="HTML")

    async def main() -> None:
    """Set up PTB application and a web application for handling the incoming requests."""
    application = (
    Application.builder().token(TOKEN).updater(None).build()
    )

    # Register command handlers
    application.add_handler(CommandHandler("start", start))
    application.add_handler(CommandHandler("mint", mint)) # Register the mint command
    application.add_handler(CommandHandler("process", process)) # Register the process command

    # Set the Acme webhook
    set_acme_webhook()

    # Set up webserver to receive updates
    flask_app = Flask(__name__)

    @flask_app.post("/acme-webhook") # type: ignore[misc]
    async def acme_webhook() -> Response:
    """Handle incoming Acme order updates."""
    try:
    data = request.json
    order_data = data.get("Order", {})
    order = AcmeOrderUpdate(
    order_id=order_data.get("id"),
    status=order_data.get("status"),
    created_at=order_data.get("createdAt"),
    transaction_hash=order_data.get("blockchainTransactionHash", None),
    execution_message=order_data.get("executionMessage", None),
    intent_id=order_data.get("intentId"),
    user_id=order_data.get("userId")
    )
    except (KeyError, TypeError, ValueError):
    logger.error("Malformed request data")
    abort(HTTPStatus.BAD_REQUEST, "Invalid order payload.")

    # Place update into application's update queue
    await application.update_queue.put(order)
    await handle_acme_order(order, application.context)
    return Response(status=HTTPStatus.OK)

    @flask_app.get("/") # type: ignore[misc]
    async def health() -> Response:
    """For the health endpoint, reply with a simple plain text message."""
    response = Response("The bot is still running fine :)", status=HTTPStatus.OK, mimetype="text/plain")
    return response

    # Start the Uvicorn webserver
    webserver = uvicorn.Server(
    config=uvicorn.Config(
    app=WsgiToAsgi(flask_app),
    port=PORT,
    use_colors=False,
    host="0.0.0.0",
    )
    )

    # Run the application and webserver together
    async with application:
    await application.start()
    await webserver.serve()
    await application.stop()

    if __name__ == "__main__":
    asyncio.run(main())


    Tried removing the Flask Webhook -- and the Telgram commands fine. After adding the Flask server in the code above, the commands are now non-responsive. Referred to sample code from Telegram for the snippet above:

    https://docs.python-telegram-bot.org/en/stable/examples.customwebhookbot.html

    Continue reading...

Compartilhe esta Página