Discord bot如何向thread(线程)频道发送消息?
机器人向Discord线程(Thread)发送消息的实现方案
虽然早期discord.py官方文档未及时更新线程相关操作说明,但2.0及以上版本的discord.py已经原生支持Thread类型的交互,实现逻辑如下:
核心逻辑说明
Discord的线程(Thread)本质属于频道子类,bot.get_channel()方法可以直接识别线程ID,返回对应的线程对象,send()、trigger_typing()等操作方法和普通文本频道完全兼容。
方案1:直接传入目标ID发送消息
原有代码几乎不需要修改,只需要将传入的channel_id替换为目标线程的ID即可,该方案同时兼容普通频道和线程的消息发送:
import discord from discord.ext import commands # 初始化需开启必要意图,需提前在Discord开发者后台开启Message Content Intent权限 intents = discord.Intents.default() intents.message_content = True bot = commands.Bot(command_prefix='!', intents=intents) @bot.command() async def text(ctx, target_id, *, msg): # target_id支持传入普通频道ID或线程ID channel = bot.get_channel(int(target_id)) if not channel: await ctx.send("未找到对应频道/线程,请检查ID是否正确") return try: await channel.send(ctx.message.attachments[0].url) except IndexError: pass await channel.trigger_typing() await channel.send(msg)
方案2:按父频道ID+线程名称发送消息
如果仅持有父频道ID,需要按线程名称匹配发送,可以遍历父频道的线程列表实现:
@bot.command() async def text_to_thread(ctx, parent_channel_id, thread_name, *, msg): parent_channel = bot.get_channel(int(parent_channel_id)) if not parent_channel: await ctx.send("未找到对应父频道") return # 获取父频道下所有活跃线程 active_threads = parent_channel.threads # 匹配目标线程名称 target_thread = next((t for t in active_threads if t.name == thread_name), None) if not target_thread: await ctx.send("未找到对应名称的活跃线程") return # 发送逻辑和普通频道完全一致 try: await target_thread.send(ctx.message.attachments[0].url) except IndexError: pass await target_thread.trigger_typing() await target_thread.send(msg)
注意事项
- 如果需要向归档状态的线程发消息,需要先调用
await parent_channel.archived_threads()拉取归档线程列表,匹配到目标线程后先解除归档再发送 - 请确保机器人拥有目标线程的
发送消息权限,否则会触发权限类报错
内容的提问来源于stack exchange,提问作者Aditya Tomar
相关产品推荐
相关产品推荐

