This code for changing roles doesn't work - discord.py

I got this code to change a user's role, but it won't work.
#client.command(pass_context=True)
async def ruleBreak(ctx):
member = ctx.message.author
role = discord.utils.get(member.server.roles, name="RuleBreakers")
await client.add_roles(member, role)
But it's causing this error
Ignoring exception in command ruleBreak:
Traceback (most recent call last):
File "C:\Users\unkno\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "c:/Users/unkno/Desktop/Code_Tests/Python/discord_bot/WIP/bot2.py", line 19, in ruleBreak
role = discord.utils.get(member.server.roles, name="RuleBreakers")
AttributeError: 'Member' object has no attribute 'server'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\unkno\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\bot.py", line 903, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\unkno\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 855, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\unkno\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Member' object has no attribute 'server'
What do I do, why is this happening, and where do I change it?
Thanks in advance!

You don't need to pass context as it's done for you in the rewrite branch.
#client.command()
async def ruleBreak(ctx):
member = ctx.message.author
role = discord.utils.get(member.guild.roles, name="RuleBreakers")
await discord.Member.add_roles(member, role)
EDIT: The main issue here was that Client.add_roles changed to Member.add_roles() in the rewrite version. Migrating to v1.0

Related

Discord.py new timeout command error: "AttributeError: 'User' object has no attribute 'timeout_for'"

Hello all and happy new year 2022!!
Since the recent add of "timeouts" for discord, I have tried to make the timeout command following some tutorials like:
https://docs.pycord.dev/en/master/api.html?highlight=timeout#discord.Member.timeout
https://youtu.be/c5V4OaTNDtM
But I may get the following error for a reason I don't know:
Ignoring exception in command timeout2:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "/home/runner/Russia-Bot/moderator.py", line 42, in timeout2
await member.timeout_for(time)
AttributeError: 'Member' object has no attribute 'timeout_for'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Member' object has no attribute 'timeout_for'
Here's the command code, i have made 2 different commands but both give the same issue:
Variant 1:
#client.command()
async def timeout(ctx, member: discord.Member, time=None, reason=None):
time = humanfriendly.parse_timespan(time)
await member.timeout(until = discord.utils.utcnow() + datetime.timedelta(seconds=time), reason=reason)
await ctx.send (f"{member} callate un rato anda {time}")
Variant 2
#client.command(pass_context =True)
async def timeout2(ctx, member:discord.User=None, time=None):
#time = humanfriendly.parse_timespan(time)
# tiempo = datetime.timedelta(seconds=time)
user = await client.fetch_user(member)
#await ctx.send (f"{user}")
#await ctx.send (f"{member}")
await user.timeout_for(time)
await ctx.send (f"{user} callate un rato anda {time}")
Best Regards,
Engineer
Update your py-cord library by using pip install -U git+https://github.com/pycord-development/pycord
If works , pls consider accepting answer

How come I can't use message.user.tag?

I'm trying to get the 4-digit tag of the person who used the command !hours, but discord won't recognize user.tag
import discord
from discord import message
from discord.ext import commands
client = commands.Bot(command_prefix = '!')
##########HOURS##########
chung_victor = [21, 10]
##########HOURS##########
# chung_victor
if usertag == 5308:
h = chung_victor[0]
m = chung_victor[1]
await ctx.send(f'> You currently have {h} hours and {m} minutes!')
And when I use !hours, I get the error message
Ignoring exception in command hours:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 36, in hours
usertag = message.user.tag
AttributeError: module 'discord.message' has no attribute 'user'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: module 'discord.message' has no attribute 'user'
Well, as you see to get user name you need to use it as user.name and same goes for the discriminator user.discriminator. You can refer to the code below :
#bot.command()
async def test(ctx, member : discord.Member, *,reason = None) :
user = member.discriminator
await ctx.send(f" User Tag is : {user} ")
In the example above, I set a command test and user must tag someone after a command like:
!test #Victor Chung and ! is a command_prefix.
Thank You :)

User permission check throws error, but I don't know why

