ERROR in my minecraft bot discord.py . KeyError - python

#bot.command()
async def profile(ctx):
await open_account(ctx.author)
user = ctx.author
users = await get_shards_data()
shards_amt = users[str(user.id)]["shards"]
em = discord.Embed(title=f'{ctx.author.name} SHARDS',color = discord.Color.red())
em.add_field(name="SHARDS ", value=shards_amt, inline = False)
em.add_field(name ="TOTAL ITEMS", value = "`stone` `coal` `iron` `gold` `redstone` `emerald` `diamond`", inline = False)
em.add_field(name = "YOUR ITEMS", value = "Type s;inventory or s;inv to view your items list")
await ctx.send(embed= em)
#bot.command(aliases=['inv'])
async def inventory(ctx):
await open_account(ctx.author)
user = ctx.author
users = await get_items_data()
stone_amt = users[str(user.id)]["stone"]
coal_amt = users[str(user.id)]["coal"]
iron_amt = users[str(user.id)]["iron"]
gold_amt = users[str(user.id)]["gold"]
redstone_amt = users[str(user.id)]["redstone"]
emerald_amt = users[str(user.id)]["emerald"]
diamond_amt = users[str(user.id)]["diamond"]
em = discord.Embed(title=f'{ctx.author.name} INVENTORY',color = discord.Color.red())
em.add_field(name="STONES", value=stone_amt, inline = False)
em.add_field(name="COAL", value=coal_amt, inline = False)
em.add_field(name="IRON", value=iron_amt, inline = False)
em.add_field(name="GOLD", value=gold_amt, inline = False)
em.add_field(name="REDSTONE", value=redstone_amt, inline = False)
em.add_field(name="EMERALD", value= emerald_amt, inline = False)
em.add_field(name="DIAMOND", value=diamond_amt, inline = False)
await ctx.send(embed = em)
#bot.command()
async def mine(ctx):
await open_account(ctx.author)
user = ctx.author
users = await get_shards_data()
a = 9, 10, 16, 23, 11, 26
b = "stone", "coal", "iron", "gold", "redstone", "emerald", "diamond","stone", "coal" ,"iron", "stone"
c = random.choice(a)
d = random.choice(b)
e = 2, 3, 4, 5, 6, 2, 8, 9, 14, 13, 16, 18,20
f = random.choice(e)
em = discord.Embed(title = f'{ctx.author.name} you mined the ground')
em.add_field(name = "SHARDS", value = f"`You got {c} shards`", inline = False)
em.add_field(name = "ITEMS", value = f"`You got {f} {d}`")
await ctx.send(embed =em)
users[str(user.id)]["shards"] += c
if d == "stone":
users[str(user.id)]["stone"] += f
elif d == "coal":
users[str(user.id)]["coal"] += f
elif d == "iron":
users[str(user.id)]["iron"] += f
else:
users[str(user.id)]["gold"] += f
with open("items.json", 'r') as f:
json.dump(users,f)
with open("shards.json",'w') as f:
json.dump(users,f)
I am trying to make a minecraft bot in which my i get random shards and items after mining, shards are updating in my shards balance but, the items are not updating and in inventory command it is giving error.Pease tell how to do i am facing difficulty in it
Ignoring exception in command mine:
Traceback (most recent call last):
File "C:\Users\manoj\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\manoj\OneDrive\Desktop\Coding and editing\discord bot\Mezuhashi.py", line 79, in mine
users[str(user.id)]["coal"] += f
KeyError: 'coal'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\manoj\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\manoj\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\manoj\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: KeyError: 'coal'
THE MINE COMMAND ERROR
Ignoring exception in command inventory:
Traceback (most recent call last):
File "C:\Users\manoj\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\manoj\OneDrive\Desktop\Coding and editing\discord bot\Mezuhashi.py", line 36, in inventory
stone_amt = users[str(user.id)]["stone"]
KeyError: '773913180271280129'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\manoj\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\manoj\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\manoj\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: KeyError: '773913180271280129'
THE INVENTORY COMMAND ERROR

Related

Exception on "add_roles" function for discord.py

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>

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: module 'discord.ext.commands' has no attribute 'qualified_name' | Discord.py

