AttributeError: 'Select' object has no attribute 'get' - python

I'm making a discord bot with python and I want a select menu for my top command. But when I try to run the command I get:
Traceback (most recent call last):
File "C:\Users\zhsos\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord_slash\client.py", line 1353, in invoke_command
await func.invoke(ctx, **args)
File "C:\Users\zhsos\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord_slash\model.py", line 210, in invoke
return await self.func(*args, **kwargs)
File "c:\Users\zhsos\OneDrive\Documents\IA bot\python_bot.py", line 505, in _top
await topselect(ctx)
File "c:\Users\zhsos\OneDrive\Documents\IA bot\python_bot.py", line 116, in topselect
top_msg = await ctx.send(embed=top_embed, components=[Select(
File "C:\Users\zhsos\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord_slash\context.py", line 215, in send
if components and not all(comp.get("type") == 1 for comp in components):
File "C:\Users\zhsos\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord_slash\context.py", line 215, in <genexpr>
if components and not all(comp.get("type") == 1 for comp in components):
AttributeError: 'Select' object has no attribute 'get'
I can't find the solution anywhere
This is the function I have:
async def topselect(ctx):
top_msg = await ctx.send(embed=top_embed, components=[Select(
placeholder='Select',
options=[
SelectOption(label='Option 1', value='1')
],
custom_id='topselect'
)])
interaction = await client.wait_for('select_option', check=lambda inter:inter.custom_id == topselect and inter.user == ctx.author)
await interaction.send(interaction.values[0])
I want this function (for now) to send the value of the option. Did anyone have this issue who can help me?

Related

PermissionError Multiprocessing argument pyppeteer.Page

PermissionError Multiprocessing argument pyppeteer.Page
successful but inefficient
import asyncio
from pyppeteer import launch
from multiprocessing import Process
async def f(x):
print("async def f(x,page):",x)
browser = await launch(headless=False, autoClose=False)
page = (await browser.pages())[0]
await page.goto('https://example.com')
h1 = await page.querySelector("body > div > h1")
await page.evaluate(f'(element) => element.textContent="{x}"', h1)
def p(x):
print("def p(x,page):",x)
asyncio.run(f(x))
async def main():
pro = Process(target=p, args=("1111",))
pro.start()
pro = Process(target=p, args=("2222",))
pro.start()
if __name__ =="__main__":
asyncio.get_event_loop().run_until_complete(main())
In order to process a lot, it is burdensome to create multiple browsers.
So, I try to create a lot of tabs.
This is the code I want, but I get an PermissionError
How can I solve this?
import asyncio
from pyppeteer import launch
from multiprocessing import Process
async def f(x,page):
print("async def f(x,page):",x)
await page.goto('https://example.com')
h1 = await page.querySelector("body > div > h1")
await page.evaluate(f'(element) => element.textContent="{x}"', h1)
def p(x,page):
print("def p(x,page):",x)
asyncio.run(f(x,page))
async def main():
browser = await launch(headless=False, autoClose=False)
page = (await browser.pages())[0]
pro = Process(target=p, args=("1111",page))
pro.start()
if __name__ =="__main__":
asyncio.get_event_loop().run_until_complete(main())
error message
c:\Users\mimmi\python\ttttt.py:24: DeprecationWarning: There is no current event loop
asyncio.get_event_loop().run_until_complete(main())
Traceback (most recent call last):
File "c:\Users\mimmi\python\ttttt.py", line 24, in <module>
asyncio.get_event_loop().run_until_complete(main())
File "C:\python\python311\Lib\asyncio\base_events.py", line 650, in run_until_complete
return future.result()
^^^^^^^^^^^^^^^
File "c:\Users\mimmi\python\ttttt.py", line 21, in main
pro.start()
^^^^^^^^^^^
File "C:\python\python311\Lib\multiprocessing\process.py", line 121, in start
self._popen = self._Popen(self)
^^^^^^^^^^^^^^^^^
File "C:\python\python311\Lib\multiprocessing\context.py", line 224, in _Popen
return _default_context.get_context().Process._Popen(process_obj)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\python\python311\Lib\multiprocessing\context.py", line 336, in _Popen
return Popen(process_obj)
^^^^^^^^^^^^^^^^^^
File "C:\python\python311\Lib\multiprocessing\popen_spawn_win32.py", line 94, in __init__
reduction.dump(process_obj, to_child)
File "C:\python\python311\Lib\multiprocessing\reduction.py", line 60, in dump
ForkingPickler(file, protocol).dump(obj)
TypeError: cannot pickle '_thread.lock' object
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\python\python311\Lib\multiprocessing\spawn.py", line 111, in spawn_main
new_handle = reduction.duplicate(pipe_handle,
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\python\python311\Lib\multiprocessing\reduction.py", line 79, in duplicate
return _winapi.DuplicateHandle(
^^^^^^^^^^^^^^^^^^^^^^^^
PermissionError: [WinError 5] Access is denied
my environment
windows11
python3.11
pyppeteer1.0.2
I got the desired result with this code.
queue = asyncio.Queue()
browser = await launch(headless=False, autoClose=False)
for i in range(MAX_TASK_COUNT-1):
await browser.newPage()
pages = await browser.pages()
for page in pages:
asyncio.create_task(crawlingTask(queue, page))
await asyncio.create_task(queuePutter(queue, session, appendList))
await queue.join()

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)
)

asyncio.wait_for exec function error in Python3.7.2

I try to run this code:
import asyncio
async def eva(code):
exec("async def ex(): return {}".format(code))
return await asyncio.wait_for(locals()["ex"](), timeout=1.0)
async def main():
while True:
code = input()
x = await asyncio.wait_for(eva(code), timeout=1.0)
print(x)
asyncio.run(main())
And getting following error:
<module>
asyncio.run(main()) File "C:\Users\\{user}\AppData\Local\Programs\Python\Python37\lib\asyncio\runners.py",
line 43, in run
return loop.run_until_complete(main) File "C:\Users\\{user}\AppData\Local\Programs\Python\Python37\lib\asyncio\base_events.py",
line 584, in run_until_complete
return future.result()
File "eval.py", line 10, in main
x = await asyncio.wait_for(eva(code), timeout=1.0) File "C:\Users\\{user}\AppData\Local\Programs\Python\Python37\lib\asyncio\tasks.py",
line 416, in wait_for
return fut.result()
File "eval.py", line 5, in eva
return await asyncio.wait_for(locals()["ex"](), timeout=1.0)
File "C:\Users\\
{user}\AppData\Local\Programs\Python\Python37\lib\asyncio\tasks.py",
line 416, in wait_for
return fut.result()
File "<string>", line 1, in ex TypeError: 'int' object is not
iterable ```
Can you help me to understand what exactly happens?
From traceback you can see that error happend at function ex:
File "<string>", line 1, in ex
And shortly before it this line was executed:
File "eval.py", line 5, in eva
return await asyncio.wait_for(locals()["ex"](), timeout=1.0)
In other words exception was raised somewhere inside coroutine ex you got from locals()["ex"].
Exception message is:
TypeError: 'int' object is not iterable
You can google it to understand typical situation when it can happen, but it's not hard to assume either: something inside ex tried to iterate object of type int.
Something like this happened:
import asyncio
async def ex():
for i in 123:
pass
async def main():
return await asyncio.wait_for(ex(), timeout=1.0)
asyncio.run(main())
Run and you'll see similar:
File "...\main.py", line 15, in main
return await asyncio.wait_for(ex(), timeout=1.0)
File "...\python37\lib\asyncio\tasks.py", line 416, in wait_for
return fut.result()
File "...\main.py", line 11, in ex
for i in 123:
TypeError: 'int' object is not iterable

Discord.py printing a invite link

I'm having an issue where i try to print a invite link into console, but instead it prints out
<generator object Client.create_invite at 0x000001D310A183B8>
<generator object Client.create_invite at 0x000001D310A65410>
i am using this code:
#client.event
async def on_ready():
#await client.change_presence(game=Game(name="with humans"))
print("Logged in as " + client.user.name)
await asyncio.sleep(3)
for server in client.servers:
for channel in server.channels:
channel_type = channel.type
if str(channel_type) == 'text':
invitelinknew = client.create_invite(destination=channel, xkcd=True, max_uses=100)
print(str(invitelinknew))
break
i tried changing print(invitelinknew) to print(str(invitelinknew)), but it didn't change the outcome
EDIT:
New errors when consuming the genrator with invitelinknew2 = list(invitelinknew)
and print(invitelinknew2):
Traceback (most recent call last):
File "C:\Program Files\Python36\lib\site-packages\discord\client.py", line 307, in _run_event
yield from getattr(self, event)(*args, **kwargs)
File "C:/Users/Rasmus/Python/discordbot/botnoggi2.py", line 128, in on_ready
invitelinknew2 = list(invitelinknew)
File "C:\Program Files\Python36\lib\site-packages\discord\client.py", line 2628, in create_invite
data = yield from self.http.create_invite(destination.id, **options)
File "C:\Program Files\Python36\lib\site-packages\discord\http.py", line 137, in request
r = yield from self.session.request(method, url, **kwargs)
File "C:\Program Files\Python36\lib\site-packages\aiohttp\client.py", line 555, in __iter__
resp = yield from self._coro
File "C:\Program Files\Python36\lib\site-packages\aiohttp\client.py", line 202, in _request
yield from resp.start(conn, read_until_eof)
File "C:\Program Files\Python36\lib\site-packages\aiohttp\client_reqrep.py", line 640, in start
message = yield from httpstream.read()
File "C:\Program Files\Python36\lib\site-packages\aiohttp\streams.py", line 641, in read
result = yield from super().read()
File "C:\Program Files\Python36\lib\site-packages\aiohttp\streams.py", line 476, in read
yield from self._waiter
AssertionError: yield from wasn't used with future
Future exception was never retrieved
future: <Future finished exception=ServerDisconnectedError()>
aiohttp.errors.ServerDisconnectedError
According to the documentation create_invite is a coroutine and requires the await keyword
Change your code to include it such as
if channel.type == discord.ChannelType.text:
invitelinknew = await client.create_invite(destination=channel, xkcd=True, max_uses=100)
print(invitelinknew.url)

Categories