Error when saving data to MongoDB database - python

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.

Related

RSS Feed with Discord Bot ERROR:discord.client:Ignoring exception

I try to send periodically new RSS feeds to a Discord channel for asyncio. Here is my Code
discord_token = "Token"
discord_channel_id = "ChannelID"
feed_urls = ["URL1", "URL2"]`your text`
intents = discord.Intents.default()
intents.members = True
client = discord.Client(intents=intents)
async def send_discord_message(message):
channel = client.get_channel(int(discord_channel_id))
if channel is not None:
await channel.send(message)
else:
print(f"Could not send message to channel with ID {discord_channel_id}")
async def check_feeds():
conn = sqlite3.connect("/home/feed_entries.db")
c = conn.cursor()
c.execute("""CREATE TABLE IF NOT EXISTS entries (
link TEXT PRIMARY KEY,
title TEXT,
feed_url TEXT
)
""")
conn.commit()
while True:
for feed_url in feed_urls:
try:
feed_entries = feedparser.parse(feed_url)["entries"]
for entry in feed_entries:
c.execute("SELECT * FROM entries WHERE link=?", (entry.link,))
result = c.fetchone()
if result is None:
c.execute("INSERT INTO entries VALUES (?,?,?)", (entry.link, entry.title, feed_url))
conn.commit()
logging.info("New Feed in", feed_url)
message = f"New entry in feed {feed_url}: {entry.title}\n{entry.link}"
await send_discord_message(message)
except Exception as e:
logging.error(f"Error while fetching from {feed_url}: {e}")
try:
await asyncio.wait_for(asyncio.sleep(600), timeout=300)
except asyncio.exceptions.CancelledError:
pass
async def delete_old_entries():
conn = sqlite3.connect("/home/feed_entries.db")
c = conn.cursor()
while True:
c.execute("SELECT * FROM entries")
"Code to delete old entries "
await asyncio.sleep(120)
#client.event
async def on_ready():
logging.info("Bot is ready")
await asyncio.create_task(check_feeds())
await asyncio.create_task(delete_old_entries())
async def main():
logging.info("Starte Login")
try:
await client.start(discord_token)
logging.info("Login erfolgreich")
except Exception as e:
logging.error(f"Fehler beim Login: {e}")
await client.wait_until_disconnected()
asyncio.run(main())
And i got this Error:
ERROR:discord.client:Ignoring exception in on_ready
Traceback (most recent call last):
File "/usr/lib/python3.9/asyncio/tasks.py", line 654, in sleep
return await future
asyncio.exceptions.CancelledError
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/lib/python3.9/asyncio/tasks.py", line 492, in wait_for
fut.result()
asyncio.exceptions.CancelledError
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/usr/local/lib/python3.9/dist-packages/discord/client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "/home/RSS.py", line 106, in on_ready
await asyncio.create_task(check_feeds())
File "/home/RSS.py", line 77, in check_feeds
await asyncio.wait_for(asyncio.sleep(600), timeout=300)
File "/usr/lib/python3.9/asyncio/tasks.py", line 494, in wait_for
raise exceptions.TimeoutError() from exc
asyncio.exceptions.TimeoutError
It came to this error after I changed these lines:
try:
await asyncio.wait_for(asyncio.sleep(600), timeout=300)
except asyncio.exceptions.CancelledError:
pass
I added them because of the following error:
WARNING:discord.gateway:Shard ID None heartbeat blocked for more than 35990 seco nds.
Loop thread traceback (most recent call last):
File "/home//RSS.py", line 106, in
asyncio.run(main())
Originally it looked like this:
await asyncio.sleep(600)
I don't know if I have a thinking error or a logical problem. I do not see it. Maybe you?

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>

Python asyncio.exceptions.CancelledError

