【问题标题】:How restart dicord bot after client.close(). Discord.py在 client.close() 之后如何重启 discord 机器人。不和谐.py
【发布时间】:2021-12-30 21:36:08
【问题描述】:

我在烧瓶中使用 api 制作不和谐机器人。现在它只需要向频道发送消息。但是如果我用烧瓶启动机器人,所有烧瓶代码都会停止。我尝试使用 client.close,但出现异常RuntimeError: Event loop is closed。我尝试在不同的地方使用 client.clean。但我还是有这个例外。

现在我的代码看起来是这样的:

from flask import Flask, request
import json
import discord

global data

app = Flask(__name__)
client = discord.Client()

CHANNEL = <id>

@client.event
async def on_ready():
    global data

    channel = client.get_channel(id=CHANNEL)

    await channel.send(f"{data['products'][0]['custom_fields'][0]['discord']}\nТовар : {data['products'][0]['name']}")

    await client.close()
    client.clear()

@app.route('/purchase', methods=['POST'])
def purchase():
    global data
    data = json.loads(request.data)

    client.run('token')

    return data['products'][0]['custom_fields'][0]['discord']

【问题讨论】:

  • 将烧瓶部分放在不同的文件中,使用线程同时运行两个文件。
  • @FusionSid 但是如何将请求中的数据提供给机器人?(我在线程方面很糟糕)

标签: python flask discord.py


【解决方案1】:

我可以建议在线程中运行它。当我不必阻塞游戏客户端的主线程时,我遇到了同样的问题(我相信这也适用于 Flask)。例子可以找到here:

import discord
import asyncio

discord_loop = asyncio.get_event_loop()
client = discord.Client(loop=discord_loop, heartbeat_timeout=20, intents=discord.Intents.all())

def init():
    try:
        asyncio.get_child_watcher()

        global discord_loop
        discord_loop = asyncio.get_event_loop()

        thread = threading.Thread(target=discord_loop.run_forever)
        thread.start()

        asyncio.run_coroutine_threadsafe(client.connect(reconnect=True), discord_loop)
        asyncio.run_coroutine_threadsafe(client.login(token=DiscordSettings.TOKEN, bot=True), discord_loop)
    except:
        utils.get_and_log_exception_info()


def stop():
    asyncio.run_coroutine_threadsafe(client.logout(), discord_loop)
    discord_loop.call_soon_threadsafe(discord_loop.stop)


def reconnect():
    client.clear()
    asyncio.run_coroutine_threadsafe(client.connect(reconnect=True), discord_loop)

【讨论】:

    猜你喜欢
    • 2021-05-09
    • 2020-06-20
    • 2021-07-07
    • 2020-10-08
    • 2021-09-28
    • 2021-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多