Exception on "add_roles" function for discord.py - python

I'm trying to add roles to users by listening for Reaction. Although it will succeed, there will always be errors after execution. I want to ask how to solve this problem?
Codes there:
#client.event
async def on_raw_reaction_add(payload: discord.RawReactionActionEvent):
if payload.message_id == 0000:
guild: discord.Guild = client.get_guild(payload.guild_id)
if payload.emoji.name == "someEmoji":
role0: discord.Role = guild.get_role(1111)
await payload.member.add_roles(role0)
elif payload.emoji.name == "someEmoji":
role1: discord.Role = guild.get_role(2222)
await payload.member.add_roles(role1)
Logs(With pysnooper):
19:50:26.101973 line 54 await member.add_roles(role1)
19:50:26.104641 return 54 await member.add_roles(role1)
Return value:.. <Future pending>
Starting var:.. payload = <RawReactionActionEvent message_id=1111...d=None> event_type='' member=None>
Starting var:.. guild = <Guild id=1111 name='' shard_id=0 chunked=True member_count=0>
Starting var:.. member = <Member id=00000 name='member'>
Starting var:.. role1 = <Role id=11111 name='role1'>
19:50:26.588117 call 54 await member.add_roles(role1)
19:50:26.590784 exception 54 await member.add_roles(role1)
Exception:..... StopIteration
[2022-12-20 19:50:26] [ERROR ] discord.client: Ignoring exception in on_raw_reaction_remove
Traceback (most recent call last):
File "C:\Users\****\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "main.py", line 54, in on_raw_reaction_remove
await member.remove_roles(en_role)
File "C:\Users\****\AppData\Local\Programs\Python\Python38\lib\site-packages\pysnooper\tracer.py", line 367, in __exit__
start_time = self.start_times.pop(calling_frame)
KeyError: <frame at 0x000001A1014E6DD0, file 'main.py', line 54, code on_raw_reaction_remove>

Related

Error when saving data to MongoDB database

