Discord.py 运行 单独线程上的命令
Discord.py running commands on a separate thread
我的 discord 机器人有命令让机器人每 30 秒说 "I'm running"。但是,这会使主线程休眠,从而使机器人命令无法使用。
代码如下:
while true:
await channel.send("I'm running")
time.sleep(30)
我尝试使用 https://github.com/Rapptz/discord.py/issues/82 and https://docs.python.org/3/library/asyncio-task.html#asyncio.run_coroutine_threadsafe 作为参考,但我无法理解它是如何工作的。
你应该使用一些非阻塞睡眠。例如,您可以尝试 await asyncio.sleep(30)
而不是使用 time.sleep
,也许它可以直接工作?
如果不是,那么您必须实现手动计时器,以便在特定时间过后使用 if
语句调用 channel.send
。异步方法起初可能令人困惑。
您检查过的有关线程的示例已经过时,因为 discord.py 现在使用异步方法。
如果它的目的只是每 30 秒发送一条消息。您还可以创建一个每 30 秒运行一次的任务。您可以随时 start/stop 任务。
示例:
class example_class():
def __init__():
self.channel = None
async def some_command_starting_our_task(ctx):
self.channel = ctx.channel
botStatus.start() # Used to start the task
async def some_command_stopping_our_task():
botStatus.stop() # Used to stop the task
@task.loop(seconds=30)
async def botStatus():
self.channel.send("Im running")
有关任务的更多信息,您可以阅读 documentation。
我的 discord 机器人有命令让机器人每 30 秒说 "I'm running"。但是,这会使主线程休眠,从而使机器人命令无法使用。
代码如下:
while true:
await channel.send("I'm running")
time.sleep(30)
我尝试使用 https://github.com/Rapptz/discord.py/issues/82 and https://docs.python.org/3/library/asyncio-task.html#asyncio.run_coroutine_threadsafe 作为参考,但我无法理解它是如何工作的。
你应该使用一些非阻塞睡眠。例如,您可以尝试 await asyncio.sleep(30)
而不是使用 time.sleep
,也许它可以直接工作?
如果不是,那么您必须实现手动计时器,以便在特定时间过后使用 if
语句调用 channel.send
。异步方法起初可能令人困惑。
您检查过的有关线程的示例已经过时,因为 discord.py 现在使用异步方法。
如果它的目的只是每 30 秒发送一条消息。您还可以创建一个每 30 秒运行一次的任务。您可以随时 start/stop 任务。
示例:
class example_class():
def __init__():
self.channel = None
async def some_command_starting_our_task(ctx):
self.channel = ctx.channel
botStatus.start() # Used to start the task
async def some_command_stopping_our_task():
botStatus.stop() # Used to stop the task
@task.loop(seconds=30)
async def botStatus():
self.channel.send("Im running")
有关任务的更多信息,您可以阅读 documentation。