I've been trying for days to find an answer with no luck. I cannot get this to work, so I have to ask it here.
How do I use #commands.has_permissions? I've tried a few things.
Here is my code.
#client.command(name="role")
#commands.has_permissions(manage_roles=True)
async def addrole(ctx, user: discord.Member, role: discord.Role):
await user.add_roles(role)
await ctx.send(f"I gave {user.name} the role {role.name}")
But I keep getting this error.
Ignoring exception in command role:
Traceback (most recent call last):
File "C:\Users\unkno\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "c:/Users/unkno/Desktop/Code_Tests/Python/discord_bot/bot2.py", line 17, in addrole
await user.add_roles(role)
File "C:\Users\unkno\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\member.py", line 641, in add_roles
await req(guild_id, user_id, role.id, reason=reason)
File "C:\Users\unkno\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\http.py", line 241, in request
raise Forbidden(r, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\unkno\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\bot.py", line 903, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\unkno\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 855, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\unkno\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
Please help.
Thanks in advance!
The reason why you're getting the exception is because the bot is missing the Manage Roles permission.
You have set it here:
#commands.has_permissions(manage_roles=True)
To fix this simply give your bot the permissions. You can also handle the exception by adding this to your code:
#addrole.error
async def addrole_error(ctx, error):
if isinstance(error, commands.errors.ErrorNameHere):
await ctx.send("You don't have permission to execute this command!")
You will just have to replace ErrorNameHere with the name of your error.

How do I fix this error with kick command

I wanted to make an kick command but i ran into this error but i couldnt find out how to fix it.
I tried giving permissions to the bot. And giving permissions to me but it all didnt work.
This is my code:
#bot.command(name='kick', aliases=['Kick'])
#commands.has_permissions(kick_members=True)
async def kick(ctx, member: discord.Member):
await ctx.send('What is the reason?')
msg = await bot.wait_for('message')
reason = msg.content
description = f'''
**Member:** = {member}
**Responsible moderator:** {ctx.author.mention}
**Reason:** {reason}
'''
embed = discord.Embed(title='Kick', description=description)
await ctx.send(content=None, embed=embed)
await member.kick(reason=reason)
This is the error:
Traceback (most recent call last):
File "C:\Users\Guido\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 83, in wrapped
ret = await coro(*args, **kwargs)
File "c:/Users/Guido/Desktop/yeet/overig/coding/discord bots/self coded/oden/code/Oden.py", line 80, in kick
await member.kick(reason=reason)
File "C:\Users\Guido\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\member.py", line 489, in kick
await self.guild.kick(self, reason=reason)
File "C:\Users\Guido\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\guild.py", line 1627, in kick
await self._state.http.kick(user.id, self.id, reason=reason)
File "C:\Users\Guido\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\http.py", line 221, in request
raise Forbidden(r, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Guido\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\bot.py", line 892, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Guido\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 797, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\Guido\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 92, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions```
It looks like the error is that the bot does not have the permission to kick a user in that server. Make sure that the bot has the Kick Members permission. The bot having permission is the only thing that matters from the API's perspective

User assigned roles using discord.py

I am trying to program a bot using discord.py for a discord server. I want to make a command that would allow users to assign themselves name colors (i.e Red or Blue) I tried to achieve this by creating roles. But I am having some trouble assigning roles using the newest form of discord.py.
#client.command()
async def role(ctx, * role: discord.Role):
user = ctx.message.author
await user.add_roles(role)
Does anyone know how to fix the error I'm getting. The error is given below:
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'tuple' object has no attribute 'id'
It seems to me that the issue is the '*'...
If you use your code and add a print line to see what is actually passed to your method you will see this result:
Code
#client.command()
async def role(ctx, * role: discord.Role):
print(role)
user = ctx.message.author
await user.add_roles(role)
Output
(<Role id=671750373761089546 name='Red'>,)
Ignoring exception in command role:
Traceback (most recent call last):
File "/home/dual/PyProjects/Discord/Chandler/env/lib/python3.7/site-packages/discord/ext/commands/core.py", line 79, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 57, in role
await user.add_roles(role)
File "/home/dual/PyProjects/Discord/Chandler/env/lib/python3.7/site-packages/discord/member.py", line 616, in add_roles
await req(guild_id, user_id, role.id, reason=reason)
AttributeError: 'tuple' object has no attribute 'id'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/dual/PyProjects/Discord/Chandler/env/lib/python3.7/site-packages/discord/ext/commands/bot.py", line 863, in invoke
await ctx.command.invoke(ctx)
File "/home/dual/PyProjects/Discord/Chandler/env/lib/python3.7/site-packages/discord/ext/commands/core.py", line 728, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/home/dual/PyProjects/Discord/Chandler/env/lib/python3.7/site-packages/discord/ext/commands/core.py", line 88, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'tuple' object has no attribute 'id'
If you remove the '*' and keep everything else the same this is what it looks like:
Code
#client.command()
async def role(ctx, role: discord.Role):
print(role)
user = ctx.message.author
await user.add_roles(role)
Output
Red
Without the '*' the role is added to the user who called the command. This only works if the role is spelled correctly and is case sensitive so I would advise implementing some sort of input validation.
Edit:
This article explains about *args and **kwargs in python. It may be useful to check it out to get a better understanding of how to pass arguments to a function :D

Resources