Discord中如何实时获取特定分类下新增频道的名称与ID
问题解决思路与修正代码
你的问题核心出在权限意图(Intents)配置不全、未使用正确的频道创建事件,还有一处ID类型错误,以下是具体修正方案:
1. 补全必要的Intents权限
Discord Bot要监听频道创建事件,必须启用guild_channels意图(默认的default()已包含guilds,但需显式开启guild_channels)。你之前开启的members意图和频道监听无关,可根据需求保留或删除。
2. 使用on_guild_channel_create事件
这是Discord.py专门用于监听服务器内频道创建的事件,替换你现有仅依赖on_message的逻辑(若需保留手动查询功能,可同时保留on_message)。
3. 修正Guild ID的类型
Discord服务器ID是整数类型,你代码里用字符串'101780234'会导致找不到服务器,需改成整数101780234。
修正后的完整代码
import discord TOKEN = '你的Bot令牌' # 配置必要的Intents intents = discord.Intents.default() intents.guild_channels = True # 必须开启此权限才能监听频道创建/删除事件 intents.members = True # 无需监听成员事件可删除此行 client = discord.Client(intents=intents) @client.event async def on_ready(): print(f'Logged in as {client.user.name} ({client.user.id})') print('------') # 监听频道创建事件 @client.event async def on_guild_channel_create(channel): # 目标分类名称 target_category = 'Games' # 目标服务器ID(替换为你的服务器整数ID) target_guild_id = 101780234 # 过滤非目标服务器的频道创建事件 if channel.guild.id != target_guild_id: return # 判断频道是否属于目标分类 if channel.category and channel.category.name == target_category: # 输出新增频道信息 print(f"检测到新增频道:名称【{channel.name}】,ID【{channel.id}】") # 如需发送通知到指定频道,可添加以下逻辑(替换为你的通知频道ID) # notify_channel = client.get_channel(123456789) # await notify_channel.send(f"检测到新增频道:名称【{channel.name}】,ID【{channel.id}】") # 保留手动查询命令(可选) @client.event async def on_message(message): if message.content.startswith('!get_channels'): category_name = 'Games' # 服务器ID改为整数类型 guild = discord.utils.get(client.guilds, id=101780234) if guild: category = discord.utils.get(guild.categories, name=category_name) if category: public_channels = [channel.name for channel in category.channels if not channel.private] await message.channel.send(f'分类"{category_name}"下的公开频道:{", ".join(public_channels)}') else: await message.channel.send(f'未找到分类"{category_name}"。') else: await message.channel.send('未找到目标服务器。') client.run(TOKEN)
最后一步:开启开发者门户权限
登录Discord开发者门户,找到你的Bot应用进入Bot页面,在Privileged Gateway Intents区域,确保相关权限已开启,随后重启Bot即可。
内容的提问来源于stack exchange,提问作者Sajjad Sarwar
相关产品推荐
相关产品推荐

