Creating a channel in specific category (the category id is should be variable) discord.py

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

So here is the normal method but I want to do it by giving variable:

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

but When I print(maincategory) it says None how can I do it?

3 Answers
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!')

Important part:

await category.create_text_channel(channel_name)

You can do something like

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

In case anyone else comes across the same problem:

Common cases that causes utils.get or any get_x method to return None would be:

  • The bot can't "see" the object
  • The id passed is invalid (IDs are integers, not strings)
  • The object is not in cache or the bot is not logged in.

A possible solution would be to use fetch_x methods which calls the API to pull the relevant object if it's in cache or not.

wanted_category_id = 858441350667698190

category = await bot.fetch_channel(wanted_category_id)

Bot.fetch_channel

Related