Невозможно для бота Telegram Telegram выполнять команды и пользовательский вебхук вместеPython

Программы на Python
Ответить
Anonymous
 Невозможно для бота Telegram Telegram выполнять команды и пользовательский вебхук вместе

Сообщение Anonymous »

Уже несколько дней пытаюсь устранить эту неполадку, но безуспешно. В приведенном ниже коде бот Telegram должен выполнять команду mint/process/start, а также прослушивать Webhooks. Эти команды работали нормально, пока я не добавил сервер Flask для прослушивания веб-перехватчиков. Кто-нибудь может помочь?

Код: Выделить всё

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"Order ID:[/b] {update.order_id}\n"[b]        f"Status:[/b] {update.status}\n"[b]        f"Created At:[/b] {update.created_at}\n"[b]        f"Blockchain Tx Hash:[/b] {update.transaction_hash or 'N/A'}\n"[b]        f"Intent ID:[/b] {update.intent_id}\n"[b]        f"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())
Попробовал удалить Flask Webhook — команды Telgram работают нормально. После добавления сервера Flask в приведенный выше код команды теперь не отвечают. Ссылается на пример кода из Telegram для приведенного выше фрагмента:
https://docs.python-telegram-bot.org/en ... okbot.html

Подробнее здесь: https://stackoverflow.com/questions/790 ... k-together
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Python»