discord.py:如何从提及频道获取频道名称与ID
在discord.py中获取命令提及频道的名称与ID
刚好我之前做过类似的功能,在discord.py里有两种简单直接的方式实现你的需求,我给你详细拆解一下:
方法一:利用命令扩展的参数类型注解(推荐)
这是最省心的方式,discord.py的命令扩展会自动帮你解析频道提及,不需要手动处理字符串。只需要给命令参数指定discord.TextChannel类型即可:
from discord.ext import commands import discord # 必须开启必要的intents,尤其是message_content intents = discord.Intents.default() intents.message_content = True bot = commands.Bot(command_prefix="--", intents=intents) @bot.command(name="command") async def get_channel_info(ctx, target_channel: discord.TextChannel): # 直接从频道对象获取名称和ID channel_name = target_channel.name channel_id = target_channel.id await ctx.send(f"你提及的频道:\n名称:*{channel_name}*\nID:`{channel_id}`") # 替换成你的机器人令牌 bot.run("YOUR_BOT_TOKEN")
当用户发送--command #测试频道时,discord.py会自动把#测试频道转换成对应的TextChannel对象,你直接调用它的name和id属性就能拿到需要的信息。
方法二:手动解析消息中的频道提及
如果你的场景不适合用命令扩展(比如需要自定义消息处理逻辑),可以通过message.channel_mentions属性获取所有被提及的频道:
from discord.ext import commands import discord intents = discord.Intents.default() intents.message_content = True bot = commands.Bot(command_prefix="--", intents=intents) @bot.event async def on_message(message): # 忽略机器人自身的消息 if message.author.bot: return # 检测是否是目标命令 if message.content.strip().startswith("--command"): # 获取消息中所有被提及的频道 mentioned_channels = message.channel_mentions if mentioned_channels: # 取第一个被提及的频道(如果有多个的话可以遍历处理) target_channel = mentioned_channels[0] await message.channel.send( f"检测到提及频道:\n名称:*{target_channel.name}*\nID:`{target_channel.id}`" ) else: await message.channel.send("没有检测到任何频道提及哦,请确保格式是`--command #频道`") # 必须调用这个,否则命令扩展的命令会失效 await bot.process_commands(message) bot.run("YOUR_BOT_TOKEN")
注意事项
- 一定要在Discord开发者门户的机器人设置里开启Message Content Intent,否则bot无法读取消息内容,也就无法解析频道提及。
- 如果需要支持语音频道、分类频道等其他类型,可以把参数类型换成
discord.abc.GuildChannel,这样能匹配所有服务器内的频道类型。
内容的提问来源于stack exchange,提问作者Nat L
相关产品推荐
相关产品推荐

