如何让Discord机器人加入指定线程并正确响应消息?
问题描述
我开发了一个Discord机器人,能响应包含+后接1-10数字的消息(例如收到+1时回复Total=1)。但目前机器人无法加入指定线程,只会在#general频道中响应。
相关代码片段:
@client.event async def on_ready(): print(f'Logged in as {client.user.name} (ID: {client.user.id})') channel = client.fetch_channel(threadidhere) thread = await channel.fetch_message(threadidhere) await thread.join() async for msg in channel.history(limit=200):
报错信息:
Ignoring exception in on_ready Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/discord/client.py", line 343, in _run_event await coro(*args, **kwargs) File "/app/bot.py", line 9, in on_ready thread = await channel.fetch_message(threadidhere) AttributeError: 'coroutine' object has no attribute 'fetch_message' /usr/local/lib/python3.9/site-packages/discord/client.py:350: RuntimeWarning: coroutine 'Client.fetch_channel' was never awaited pass RuntimeWarning: Enable tracemalloc to get the object allocation traceback
尝试过多种on_ready相关方法,均无法让机器人加入指定线程。
解决方案
核心错误点
client.fetch_channel()是异步方法,调用时未加await,导致channel为coroutine对象而非频道实例,引发后续属性错误。- 误用
fetch_message()获取线程:该方法用于获取普通消息,获取线程需使用fetch_thread()。
修复代码
@client.event async def on_ready(): print(f'Logged in as {client.user.name} (ID: {client.user.id})') # 获取线程所在的父频道(替换为实际父频道ID) parent_channel = await client.fetch_channel(PARENT_CHANNEL_ID) # 通过父频道获取目标线程(替换为实际线程ID) target_thread = await parent_channel.fetch_thread(TARGET_THREAD_ID) # 让机器人加入线程 await target_thread.join() # 若需遍历线程历史消息,使用thread.history而非channel.history async for msg in target_thread.history(limit=200): # 此处添加消息处理逻辑 pass
注意事项
- 确保机器人拥有查看线程和加入线程的权限,否则会触发权限异常。
- 如果线程属于论坛频道,父频道即为该论坛频道,获取方式相同。
- 后续消息响应逻辑需确保监听线程内的消息,让机器人能在指定线程中触发回复。
内容的提问来源于stack exchange,提问作者Randy Bailey
相关产品推荐
相关产品推荐

