Discord Python 使用 ID 删除类别和频道

时间:2021-06-11 23:36:52

标签: python discord discord.py

#deleted unused registered channels
@bot.command(pass_context=True)
#so that only an admin can run this command
@commands.has_role('Admin')
async def unregister(ctx, catID):
  cat = discord.utils.get(ctx.guild.categories, id = catID)

  #await ctx.channel.send(cat)

  for channel in cat.voice_channels:
    await channel.delete()

  for channel in cat.text_channels:
    await channel.delete()
  
  cat.delete()

这是我目前拥有的代码。我也用 client.get_channel() 试过了。我似乎收到了类别无法访问 .voice_channels 和 .text_channels 的错误,或者那只猫是“NoneType”。我是 python 的新手并且编写了一个不和谐的机器人,所以这个命令的任何帮助都会很棒。谢谢!

该命令旨在获取您可以通过右键单击并复制不和谐类别获得的类别 ID。然后删除它下面的每个语音和文本频道。然后删除自己。

1 个答案:

答案 0 :(得分:0)

您的代码本身几乎是正确的,但可以在许多地方进行简化。

cat 完全没有必要,所以不需要定义,因为我们可以简单地说如下:

category: discord.CategoryChannel

现在我们只需要输入 ID,剩下的就自己处理了。根据定义,我们现在可以进一步构建代码:

@bot.command(pass_context=True)
@commands.has_role('Admin')
async def unregister(ctx, category: discord.CategoryChannel):
    delcategory = category # delcategory is our ID (category)
    channels = delcategory.channels # Get all channels of the category

    for channel in channels: # We search for all channels in a loop
        try:
            await channel.delete() # Delete all channels
        except AttributeError: # If the category does not exist/channels are gone
            pass
    await delcategory.delete() # At the end we delete the category, if the loop is over