使用discord.py创建文本频道并授予指定用户查看权限的问题
问题解决代码
@client.command() @commands.has_permissions(manage_channels=True) async def channelCreate(ctx, channel_name, member: discord.Member): guild = ctx.guild # 筛选分类,避免匹配到同名普通频道 category = discord.utils.get(guild.categories, name="Alliances") if not category: await ctx.send("未找到Alliances分类") return # 配置频道权限覆盖规则 overwrites = { # 禁止全体成员默认访问,保证频道私密性 guild.default_role: discord.PermissionOverwrite(view_channel=False), # 给指定用户开放基础访问权限 member: discord.PermissionOverwrite(view_channel=True, send_messages=True, read_message_history=True), # 保留指令发起者的管理权限,可按需删除 ctx.author: discord.PermissionOverwrite(view_channel=True, manage_channels=True) } # 创建频道时传入权限和分类配置 new_channel = await guild.create_text_channel( name=channel_name, category=category, overwrites=overwrites ) await ctx.send(f"频道 {new_channel.mention} 创建成功,已为 {member.mention} 开放访问权限")
关键调整说明
- 查找分类时使用
guild.categories而非全频道列表筛选,避免匹配到同名普通频道导致创建失败 - 你提到的按用户名添加成员的需求已经被
discord.Member类型参数原生支持,执行指令时可以直接用用户名、#用户标签、用户ID、@提及四种方式指定成员,不需要额外写匹配逻辑 - 如果需要给指定用户配置更多权限,直接在
PermissionOverwrite中添加对应参数即可,比如manage_messages=True开放消息管理权限
内容的提问来源于stack exchange,提问作者CodeKid
相关产品推荐
相关产品推荐

