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?
Related
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.
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)
)
#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
So I'm working on a cogs that can make my bot work as a modmail. So far, here's the code:
import discord
from discord.ext.commands import Bot
from discord.ext import commands
import asyncio
client = commands.Bot(command_prefix="!")
class Modmail(commands.Cog):
def __init__(self, bot):
self.bot = bot
#commands.Cog.listener()
async def on_message(self, message):
empty_array = []
modmail_channel = discord.utils.get(message.guild.get_all_channels(), name="modmail")
if message.author == message.user:
return
if str(message.channel.type) == "private":
if message.attachments != empty_array:
files = message.attachments
await modmail_channel.send("<#" + message.author.id + ">: ")
for file in files:
await modmail_channel.send(file.url)
else:
await modmail_channel.send("<#" + str(message.author.id) + ">: " + message.content)
elif str(message.channel) == "modmail" and message.content.startswith("<"):
member_object = message.mentions[0]
if message.attachments != empty_array:
files = message.attachments
await member_object.send("**[MOD]** " + "**" + message.author.display_name + "**: ")
for file in files:
await member_object.send(file.url)
else:
index = message.content.index(" ")
string = message.content
mod_message = string[index:]
await member_object.send("**[MOD]** " + "**" + message.author.display_name + "**: " + mod_message)
def setup(bot):
bot.add_cog(Modmail(bot))
So the problem is, when I run it, I get this error:
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\Blue\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "c:\Users\Blue\Documents\Project\Articuno (Canary)\automod.py", line 39, in on_message
channel = discord.utils.get(guild.channels, name="📝║logs")
AttributeError: 'NoneType' object has no attribute 'channels'
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\Blue\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "c:\Users\Blue\Documents\Project\Articuno (Canary)\modmail.py", line 14, in on_message
modmail_channel = discord.utils.get(message.guild.get_all_channels(), name="modmail")
AttributeError: 'NoneType' object has no attribute 'get_all_channels'
What should I fix this? Because as far as I know, message and guild can't work together. But if I do message.get_all_channels(), it will have another error!
I have a rewrite version discord.py.If message have content, error does not happened.I need that error does not happened if message have not content.
My code:
#client.command(pass_context = True)
def async search(ctx,message):
...
some code
...
if members_count < voice_channel.user_limit:
message.content += ' '
print(message.content)
invite = await channel.create_invite(max_age=0)
avatar = user.avatar_url
if message == '':
message_for_emb = '\u200b'
elif message != '':
message_for_emb = ':white_small_square: {}'.format(message)
if user.default_avatar_url == avatar:
avatar = 'https://i.imgur.com/XjeDXnB.png'
embed = discord.Embed(description=members, colour=discord.Embed.Empty)
embed.set_author(name='В поисках +{} в {} {}'.format((voice_channel.user_limit - members_count),
voice_channel.category.name,voice_channel.name), icon_url=avatar)
embed.add_field(name=message_for_emb,
value='Зайти: {} :white_check_mark:'.format(invite.url), inline=False)
await channel.send(embed=embed)
Full traceback:
Ignoring exception in command search:
Traceback (most recent call last):
File "C:\Users\Даниил\PycharmProjects\discordbot\venv\lib\site-packages\discord\ext\commands\bot.py", line 886, in invoke
yield from ctx.command.invoke(ctx)
File "C:\Users\Даниил\PycharmProjects\discordbot\venv\lib\site-packages\discord\ext\commands\core.py", line 491, in invoke
yield from self.prepare(ctx)
File "C:\Users\Даниил\PycharmProjects\discordbot\venv\lib\site-packages\discord\ext\commands\core.py", line 455, in prepare
yield from self._parse_arguments(ctx)
File "C:\Users\Даниил\PycharmProjects\discordbot\venv\lib\site-packages\discord\ext\commands\core.py", line 369, in _parse_arguments
transformed = yield from self.transform(ctx, param)
File "C:\Users\Даниил\PycharmProjects\discordbot\venv\lib\site-packages\discord\ext\commands\core.py", line 249, in transform
raise MissingRequiredArgument(param)
discord.ext.commands.errors.MissingRequiredArgument: message is a required argument that is missing.
The way commands parse arguments means that defining
async def search(ctx, message):
means that search requires a word message as part of the command invocation. If you instead want to capture the remainder of the message, you can use the keyword-only argument syntax:
async def search(ctx, *, message)
This feature is documented here.