python - Discord.py:如何从线程函数发送消息?
问题描述
我有以下代码:
import asyncio
import threading
import time
import discord
from discord.ext import commands
from .utils import error
class threaded:
def __init__(self, channel, bot):
self.channel = bot.get_channel(channel)
self.bot = bot
def doSomething(self):
print("abc")
async def IAmThreaded(self):
time.sleep(30)
embed = discord.Embed(title=f"Finished doing something",
description=f"abc",
color=0x000000)
# this is where I get the error
await self.channel.send(embed=embed)
time.sleep(30)
Busy.busy = False
def threadMe(self):
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(self.IAmThreaded())
loop.close()
class Busy:
busy = False
@commands.command()
async def something(ctx):
if not Busy.busy:
threadMeClass = threaded(ctx.channel.id, ctx.bot)
embed = discord.Embed(title=f"Starting doing something",
description=f"abc", color=0x000000)
await ctx.channel.send(embed=embed)
threadMeClass.doSomething()
Busy.bosy= True
threading.Thread(target=threadMeClass.threadMe).start()
else:
await error(ctx, "There is already something running, please wait for it to finish")
当它运行时,线程一直工作,直到它完成并尝试发送消息,当它完成时,我得到: RuntimeError: Timeout context manager should be used inside a task。我尝试将 ctx 直接传递给类并通过保存 id 来获取频道,但它们都不起作用,有什么提示吗?
解决方案
推荐阅读
- mysql - 没有外键的关联并在表中加入
- c# - 如何使用 ASP.NET MVC 操作来自 HTML 输入标记的数据
- vb.net - 有没有办法在即时窗口中直接通过代码编写命令?
- java - “如何解决错误:';' 预计在 Java 中?”
- java - 为什么使用随机和线程池时输出顺序没有改变?
- c# - 我应该如何构建一个在应用程序启动时运行并加载数据的启动类?
- python - 按键不适用于 Urwid 中的编辑小部件
- c# - 所有 Visual Studio 主题的选项卡都变为蓝色
- node.js - 如何将带有winston的日志记录集成到logstash-kibana中
- elasticsearch-2.0 - elasticsearch-2 在将 kibana 从 4.5 版升级到 5.x 或 6.x 时是否兼容