discord.py非异步函数发消息报错:Thread-1无事件循环
解决Discord机器人非异步函数发送消息的RuntimeError问题
问题描述
开发Discord机器人时,在非异步函数check_time中尝试发送消息,触发以下错误:
RuntimeError: There is no current event loop in thread 'Thread-1'
错误栈如下:
Exception in thread Thread-1: Traceback (most recent call last): File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python38\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python38\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "c:/Users/LENOVO/Documents/Ada-online/Discord bot/main copy.py", line 19, in check_time asyncio.get_event_loop().create_task(channel.send("example message")) File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python38\lib\asyncio\events.py", line 639, in get_event_loop raise RuntimeError('There is no current event loop in thread %r.' RuntimeError: There is no current event loop in thread 'Thread-1'
完整代码:
import discord import threading import datetime import time import asyncio intents = discord.Intents.default() intents.message_content = True client = discord.Client(intents=intents) my_secret = 'bot_key' def check_time(): time.sleep(10) channel = client.get_channel(1027207022132863036) print('Channel:', channel) asyncio.get_event_loop().create_task(channel.send("example message")) while True: ndt = datetime.datetime.now() if ndt.strftime('%A') == 'Friday' and ndt.hour == 16 and ndt.minute == 29 and ndt.second == 5: asyncio.get_event_loop().create_task(channel.send("example message")) time.sleep(0.9) @client.event async def on_ready(): print('We have logged in as {0.user}'.format(client)) @client.event async def on_message(msg): print(msg.channel) msg_words1 = msg.content.split(' ') msg_words = [] for i in msg_words1: msg_words.append(i.lower()) if msg.author == client.user: return if ('zoom' in msg_words and 'when' in msg_words) or ('zoom' in msg_words and 'when?' in msg_words) or ('zoom?' in msg_words and 'when' in msg_words): await msg.channel.send('We have zoom every day from 16:00 to 17:30.') t = threading.Thread(target=check_time) t.start() client.run(my_secret)
错误原因
discord.py的客户端运行在主线程的asyncio事件循环中,手动创建的子线程Thread-1没有绑定任何事件循环,直接调用asyncio.get_event_loop()会找不到可用的循环,导致报错。
解决方案
方案一:使用discord.py内置任务(推荐)
放弃手动线程,改用discord.py提供的异步任务机制,将定时检查逻辑改为异步函数,完全在框架的事件循环内运行:
修改后的代码:
import discord import datetime import asyncio intents = discord.Intents.default() intents.message_content = True client = discord.Client(intents=intents) my_secret = 'bot_key' async def check_time(): await asyncio.sleep(10) # 替换time.sleep为异步版本 channel = client.get_channel(1027207022132863036) print('Channel:', channel) await channel.send("example message") while True: ndt = datetime.datetime.now() if ndt.strftime('%A') == 'Friday' and ndt.hour == 16 and ndt.minute == 29 and ndt.second == 5: await channel.send("example message") await asyncio.sleep(0.9) # 替换time.sleep为异步版本 @client.event async def on_ready(): print('We have logged in as {0.user}'.format(client)) # 启动定时任务 asyncio.create_task(check_time()) @client.event async def on_message(msg): print(msg.channel) msg_words = [i.lower() for i in msg.content.split(' ')] # 简化列表处理 if msg.author == client.user: return if ('zoom' in msg_words and 'when' in msg_words) or ('zoom' in msg_words and 'when?' in msg_words) or ('zoom?' in msg_words and 'when' in msg_words): await msg.channel.send('We have zoom every day from 16:00 to 17:30.') client.run(my_secret)
方案二:保留线程,使用run_coroutine_threadsafe
如果必须使用线程,通过asyncio.run_coroutine_threadsafe将发送消息的协程提交到主线程的事件循环执行:
修改后的check_time函数:
def check_time(): time.sleep(10) channel = client.get_channel(1027207022132863036) print('Channel:', channel) # 提交协程到主线程的事件循环 asyncio.run_coroutine_threadsafe(channel.send("example message"), client.loop) while True: ndt = datetime.datetime.now() if ndt.strftime('%A') == 'Friday' and ndt.hour == 16 and ndt.minute == 29 and ndt.second == 5: asyncio.run_coroutine_threadsafe(channel.send("example message"), client.loop) time.sleep(0.9)
注意:此方案需要确保client.loop已初始化(即客户端已完成启动),否则会触发额外错误。
内容的提问来源于stack exchange,提问作者Rok Kužner
相关产品推荐
相关产品推荐

