2

I want to create a discord bot that gives roles to members in Python.

I tried this:

@async def on_message(message):
     if message.content == "give me admin"
           role = discord.utils.get(server.roles, name="Admin")
           await client.add_roles(message.author.id, role)
15
  • The bot has Administrator permissions!
    – MikeyJY
    Commented Feb 26, 2018 at 11:05
  • The @ in front of async shouldn't be there. This function should be decorated with @client.event, or something similar. Instead of message.author.id, just pass message.author to add_roles Commented Feb 26, 2018 at 15:30
  • The program returned: "NameError: name 'server' is not defined"
    – MikeyJY
    Commented Feb 26, 2018 at 16:20
  • Use message.server.roles. Commented Feb 26, 2018 at 16:21
  • Ok i will try. Thx!
    – MikeyJY
    Commented Feb 26, 2018 at 16:22

2 Answers 2

7
import discord
from discord.utils import get

client = discord.Client()

@client.event
async def on_message(message):
    if message.author == client.user:
        return
    if message.content == 'give me admin':
        role = get(message.server.roles, name='Admin')
        await client.add_roles(message.author, role)

I think this should work. The documentation for is here.

You could also use the discord.ext.commands extension:

from discord.ext.commands import Bot
import discord

bot = Bot(command_prefix='!')

@bot.command(pass_context=True)
async def addrole(ctx, role: discord.Role, member: discord.Member=None):
    member = member or ctx.message.author
    await client.add_roles(member, role)

bot.run("token")
13
  • Thank You! You helped me very much!
    – MikeyJY
    Commented Feb 26, 2018 at 16:42
  • Using this code I get this error: "new_roles = utils._unique(role.id for role in itertools.chain(member.roles, roles)) AttributeError: 'NoneType' object has no attribute 'id'"
    – MikeyJY
    Commented Feb 26, 2018 at 16:44
  • @MikeyJY Then there's no role on your server named Admin Commented Feb 26, 2018 at 16:47
  • I know what is the problem: The role is named: Admin+an emoji but I use Python IDLE and when I put emoji the file is closing. Can I use role id?
    – MikeyJY
    Commented Feb 26, 2018 at 16:57
  • Yes. change role = get(message.server.roles, name='Admin') to role = get(message.server.roles, id='<role id>') Commented Feb 26, 2018 at 16:58
1

All you need to do is

import discord
from discord.utils import get

@client.event
async def on_message(message):
    if message.content == "give me admin":
        member = message.author
        role = get(member.guild.roles, name="Admin")
        await member.add_roles(role)
0

Not the answer you're looking for? Browse other questions tagged or ask your own question.