I'm trying to write a program that receives data about the lots of a marketplace via a websocket. Then the program compares each lot with my list of lots and if the lot is profitable it buys it. After starting the program runs for 5-10 minutes after which I get an error.
Traceback (most recent call last):
File "C:\Users\Администратор.WIN-TJGJ26MRVI4\AppData\Local\Programs\Python\Python310\lib\site-packages\websockets\legacy\protocol.py", line 968, in transfer_data
message = await self.read_message()
File "C:\Users\Администратор.WIN-TJGJ26MRVI4\AppData\Local\Programs\Python\Python310\lib\site-packages\websockets\legacy\protocol.py", line 1038, in read_message
frame = await self.read_data_frame(max_size=self.max_size)
File "C:\Users\Администратор.WIN-TJGJ26MRVI4\AppData\Local\Programs\Python\Python310\lib\site-packages\websockets\legacy\protocol.py", line 1113, in read_data_frame
frame = await self.read_frame(max_size)
File "C:\Users\Администратор.WIN-TJGJ26MRVI4\AppData\Local\Programs\Python\Python310\lib\site-packages\websockets\legacy\protocol.py", line 1170, in read_frame
frame = await Frame.read(
File "C:\Users\Администратор.WIN-TJGJ26MRVI4\AppData\Local\Programs\Python\Python310\lib\site-packages\websockets\legacy\framing.py", line 99, in read
data = await reader(length)
File "C:\Users\Администратор.WIN-TJGJ26MRVI4\AppData\Local\Programs\Python\Python310\lib\asyncio\streams.py", line 707, in readexactly
await self._wait_for_data('readexactly')
File "C:\Users\Администратор.WIN-TJGJ26MRVI4\AppData\Local\Programs\Python\Python310\lib\asyncio\streams.py", line 501, in _wait_for_data
await self._waiter
asyncio.exceptions.CancelledError`
with open('steam.json', encoding="utf-8") as f:
items_em = json.load(f)
async def main():
async with websockets.connect("wss://wsn.dota2.net/wsn/") as client:
await client.send('newitems_go')
while True:
data = json.loads(await client.recv())
data = json.loads(data['data'])
if float(data.get('ui_price')) >= float(min_price):
for item_em in items_em["items"]:
if item_em['name'] == data.get('i_market_hash_name'):
name_tm = data.get('i_market_hash_name')
price_tm = data.get('ui_price')
try:
price_em = item_em['prices'].get('steam').get('price')
except AttributeError:
continue
if price_tm and price_em != 0 and price_em is not None:
discount = round(float(price_tm)/73/float(price_em)*(-10000)+100, 1)
if discount >= float(min_discount):
resp = requests.get(f'https://market.csgo.com/api/v2/buy-for?key={your_secret_key}&hash_name={name_tm}&price={price_tm * 100}&partner={partner}&token={token}')
print(f'{name_tm} {price_tm} {discount}% {resp.text}')
asyncio.run(main())
What is my mistake?

how to get posts in a telegram megagroup

I am trying to get the post's text of a megagroup in Telegram using Telethon. I could get the messages from chats however megagroup's posts cannot be retrieved using the same method (How to get channels and groups data from my Telegram account?(Python)). Are megagroups open to fetch their posts by being a simple user using telethon?
Code:
def get_entity_data(entity_id, limit):
entity = client.get_entity(entity_id)
posts = client(GetHistoryRequest(peer=entity, limit=limit, offset_date=None, offset_id=0, max_id=0, min_id=0, add_offset=0, hash=0))
messages = []
for message in posts.messages:
messages.append(message.message)
return messages
result = client(GetDialogsRequest(offset_date=None, offset_id=0, offset_peer=InputPeerEmpty(), limit=100, hash=0)) entities = result.chats entities.reverse()
for entity in entities:
title = entity.title
messages = get_entity_data(entity.id, 10)
print(title + ' :')
print(messages)
print('#######')
and the error message is:
Traceback (most recent call last):
File "./search_message3.py", line 61, in <module>
messages = get_entity_data(entity.id, 10)
File "./search_message3.py", line 48, in get_entity_data
entity = client.get_entity(entity_id)
File "/home/carlos/.local/lib/python3.8/site-packages/telethon/sync.py", line 39, in syncified
return loop.run_until_complete(coro)
File "/home/carlos/.miniconda3/lib/python3.8/asyncio/base_events.py", line 616, in run_until_complete
return future.result()
File "/home/carlos/.local/lib/python3.8/site-packages/telethon/client/users.py", line 316, in get_entity
chats = (await self(
File "/home/carlos/.local/lib/python3.8/site-packages/telethon/client/users.py", line 30, in __call__
return await self._call(self._sender, request, ordered=ordered)
File "/home/carlos/.local/lib/python3.8/site-packages/telethon/client/users.py", line 84, in _call
result = await future
telethon.errors.rpcerrorlist.PeerIdInvalidError: An invalid Peer was used. Make sure to pass the right peer type and that the value is valid (for instance, bots cannot start conversations) (caused by GetChatsRequest)
Carlos

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