【问题标题】:Discord.py: Restarting the event loop after the event loop already closes due to bot.close()Discord.py:在事件循环由于 bot.close() 而关闭后重新启动事件循环
【发布时间】:2021-09-29 06:27:23
【问题描述】:

我有一个不和谐的机器人,它基于网络抓取应用程序每隔一段时间发送一条消息(这里不会显示,因为它有 500 行长,其他人可以与它竞争)这是代码发送消息:

import discord
import time
import asyncio

#the reason it is in while true is so it sends more frequently than once every 30 minutes for testing
while True:

    bot = discord.Client()
    @bot.event 
    async def on_ready():
        channel = bot.get_channel(866363006974820355)
        await channel.send("Test")
        print("Sent")
        await bot.close()
      

    print("started")
    
    bot.run('hiddentoken')

机器人关闭循环后,它会返回bot.run() 并给出以下异常:Event loop is closed。在bot.run() 之前如何重新打开事件循环?我是否需要或者是否有我可以使用的解决方法。 注意:我尝试让机器人一直保持打开状态,但它会在一段时间后退出不和谐。

【问题讨论】:

  • await bot.close() 关闭websocket 连接。因此与不和谐服务器没有任何连接。我想因此事件循环也关闭了。 Discord.py Wiki client.close()。也许只是不关闭机器人?
  • 你能添加一个Minimal, Reproducible Example 来说明网络抓取的作用吗?或者是它的代理?我怀疑代码被阻塞了,这会冻结你的机器人。
  • @Doluk 我试图不关闭循环,但是当机器人回到bot.run() 时,它只是冻结并且什么都不做。
  • @Benjin 它搜索网站,然后搜索 eBay 以查看商品是否有利润。没有代理,它在我的测试脚本中不起作用,这正是您在我最初的答案中看到的。
  • 就像我说的,我最好的猜测是有什么东西阻塞了。如果没有看到代码,它只能是猜测。看看here,它可能会解决你的问题。它不会保持循环打开,但机器人可能不会再冻结和关闭。

标签: python discord discord.py python-asyncio


【解决方案1】:

这不是我的回复,这是@Benjin。 This is where he answered.

praw 依赖于requests 库,它是同步的,意味着代码是阻塞的。如果阻塞代码执行时间过长,这可能会导致您的机器人冻结。

为了解决这个问题,可以创建一个单独的线程来处理阻塞代码。下面是一个例子。请注意blocking_function 将如何使用time.sleep 阻止 10 分钟(600 秒)。这应该足以冻结并最终使机器人崩溃。但是,由于该函数在它自己的线程中使用run_in_executor,因此机器人继续正常运行。

import time
import asyncio
from discord.ext import commands
from concurrent.futures import ThreadPoolExecutor

def blocking_function():
    print('entering blocking function')
    time.sleep(600)
    print('sleep has been completed')
    return 'Pong'

client = commands.Bot(command_prefix='!')

@client.event
async def on_ready():
    print('client ready')

@client.command()
async def ping():
    loop = asyncio.get_event_loop()
    block_return = await loop.run_in_executor(ThreadPoolExecutor(), blocking_function)
    await client.say(block_return)

client.run('token')

【讨论】:

    猜你喜欢
    • 2018-08-11
    • 1970-01-01
    • 2021-04-27
    • 1970-01-01
    • 1970-01-01
    • 2020-10-02
    • 1970-01-01
    • 1970-01-01
    • 2021-02-21
    相关资源
    最近更新 更多