discord.py如何从指定分类中提取特定文本频道test-channel2?
解决discord.py获取指定分类下特定频道的问题
你的问题出在使用discord.utils.get(category.text_channels)时没有指定筛选条件,这个方法默认会返回列表里的第一个元素,所以只拿到了test-channel。要获取test-channel2,可以用以下几种方法:
方法1:按频道名称获取
直接用discord.utils.get指定name参数,精准匹配频道名称:
@commands.command() async def c(self, ctx): category = discord.utils.get(ctx.guild.categories, id=941749835328012328) # 按名称获取test-channel2 target_channel = discord.utils.get(category.text_channels, name='test-channel2') if target_channel: print(target_channel) else: print("找不到指定频道")
方法2:按频道ID获取(更可靠)
如果知道test-channel2的ID(从你的输出里是943971117717160007),用ID获取更稳定,避免名称重复的问题:
@commands.command() async def c(self, ctx): category = discord.utils.get(ctx.guild.categories, id=941749835328012328) # 按ID获取test-channel2 target_channel = discord.utils.get(category.text_channels, id=943971117717160007) if target_channel: print(target_channel) else: print("找不到指定频道")
方法3:遍历筛选(适合复杂条件)
如果需要更灵活的筛选逻辑,可以遍历频道列表:
@commands.command() async def c(self, ctx): category = discord.utils.get(ctx.guild.categories, id=941749835328012328) # 遍历找到名称为test-channel2的频道 target_channel = None for channel in category.text_channels: if channel.name == 'test-channel2': target_channel = channel break if target_channel: print(target_channel) else: print("找不到指定频道")
运行任意一种方法,都能精准获取到test-channel2频道。
内容的提问来源于stack exchange,提问作者Smh
相关产品推荐
相关产品推荐

