discord.py 在特定类别中创建通道(类别 ID 应该是可变的)


maincategory = discord.utils.get(guild.categories, id=858441350667698190)

所以这是正常的方法,但我想通过给出变量来做到这一点:

wanted_category_id = 858441350667698190
maincategory = discord.utils.get(guild.categories, id=wanted_category_id)

但是当我print(maincategory)它说None我该怎么做?

Category 实际上是一个CategoryChannel对象,它派生自abc.GuildChannelGuild.get_channel函数的返回类型,因此您可以利用它来发挥自己的优势,而不是像这样获得此类别:

category = discord.utils.get(guild.categories, id=category_id)

你可以这样做:
discord.Guild.get_channel

category = guild.get_channel(category_id)

以这种方式获取类别通道后,可以通过这样做在其中创建文本通道:discord.CategoryChannel.create_text_channel

await category.create_text_channel(channel_name, **options)
category = bot.get_channel(wanted_category_id)
brand_new_channel = await category.create_text_channel(  # There's also create_voice_channel and create_stage_channel.
channel_name,                                        # channel_name should be "general", not "#general".
# The rest are optional.
overwrites={                                         # Used for custom channel permissions and private channels.
guild.default_role: discord.PermissionOverwrite(
send_messages=False                          # By default, members can't send messages...
),
guild.me: discord.PermissionOverwrite.from_pair(
discord.Permissions.all(),                   # But the bot has all permissions enabled...
discord.Permissions.none()                   # And none disabled!
)
},
reason='Because I can'                               # This shows up in the audit logs.
)
await brand_new_channel.send('Ooh boy! A shiny new channel!')

重要部分:

await category.create_text_channel(channel_name)

你可以做类似的事情

c = discord.utils.get(ctx.guild.categories, id=ID) # Gets the category.
await ctx.guild.create_text_channel(name="whatever", category=c)

如果其他人遇到同样的问题:

导致utils.get或任何get_x方法返回None的常见情况是:

  • 机器人无法"看到"对象
  • 传递的 id 无效(ID 是整数,而不是字符串)
  • 对象不在缓存中或机器人未登录。

一个可能的解决方案是使用调用 APIfetch_x方法来提取相关对象(如果它是否在缓存中)。

wanted_category_id = 858441350667698190
category = await bot.fetch_channel(wanted_category_id)

Bot.fetch_channel

最新更新