I'm tryna make a help command. But when I run >help <cmd>
I get this error:
AttributeError: module 'discord.ext.commands' has no attribute 'qualified_name'
Here is the code:
class HelpCommand(commands.HelpCommand):
color = 0x171616
def footer(self):
return f"{self.clean_prefix}{self.invoked_with} <command> for more details"
def get_command_signature(self, command):
return f"```yaml\n{self.clean_prefix}{command.qualified_name} {command.signature}```"
async def send_cog_help(self, cog):
em = discord.Embed(
title=f"***{cog.qualified_name}** Commands", colour=self.color)
if cog.description:
em.description = cog.description
filtered = await self.filter_commands(cog.get_commmands(), sort=True)
for command in filtered:
em.add_field(name=command.qualified_name,
value=command.short_doc or "No Description Provided")
em.set_footer(text=self.footer())
await self.get_destination().send(embed=em)
async def send_command_help(self, command):
em = discord.Embed(title=command.qualified_name, color=self.color)
if command.help:
em.description = command.help
em.add_field(name="Syntax", value=self.get_command_signature(commands))
em.set_footer(text=self.footer())
await self.get_destination().send(embed=em)
async def send_bot_help(self, mapping):
em = discord.Embed(title="Loofah Help", color=self.color)
for cog, commands in mapping.items():
if not cog:
continue
filtered = await self.filter_commands(commands, sort=True)
if filtered:
value = "\t".join(f"`{i.name}`" for i in commands)
em.add_field(name=cog.qualified_name, value=value)
em.set_footer(text=self.footer())
await self.get_destination().send(embed=em)
Full traceback error:
Traceback (most recent call last):
File "C:\Users\pc\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\pc\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\help.py", line 882, in command_callback
return await self.send_command_help(cmd)
File "D:\Kunnu\Loofah Rewrite\cogs\help.py", line 34, in send_command_help
em.add_field(name="Syntax", value=self.get_command_signature(commands))
File "D:\Kunnu\Loofah Rewrite\cogs\help.py", line 13, in get_command_signature
return f"```yaml\n{self.clean_prefix}{command.qualified_name} {command.signature}```"
AttributeError: module 'discord.ext.commands' has no attribute 'qualified_name'
Any help is appreciated

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)

Opening a specific file with Python but an error occurred

I am currently trying to make my discord.py bot opening the specific file: {guild.id}_config.yaml, here is my following code:
for guild in self.bot.guilds:
if guild.get_member(before.id) is None:
continue
else:
def get_channel_id():
with open(f'configuration/{guild.id}_config.yaml', 'r') as id_accessor:
ID = yaml.safe_load(id_accessor)
id_string: discord.TextChannel = guild.get_channel(ID['plugins']['logging']['type']['member_log']['channel'])
return id_string
MemberLoggingChannel = get_channel_id()
if before.avatar != after.avatar:
AvatarEmbed = discord.Embed(title=f":pencil: {before.name} Changed His/Her Avatar", colour=0xa6f7ff)
AvatarEmbed.set_thumbnail(url=after.avatar_url)
await MemberLoggingChannel.send(embed=AvatarEmbed)
elif before.name != after.name:
NameEmbed = discord.Embed(title=f":pencil: {after.name} Changed His/Her Username", colour=0xa6f7ff)
NameEmbed.add_field(name="Before", value=f"{before.name}", inline=True)
NameEmbed.add_field(name="After", value=f"{after.name}", inline=False)
await MemberLoggingChannel.send(embed=NameEmbed)
elif before.discriminator != after.discriminator:
DiscriminatorEmbed = discord.Embed(title=f":pencil: {after.name} Changed His/Her Username", colour=0xa6f7ff)
DiscriminatorEmbed.add_field(name="Before", value=f"{before.discriminator}", inline=True)
DiscriminatorEmbed.add_field(name="After", value=f"{after.discriminator}", inline=False)
await MemberLoggingChannel.send(embed=DiscriminatorEmbed)
But for some reason the guild id isn't in the connected guilds of my bot. Here is the list of connected guild IDs:
631100984176672768
650736030319771674
613660252545613834
And the error looks like so:
Ignoring exception in on_user_update
Traceback (most recent call last):
File "whatever file path", line 312, in _run_event
await coro(*args, **kwargs)
File "whatever file path", line 111, in on_user_update
MemberLoggingChannel = get_channel_id()
File "whatever file path", line 104, in get_channel_id
with open(f'configuration/{guild.id}_config.yaml', 'r') as id_accessor:
FileNotFoundError: [Errno 2] No such file or directory: 'configuration/613660252545613834_config.yaml'
How can I fix the problem, and what am I wrong here?

Categories