Discord.py 和 Flask - RuntimeError:超时上下文管理器应该在任务中使用

问题描述 投票:0回答:0

我有一个 Discord 机器人,它充当与 WhatsApp 用户的聊天机器人。当我尝试同时运行两个阻止功能时遇到一些问题。有什么方法可以成功运行这两个函数而不会遇到任何错误。我尝试过使用一些带有线程和异步的函数,但我无法使其工作。 我收到此错误

RuntimeError: Timeout context manager should be used inside a task
在线上
line 31, in createChannel new_channel = await guild.create_text_channel(name)

代码如下:

import discord
import asyncio
import threading
from flask import Flask, request, json
import requests

BOT_TOKEN = "MTEzMjcyNDYyNDA4NjU0NDQ4Ng.Gz3Rez.d0qL6YPy95BXYMBVKBNvsOcDbJ-PYAIYDkZmqE"
GUILD_ID = 858917141063401512
WHATSAPP_TOKEN = "EAADKZC1wS1J8BO0ZCGfjhraXxOZAkmohivzXLhsXKkwKR35dn8EAADgu9hDQGPOn9nyq1S6YZCPtgxa9ZCzH40kN9yFa3nnC1AFv6F5BZBEDywPxWFhZA3xYFJAI4TuYvQqVz9lXhhpXGPsnKZCRANti3CqISrW1oLZBjEb7QLBe5ZB6CJZCTZCXIGHQZA8TWwrfbhNdf27aGP5FwMNIHS04ZD"
WEBHOOK_TOKEN = "gigustester"
PHONE_NUMBER_ID = 112671368574187

app = Flask(__name__)

intents = discord.Intents.default()
client = discord.Client()


async def createChannel(name):
    guild = client.get_guild(GUILD_ID)

    existing_channel = discord.utils.get(guild.channels, name=name)

    if existing_channel:
        print(f'A channel with the name "{name}" already exists in the guild.')
    else:
        # Create a new text channel
        new_channel = await guild.create_text_channel(name)
        print(f'New channel "{name}" created in the guild!')


async def sendMsgToDisc(msg, id):
    channel = client.get_channel(id)
    if channel:
        await channel.send(msg)
    else:
        print("Channel not found.")


@client.event
async def on_ready():
    print(f"Logged in as {client.user.name}")


@client.event
async def on_message(message):
    channel_name = message.channel.name

    requests.post(
        f"https://graph.facebook.com/v17.0/{PHONE_NUMBER_ID}/messages",
        headers={
            "Authorization": f"Bearer {WHATSAPP_TOKEN}",
            "Content-Type": "application/json",
        },
        json={
            "messaging_product": "whatsapp",
            "recipient_type": "individual",
            "to": channel_name,
            "type": "text",
            "text": {"body": message.content},
        },
    )


@app.get("/webhook")
def webhook_get():
    if request.args.get("hub.verify_token") == WEBHOOK_TOKEN:
        return request.args.get("hub.challenge")
    else:
        return "forbidden", 400


@app.post("/webhook")
async def webhook_post():
    print(request.json)

    if request.json["entry"][0]["changes"][0]["value"]["contacts"][0]["profile"][
        "name"
    ]:
        name = request.json["entry"][0]["changes"][0]["value"]["contacts"][0][
            "profile"
        ]["name"]

        phoneNumber = request.json["entry"][0]["changes"][0]["value"]["messages"][0][
            "from"
        ]

        text = request.json["entry"][0]["changes"][0]["value"]["messages"][0]["text"][
            "body"
        ]

        await createChannel(phoneNumber)
        await sendMsgToDisc(f"{name} ({phoneNumber}):\n{text}", phoneNumber)

    return "ok", 200

def main():
    app.run(debug=False)

if __name__ == "__main__":
    flask_thread = threading.Thread(target=main)
    flask_thread.start()

    print("hello")

    client.run(BOT_TOKEN)
python python-3.x flask asynchronous discord.py
© www.soinside.com 2019 - 2024. All rights reserved.