Search code examples
pythondiscorddiscord.py

discord.py Get channel permissions and use them in a different channel


I am trying to copy the permissions of a channel and then use them in a different guild

@bot.command() #get channel permissions
async def copychannel(ctx):
    chan_perm = ctx.channel.overwrites
    print(chan_perm)

output:

{<Role id=926970474183925870 name='@everyone'>: <discord.permissions.PermissionOverwrite object at 0x00000291FC3AB940>}
#it is a dict
@bot.command() #trying to use these permissions on a different guild
async def channel(ctx):
    c={"<Role id=923673221469966336 name='@everyone'>": "<discord.permissions.PermissionOverwrite object at 0x00000291FC3AB940>"}
    await ctx.guild.create_text_channel(name='test', overwrites=c)

output:

#It is giving me an error:
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: InvalidArgument: Expected PermissionOverwrite received str

How can I fix this?


Solution

  • A revised form of Konstantinos Georgiadis's answer to clear up confusion about where code goes:

    First, we need to actually obtain the overwrites from the original server. To do this:

    
    @bot.command() # command to use in the first server to copy channel permissions
    async def copy(ctx):
        global overwrites
        overwrites = ctx.channel.overwrites
    

    Now, we can use those overwrites to "paste" our permissions into the new server:

    @bot.command() # command to paste ...
    async def paste(ctx):
        for role, overwrite in overwrites.items():    # this is the dict of overwrites from copy()
            if type(role) is discord.Role:   # we are assuming role is a Role, but could be a Member
                new_role = discord.utils.get(ctx.guild.roles, name=role.name)
                modified_overwrites[role] = overwrite
        await ctx.guild.create_text_channel(name="channel", overwrites=modified_overwrites)
    

    Effectively, this iterates through all of the permission overwrites from our "template". For each overwrite, it matches the role in the old server to the corresponding role in the new server, so that we don't get any errors when creating the channel. Then, it creates the channel with our new set of overwrites and roles.