【发布时间】:2020-02-07 18:46:01
【问题描述】:
消息以“波”的形式发送,即几秒钟内什么都没有,然后几乎同时有大约 5 秒钟。我漏掉了token 和channel。
import discord, asyncio
class Bot(discord.Client):
def __init__(self, q, channel):
super().__init__()
self.q = q
self.channel_id = channel
self.bg_task = self.loop.create_task(self.send_messages())
async def on_message(self, message):
if message.author == self.user or message.channel.id != self.channel_id:
return
print(message.content)
async def send_messages(self):
await self.wait_until_ready()
channel = self.get_channel(self.channel_id)
while not self.is_closed():
msg = await self.q.get()
await channel.send(msg)
from threading import Thread
from time import sleep
q = asyncio.Queue()
def f():
while True:
q.put_nowait("hi")
sleep(2)
Thread(target=f).start()
bot = Bot(q, channel)
bot.run(token)
奇怪的是,on_message 事件似乎不受影响,并且将msg = await self.q.get() 替换为
msg = "hi"
await asyncio.sleep(2)
似乎会导致预期的行为。
我不确定哪里出了问题,所以我将示例更具体地用于 Discord。
编辑
扩展asyncio.sleep 行为,我已将send_messages 中的循环替换为
if 0:
msg = await self.q.get()
else:
await asyncio.sleep(0.1)
if self.q.empty():
continue
msg = await self.q.get()
await channel.send(msg)
if 只是在原始和实验之间切换。
显然,人们预计else 部分最多与if 部分一样快,但是等待队列非空似乎可以完全解决问题。
我开始认为不和谐和阻塞异步队列以不可预见的方式交互
另一方面,channel.send 似乎是阻塞线,所以也许它也与速率有关。
【问题讨论】:
-
这只是 discord api 的内部工作原理,asyncio 本身不是问题
-
@LuM 我怀疑是这样的,但为什么不同样适用于 asyncio.sleep?
标签: python python-3.x python-asyncio discord.py