我有一个永远持续运行的脚本(它检查文件中的更改)。每当制作奇怪的文件时,我都需要发送 Discord 消息。
def run(self):如下)来自子类,所以我无法将其更改为async def run(self):. 因此我不能使用await channel.send()run_coroutine_threadsafe: https: //stackoverflow.com/a/53726266/9283107。效果很好!但问题是,消息被放入队列中,并且在该脚本完成之前永远不会发送(在我的情况下是:永远不会)。我假设发送消息函数被放入该脚本所在的线程中,因此线程永远不会到达它们?也许我们可以将其放入run_coroutine_threadsafe一个单独的线程或其他东西中?这是我能做的最小的例子,它仍然显示了我的子类问题。
import discord
import os
import asyncio
import time
# CHANNEL_ID = 7659170174????????
client = discord.Client()
channel = None
class Example():
# Imagine this run comes from a subclass, so you can't add sync to it!
def run(self):
# await channel.send('Test') # We can't do this because of the above comment
asyncio.run_coroutine_threadsafe(channel.send('Test'), _loop)
print('Message sent')
@client.event
async def …Run Code Online (Sandbox Code Playgroud)