I want to make a role assignment using the support approval on the discord server, in general, a complex system.. To do this, I need to save the message id and the id of the message author who needs to be assigned a role, all the code is working, an error in the line of code associated with the database.
event code
cluster = MongoClient('mongodb+srv://corry:pa4-pD6-3Dj-AdT#cluster0.gi8x6.mongodb.net/?retryWrites=true&w=majority')
db = cluster.RolesData
roles = db.RolesCollection
#bot.event
async def on_message(message):
msg = message.content.lower()
request = ['роль', 'хочу роль', 'дайте роль', 'нужна роль']
if msg in request:
for i in orgs:
if not message.author.display_name.split(' ')[0].replace('[', '') in orgs:
await message.channel.send(f'`[ROLES]`: {message.author.mention}, тег организации не найден!')
break
if i == message.author.display_name.split(' ')[0].replace('[', ''):
guild = bot.get_guild(831511376425123882)
role = discord.utils.get(guild.roles, id=orgs[i])
await message.channel.send(f'`[ROLES]`: {message.author.mention}, ваш запрос на получение роли был отправлен саппортам!')
embed = discord.Embed(
title='Запрос на получение роли!',
description='✅ - выдать роль\n❌ - отклонить запрос\n🖊️ - изменить никнейм\n📋 - запросить статистику',
color=0x000000
)
embed.add_field(name=f'Пользователь:', value=f'{message.author.mention}', inline=False)
embed.add_field(name=f'Никнейм:', value=f'{message.author.display_name}', inline=False)
embed.add_field(name=f'Роль для выдачи:', value=f'{role.mention}', inline=False)
embed.set_thumbnail(url='https://psv4.userapi.com/c537232/u356224017/docs/d1/416eb92aec38/rodina.png?extra=2E9CwKZ0PIjnG8aaNkwehlHwjxlycBfGx-4p20ABm3mPI4jNpdV1OXaUUA9zGA4Q04VM21UezrXsjtqC411Xbh-Ro7rW1L4OGgNxpcQv3lvfOYCb-Irn-_-51AaQa2fpNDZhHm80dvZm1HlR1ZWoDigw')
embed.set_image(url=message.author.avatar_url)
msgemb = await bot.get_channel(851413212485779466).send(embed=embed)
await msgemb.add_reaction('✅')
await msgemb.add_reaction('❌')
await msgemb.add_reaction('🖊️')
await msgemb.add_reaction('📋')
roles_post = {
'm_id':msg_db.id,
'user':msg_db.author
}
if roles.count_documents({'m_id':message.id}) == 0:
roles.insert_one(roles_post)
else:
await message.channel.send(f'`[ROLES]`: {message.author.mention}, вы уже отправили запрос на получение роли!')
error code
Traceback (most recent call last):
File "C:\Users\Хозяин\AppData\Local\Programs\Python\Python39\lib\site-packages\pymongo\srv_resolver.py", line 89, in _resolve_uri
results = _resolve(
File "C:\Users\Хозяин\AppData\Local\Programs\Python\Python39\lib\site-packages\pymongo\srv_resolver.py", line 43, in _resolve
return resolver.resolve(*args, **kwargs)
File "C:\Users\Хозяин\AppData\Local\Programs\Python\Python39\lib\site-packages\dns\resolver.py", line 1305, in resolve
return get_default_resolver().resolve(qname, rdtype, rdclass, tcp, source,
File "C:\Users\Хозяин\AppData\Local\Programs\Python\Python39\lib\site-packages\dns\resolver.py", line 1176, in resolve
timeout = self._compute_timeout(start, lifetime)
File "C:\Users\Хозяин\AppData\Local\Programs\Python\Python39\lib\site-packages\dns\resolver.py", line 997, in _compute_timeout
raise Timeout(timeout=duration)
dns.exception.Timeout: The DNS operation timed out after 21.201510190963745 seconds
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\Хозяин\Desktop\rodina\main.py", line 5, in <module>
cluster = MongoClient('mongodb+srv://corry:pa4-pD6-3Dj-AdT#cluster0.gi8x6.mongodb.net/?retryWrites=true&w=majority')
File "C:\Users\Хозяин\AppData\Local\Programs\Python\Python39\lib\site-packages\pymongo\mongo_client.py", line 704, in __init__
res = uri_parser.parse_uri(
File "C:\Users\Хозяин\AppData\Local\Programs\Python\Python39\lib\site-packages\pymongo\uri_parser.py", line 542, in parse_uri
nodes = dns_resolver.get_hosts()
File "C:\Users\Хозяин\AppData\Local\Programs\Python\Python39\lib\site-packages\pymongo\srv_resolver.py", line 121, in get_hosts
_, nodes = self._get_srv_response_and_hosts(True)
File "C:\Users\Хозяин\AppData\Local\Programs\Python\Python39\lib\site-packages\pymongo\srv_resolver.py", line 101, in _get_srv_response_and_hosts
results = self._resolve_uri(encapsulate_errors)
File "C:\Users\Хозяин\AppData\Local\Programs\Python\Python39\lib\site-packages\pymongo\srv_resolver.py", line 97, in _resolve_uri
raise ConfigurationError(str(exc))
pymongo.errors.ConfigurationError: The DNS operation timed out after 21.201510190963745 seconds
Для продолжения нажмите любую клавишу . . .
Judging by this bit self._raise_connection_failure(error) in your error message, I believe the issue lies within the fact that you're not successfully connecting to your db in the first place.

AttributeError: 'PermissionOverwrite' object has no attribute 'items' when editing a VoiceChannel

This line of code
await channel.edit(user_limit=0, name="💤|Dormant", overwrites=discord.PermissionOverwrite(read_messages = False))
Sourcing from
elif before.channel is not None and after.channel is None: # User left a channel
channel = before.channel
if len(channel.members) == 0:
print("debug 3")
if str(channel.name).startswith("Currently"):
print("debug 4")
await channel.edit(user_limit=0, name=":zzz:|Dormant", overwrites=discord.PermissionOverwrite(read_messages = False))
await asyncio.sleep(600)
await channel.edit(name="Waiting for game to be played...", roles=None, reason="The voice channel was empty")
await channel.set_permissions(role=discord.Role.name())
Returns
AttributeError: 'PermissionOverwrite' object has no attribute 'items'
Sourcing from
Ignoring exception in on_voice_state_update
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "z:\Programming\Python\Discord Bots\Channel name changer\main.py", line 37, in on_voice_state_update
await channel.edit(user_limit=0, name="💤|Dormant", overwrites=discord.PermissionOverwrite(read_messages = False))
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\channel.py", line 733, in edit
await self._edit(options, reason=reason)
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\abc.py", line 289, in _edit
for target, perm in overwrites.items():
AttributeError: 'PermissionOverwrite' object has no attribute 'items'
Why does it return that error, and what in the code needs to be addressed for it to function properly?
If you want the overwrite to apply to everyone, you need to use the #everyone role for set_permissions.
await channel.set_permissions(
ctx.guild.default_role, # applies it to #everyone of the guild
overwrite=discord.PermissionOverwrite(read_messages=False)
)

ValueError expected 2 got 1 discord.py

#commands.command()
#has_permissions(ban_members=True)
async def unban(self, ctx, *, member):
embed = discord.Embed(title="Unban", description=f"Unbanned - {member}", colour=discord.Colour.purple())
banned_users = await ctx.guild.bans()
member_name, member_discriminator = member.split('#')
for ban_entry in banned_users:
user = ban_entry.user
if (user.name, user.discriminator) == (member_name, member_discriminator):
await ctx.guild.unban(user)
if (member_name, member_discriminator) in banned_users:
await ctx.send(f'Error unbanning {member.mention}.')
return
else:
pass
await ctx.send(embed=embed)
print(f'{current_time} {member} has been unbanned by #{ctx.message.author}. Server Name: {ctx.guild.name}, Server ID: {ctx.guild.id}\n')
with open('textfiles/text-logs/unban-log.txt', 'a') as unbanlog:
unbanlog.writelines(f'{current_time} {member} has been unbanned by #{ctx.message.author}. Server Name: {ctx.guild.name}, Server ID: {ctx.guild.id}\n')
return
I am trying to make it so it checks if a user has been unbanned before it sends the message that they have been unbanned. But I keep on getting ValueError
Here is the exact error:
Ignoring exception in on_command_error
Traceback (most recent call last):
File "C:\Users\ajkit\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\ajkit\Desktop\Programming\Python\discord.py\Galactia\cogs\ModeratorTools.py", line 105, in unban
member_name, member_discriminator = member.split('#')
ValueError: not enough values to unpack (expected 2, got 1)
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\ajkit\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "c:\Users\ajkit\Desktop\Programming\Python\discord.py\Galactia\cogs\ErrorHandling.py", line 21, in on_command_error
raise Error
File "C:\Users\ajkit\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\ajkit\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\ajkit\AppData\Local\Programs\Python\Python39\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: ValueError: not enough values to unpack (expected 2, got 1)
I suggest converting the member argument to a Member object like so. You can then use the attributes of a discord.Member object for discriminator and etc.
async def unban(self, ctx, member:commands.MemberConverter):
You can retrieve the discriminator by doing member.discriminator and their name by using member.name. Check out the discord.Member docs.
I also suggest just checking if the user and member are the same or not instead of checking their discriminator and name.
if user == member:
You should also delete the exception handling if unbanning doesn't work. This is because if it doesn't unban properly, it will automatically raise an error.
Then, in the strings at the end, cast member to type string so that it is readable.
In total, the implementation would look something like this:
#commands.command()
#has_permissions(ban_members=True)
async def unban(self, ctx, member:commands.MemberConverter):
embed = discord.Embed(title="Unban", description=f"Unbanned - {member}", colour=discord.Colour.purple())
banned_users = await ctx.guild.bans()
for ban_entry in banned_users:
user = ban_entry.user
if user == member:
await ctx.guild.unban(user)
await ctx.send(embed=embed)
print(f'{current_time} {str(member)} has been unbanned by #{ctx.message.author}. Server Name: {ctx.guild.name}, Server ID: {ctx.guild.id}\n')
with open('textfiles/text-logs/unban-log.txt', 'a') as unbanlog:
unbanlog.writelines(f'{current_time} {str(member)} has been unbanned by #{ctx.message.author}. Server Name: {ctx.guild.name}, Server ID: {ctx.guild.id}\n')
return

Trying to get the number of warns a users has and send it discord.py

I get a new error now. I edited smth now and i get this error. What to do. New code is given below
#commands.command()
async def warn(self, ctx, user:discord.Member, *, reason=None):
user_id = user.id
if collection.count_documents({"userid":user.id}) == 0:
collection.insert_one({"userid":user.id,"count":0})
if reason == None:
return await ctx.send("Please mention a reason!")
elif user == None:
return await ctx.send("Please mention a member!")
user = collection.find_one({"userid":user.id})
current_count = user["count"]
new_count = current_count + 1
collection.update_one({"userid":user.id}, {"$set": {"count": new_count}})
em = discord.Embed(title = "Member Warned!", description = f"Warned {user.mention} for **{reason}** | They now have {new_count} warnings!", timestamp = ctx.message.created_at, color = 0xFF0000)
em.set_footer(text=f'Warned By {ctx.author} | ID: {ctx.author.id}', icon_url = ctx.author.avatar_url)
await ctx.send(embed = em)``` This is the code
Ignoring exception in command warn:
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/HorribleSentimentalParallelprocessing/cogs/warn.py", line 30, in warn
collection.update_one({"userid":user.id}, {"$set": {"count": new_count}})
AttributeError: 'dict' object has no attribute 'id'
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: 'dict' object has no attribute 'id'```
You are trying to find the user without any warnings. You were also adding warnings to the author himself instead of the user.
#commands.command()
async def warn(self, ctx,user: discord.Member, *,reason=None):
if collection.count_documents({"userid":user.id}) == 0:
collection.insert_one({"userid":user.id,"count":0})
if reason is None:
return await ctx.send("Please mention a reason!")
user_doc = collection.find_one({"userid":user.id})
current_count = user_doc["count"]
new_count = current_count + 1
collection.update_one({"userid":user.id}, {"$set": {"count": new_count}})
em = discord.Embed(title = "Member Warned!", description = f"Warned {user.mention} for **{reason}** | They now have {new_count} warnings!", timestamp = ctx.message.created_at, color = 0xFF0000)
em.set_footer(text=f'Warned By {ctx.author} | ID: {ctx.author.id}')
collection.update_one({"userid":ctx.author.id}, {"$inc": {"count": 1}})
await ctx.send(embed = em)

"Command raised an exception: AttributeError 'Nonetype' object has no attribute 'id'" when giving a set role

I'm trying to make a Reaction Role bot with the ability to set the role given when reacted. I have tried:
verifyroleid = int(0)
#bot.command(pass_context=True)
#has_permissions(administrator=True)
async def set(ctx, *, roleid=None):
em = discord.Embed(title="yBot | VERIFY")
em.add_field(name="SUCCESS: ",value="Set {} as 'verify' role!".format(roleid))
em.set_footer(text="© 2020 - Powered by yanuu ;k#2137")
verifyroleid == roleid
await ctx.send(embed=em)
#bot.command(pass_context=True)
async def verify(ctx):
em = discord.Embed(title="yBOT | VERIFY")
em.add_field(name="REACT: ", value="React '✅' to this message to get verified!", inline=False)
em.set_footer(text="© 2020 - Powered by yanuu ;k#2137")
message = await ctx.send(embed=em)
await message.add_reaction("✅")
reaction, user = await bot.wait_for("reaction_add")
def check(reaction, user):
return user != bot.user and str(reaction.emoji) in ["✅"]
while True:
try:
reaction, user = await bot.wait_for("reaction_add")
if str(reaction.emoji) == "✅":
await message.remove_reaction(reaction, user)
role = discord.utils.get(ctx.guild.roles, id=verifyroleid)
await discord.Member.add_roles(user, role)
except asyncio.TimeoutError:
await message.delete()
return
But it results in an error:
Traceback (most recent call last):
File "C:\Users\macio\AppData\Roaming\Python\Python38\site-packages\discord\client.py", line 333, in _run_event
await coro(*args, **kwargs)
File "C:\Users<..>\Documents\pythontest\diskord-test.py", line 99, in on_command_error
raise error
File "C:\Users<..>\AppData\Roaming\Python\Python38\site-packages\discord\ext\commands\bot.py", line 903, in invoke
await ctx.command.invoke(ctx)
File "C:\Users<..>\AppData\Roaming\Python\Python38\site-packages\discord\ext\commands\core.py", line 859, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users<..>\AppData\Roaming\Python\Python38\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: 'NoneType' object has no attribute 'id'
How can I fix this?

Categories