我有一个不和谐的机器人,它会根据网络抓取应用程序每隔一段时间发送一条消息(这里不会显示,因为它有 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()
之前重新打开事件循环?我是否需要或是否有我可以使用的解决方法。
注意:我试着让机器人一直保持打开状态,但过了一会儿它就退出了 discord。
答案 0 :(得分:0)
这不是我的回复,这是@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')