简体   繁体   中英

Discord.py - Checking if a user has a role based on the channel

so right now I'm trying to create a command which basically creates overrides that blocks a specific user from viewing the channel. The only thing I am having trouble with is the part where the bot verifies if the user "owns" the channel. There are a few channels which are player owned and they have a role that matches up with the channel's name.

So as an example:

#space-invaders

@Space Invaders OP

The issue in the code is that while trying to convert the roles into string, it fails to do so. So I need an alternative to this and I have no clue what else I could do.

@commands.command()
@commands.has_role("Realm OP")
  async def block(self, ctx, user: discord.User):
    #channel = await ctx.author.create_dm()
    channel = ctx.message.channel
    author = ctx.message.author
    mentions = [role.mention for role in ctx.message.author.roles if role.mentionable]
    channel2 = str(channel.name)
    channel = channel2.split('-')
    if len(channel2) == 2: # #real-emoji
      realm, emoji = channel
    else: # #realm-name-emoji  
      realm, emoji = channel[0], channel[-1]
      realmName = realm.replace("-" , " ")
      realmName1 = realmName.lower()
    rolelist = []
    authorRoles = discord.Role.name(author.roles) # Issue here
    for role in authorRoles:
      rolen = role.lower()
      rolelist.append(rolen.mention)
    if realmName1 in rolelist:
      await ctx.send("true")
    else:
      await ctx.send("false")

Any suggestions would greatly help!

You would check if the role is in the author roles.

First: Change the channel name into the format of the role space-invaders -> Space Invaders OP . Which means replace , title and OP at the end

Secondly: Get the role from the guild using discord.utils.get and check if the author has it.

@commands.command()
@commands.has_role("Realm OP")
async def block(ctx, user: discord.User):
    check_name = f'{ctx.channel.name.replace("-", " ").title()} OP'
    check_role = discord.utils.get(ctx.guild.roles, name= check_name)
    if check_role not in ctx.author.roles:
        return await ctx.send('You do not own this channel')
    
    # code here. 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM