相关疑难解决方法(0)

在单独的线程中执行 run_coroutine_threadsafe

我有一个永远持续运行的脚本(它检查文件中的更改)。每当制作奇怪的文件时,我都需要发送 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)

python async-await python-asyncio discord.py

2
推荐指数
1
解决办法
2658
查看次数

标签 统计

async-await ×1

discord.py ×1

python ×1

python-asyncio ×1