0

I want to make a bot that makes and assigns a role to the person who requested it. How do I do that? I have tried many things but they all don't work. Here is a copy of the non-functioning code.

import discord
import os
from discord.utils import get


client = discord.Client()

@client.event

async def on_ready():
  print ('we have logged in as {0.user}'.format(client))

@client.event
async def on_message(message):
  if message.author == client.user:
    return

  if message.content.startswith('~hello?'):
    await message.channel.send('YOU WILL NOW WISH YOU NEVER SUMMONED ME...')
    
client.run(os.environ['TOKEN'])

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

client.run(os.environ['TOKEN'])
    

The first part works (~hello?) but the second part (~begin?) doesn't work. Can one of you gracious souls save me from this endless tussle of debugging and coding?

  • 1
    1) It is `message.guild.roles` 2) You have to enable/import Intents 3) You have to assign the role to `message.author` – Dominik Aug 17 '21 at 02:56
  • @Dominik Oops, I was slow :( , if you want to answer it below, tag me and I'll delete mine. – Kouheng Aug 17 '21 at 03:11
  • @Kouheng No problem, just add my parts to your answer/explain them and your answer will also be correct then! :) – Dominik Aug 17 '21 at 03:20

2 Answers2

0

I see a few mistakes in your code.

To get back to your question:

  1. If you want to get the role in a server you have to request the guild, server is kind of outdated. In code this means the following: role = message.guild.roles.

    Reference: Message.guild

  2. After getting the role we have to assign it to a member, this does not work with client.add_roles, try message.author.add_roles() instead. It'll be await message.author.add_roles(role) in the long version then.

  3. If you want to assign a role to a member through your bot you also need to enable Intents. There are tons of Contributions on this site but also in the docs, for example:

Dominik
  • 3,612
  • 2
  • 11
  • 44
Kouheng
  • 383
  • 4
  • 11
0

You can add a command using the @client.command function, but first you need to add a prefix to `client by doing

client = commands.AutoShardedBot(commands.when_mentioned_or(*prefix*))

remember to import commands using from discord.ext import commands

then your life would be easy now, if you want to add a command just do

@client.command
async def add_role(ctx, member:discord.Member):
  role = get(ctx.guild.roles, name='*the role*')

  await member.add_roles(role)

so to call the command just say *prefix* add_role @*the user*