Search code examples
pythondiscorddiscord.py

How to sort discord channels in a custom order?


I have a list of channel names like this:

{
  'Information': [
    'rules', 
    'about', 
    'announcements', 
    'community-updates'
    ],
  'Moderation': [
    'mod-commands', 
    'isolation'
    ],
  'Interface': [
    'election-feed',
    'debate-feed',
    'commands'
    ], 
  'Events': [], 
  'Community': [
    'general',
    'memes'
    ], 
  'Debate': [
    'Debate 1',
    'Debate 2'
    ],
  'Logs': [
    'voice'
    ]
}

I want to be able to re-arrange channels to be in this format on running a command using discord.py using await channel.edit(position=position). I already have a get_channel() function which retrieves the correct channel object from the name. How do I do this? Discord's sorting is very confusing and won't allow regular sequential ordering.


Solution

  • I figured it out. This is the solution:

    # Reorder Channels
    for category_name in CHANNEL_SORT_ORDER.keys():
        category = discord.utils.get(guild.channels, name=category_name)
        position = list(CHANNEL_SORT_ORDER.keys()).index(category_name)
        await category.edit(position=position)
    
    for category_name in CHANNEL_SORT_ORDER.keys():
        category = discord.utils.get(guild.channels, name=category_name)
        sorted_channels = []
        for channel_name in CHANNEL_SORT_ORDER[category_name]:
            channel = discord.utils.get(guild.channels, name=channel_name)
            sorted_channels.append(channel)
    
        if sorted_channels:
            min_position = min(sorted_channels, key=lambda c: c.position)
            for new_position, channel in enumerate(sorted_channels, start=min_position.position):
                await channel.edit(category=category, position=new_position)