I'm trying to create an api, and when i try to convert the aiohttp.ClientResponse to text, my code never finishes (never go to the next line) and it raises TimeoutError, I tried to do this in terminal (with the same site), and it works, can someone help me?
Here's my current code:
async with aiohttp.ClientSession() as session:
# _base="https://frankerfacez.com"
# query="monka"
# sort="count-desc"
r = await session.get(f'{_base}/emoticons/wall?q={query}&sort={sort}')
txt = await r.text()
And it raises this:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\Kaigo\AppData\Local\Programs\Python\Python38\lib\asyncio\base_events.py", line 612, in run_until_complete
return future.result()
File "C:\Users\Kaigo\Desktop\FFZ Api\ffz\__init__.py", line 112, in search
txt = await r.text()
File "C:\Users\Kaigo\AppData\Local\Programs\Python\Python38\lib\site-packages\aiohttp\client_reqrep.py", line 1009, in text
await self.read()
File "C:\Users\Kaigo\AppData\Local\Programs\Python\Python38\lib\site-packages\aiohttp\client_reqrep.py", line 973, in read
self._body = await self.content.read()
File "C:\Users\Kaigo\AppData\Local\Programs\Python\Python38\lib\site-packages\aiohttp\streams.py", line 358, in read
block = await self.readany()
File "C:\Users\Kaigo\AppData\Local\Programs\Python\Python38\lib\site-packages\aiohttp\streams.py", line 380, in readany
await self._wait('readany')
File "C:\Users\Kaigo\AppData\Local\Programs\Python\Python38\lib\site-packages\aiohttp\streams.py", line 296, in _wait
await waiter
File "C:\Users\Kaigo\AppData\Local\Programs\Python\Python38\lib\site-packages\aiohttp\helpers.py", line 596, in __exit__
raise asyncio.TimeoutError from None
asyncio.exceptions.TimeoutError
you're trying to read from the request after clossing the session. Move the await r.text() to inside the async with block:
async with aiohttp.ClientSession() as session:
url = f'{_base}/emoticons/wall?q={query}&sort={sort}'
async with session.get(url) as r:
txt = await r.text()
Related
I have an id from a group chat, but when I try to send a message there, I get this error:
Traceback (most recent call last):
File "D:\github\repositories\python-bot\venv\lib\site-packages\aiogram\dispatcher\dispatcher.py", line 415, in _process_polling_updates
for responses in itertools.chain.from_iterable(await self.process_updates(updates, fast)):
File "D:\github\repositories\python-bot\venv\lib\site-packages\aiogram\dispatcher\dispatcher.py", line 235, in process_updates
return await asyncio.gather(*tasks)
File "D:\github\repositories\python-bot\venv\lib\site-packages\aiogram\dispatcher\handler.py", line 116, in notify
response = await handler_obj.handler(*args, **partial_data)
File "D:\github\repositories\python-bot\venv\lib\site-packages\aiogram\dispatcher\dispatcher.py", line 256, in process_update
return await self.message_handlers.notify(update.message)
File "D:\github\repositories\python-bot\venv\lib\site-packages\aiogram\dispatcher\handler.py", line 116, in notify
response = await handler_obj.handler(*args, **partial_data)
File "D:\github\repositories\python-bot\bot5.py", line 77, in cmd_create_dem
await bot.send_poll(chat_id=id,
File "D:\github\repositories\python-bot\venv\lib\site-packages\aiogram\bot\bot.py", line 1532, in send_poll
result = await self.request(api.Methods.SEND_POLL, payload)
File "D:\github\repositories\python-bot\venv\lib\site-packages\aiogram\bot\base.py", line 231, in request
return await api.make_request(await self.get_session(), self.server, self.__token, method, data, files,
File "D:\github\repositories\python-bot\venv\lib\site-packages\aiogram\bot\api.py", line 140, in make_request
return check_result(method, response.content_type, response.status, await response.text())
File "D:\github\repositories\python-bot\venv\lib\site-packages\aiogram\bot\api.py", line 115, in check_result
exceptions.BadRequest.detect(description)
File "D:\github\repositories\python-bot\venv\lib\site-packages\aiogram\utils\exceptions.py", line 140, in detect
raise err(cls.text or description)
aiogram.utils.exceptions.ChatNotFound: Chat not found
If I try to send to any other group, then everything works. Why is that?
code:
#dp.message_handler(commands=['opros'])
async def prikol(message: types.Message):
id = {-numbers}
await bot.send_message(id, 'ok')
i changed my id to {numbers}
My id has 14 characters including the minus, while the rest of the groups have like 10 characters. Could this affect something?
If you get id without -100 (example: 1234561) you need add "-100" to this id to use it with bot (ex: -1001234561)
I have two suggestions:
Be sure that your bot must be an admin of this group to be able to send messages.
Double check group id.
i have a bot which parses some links given by user. When clients want to parse realy huge amount of links, bot parses them, creates csv file from those links, sends it to user(user can download and view this file) and then raise TimeoutError
Cause exception while getting updates.
Traceback (most recent call last):
File "/Users/alex26/miniforge3/envs/rq/lib/python3.8/site-packages/aiogram/dispatcher/dispatcher.py", line 381, in start_polling
updates = await self.bot.get_updates(
File "/Users/alex26/miniforge3/envs/rq/lib/python3.8/site-packages/aiogram/bot/bot.py", line 110, in get_updates
result = await self.request(api.Methods.GET_UPDATES, payload)
File "/Users/alex26/miniforge3/envs/rq/lib/python3.8/site-packages/aiogram/bot/base.py", line 231, in request
return await api.make_request(await self.get_session(), self.server, self.__token, method, data, files,
File "/Users/alex26/miniforge3/envs/rq/lib/python3.8/site-packages/aiogram/bot/api.py", line 139, in make_request
async with session.post(url, data=req, **kwargs) as response:
File "/Users/alex26/miniforge3/envs/rq/lib/python3.8/site-packages/aiohttp/client.py", line 1138, in __aenter__
self._resp = await self._coro
File "/Users/alex26/miniforge3/envs/rq/lib/python3.8/site-packages/aiohttp/client.py", line 559, in _request
await resp.start(conn)
File "/Users/alex26/miniforge3/envs/rq/lib/python3.8/site-packages/aiohttp/client_reqrep.py", line 913, in start
self._continue = None
File "/Users/alex26/miniforge3/envs/rq/lib/python3.8/site-packages/aiohttp/helpers.py", line 721, in __exit__
raise asyncio.TimeoutError from None
asyncio.exceptions.TimeoutError
Some example how my bot looks like(that's not real code, that's EXAMPLE):
bot = Bot(token=API_TOKEN)
dp = Dispatcher(bot)
def parse_1000_links():
#it takes about 10 mins and therefore that's the same like sleep(600)
sleep(600)
#dp.message_handler()
async def msg_handler(message: types.Message):
if msg == 'parse 1000 links':
res = parse_1000_links()
create_csv_from_res(res)
file_open_obj = open('data.csv', 'rb')
await bot.send_document(message.from_user.id, file_open_obj)
.....
if __name__ == '__main__':
executor.start_polling(dp, skip_updates=True)
User can even get from bot this final file, but after sending this file to user, bot raises this error. That's strange. If user get message, it means that everything is fine(That's my opinion)
How to fix my issue?
Thanks
You should avoid using blocking operations, cause they freeze ALL event loop.
If you can't use async version of your dependency, use executor:
https://docs.python.org/3/library/asyncio-eventloop.html#executing-code-in-thread-or-process-pools
I keep getting errors with this project and this is probably the last one I'm gonna try to fix
here's the code that has the problem:
#classmethod
async def from_url(cls, url, *, loop=None, stream=False):
loop = loop or asyncio.get_event_loop()
data = await loop.run_in_executor(None, lambda: ytdl.extract_info(url, download=not stream))
if 'entries' in data:
# take first item from a playlist
data = data['entries'][0]
filename = data['url'] if stream else ytdl.prepare_filename(data)
return cls(discord.FFmpegPCMAudio(filename, **ffmpeg_options), data=data)
and this is the error:
Ignoring exception in command play:
Traceback (most recent call last):
File "C:\Users\moham\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\moham\Desktop\musicbot.py", line 104, in play
player = await YTDLSource.from_url(queue, loop=client.loop)
File "C:\Users\moham\Desktop\musicbot.py", line 40, in from_url
data = await loop.run_in_executor(None, lambda: ytdl.extract_info(url, download=not stream))
File "C:\Users\moham\AppData\Local\Programs\Python\Python38-32\lib\concurrent\futures\thread.py", line 57, in run
result = self.fn(*self.args, **self.kwargs)
File "C:\Users\moham\Desktop\musicbot.py", line 40, in <lambda>
data = await loop.run_in_executor(None, lambda: ytdl.extract_info(url, download=not stream))
File "C:\Users\moham\AppData\Local\Programs\Python\Python38-32\lib\site-packages\youtube_dl\YoutubeDL.py", line 788, in extract_info
if not ie.suitable(url):
File "C:\Users\moham\AppData\Local\Programs\Python\Python38-32\lib\site-packages\youtube_dl\extractor\common.py", line 413, in suitable
return cls._VALID_URL_RE.match(url) is not None
TypeError: expected string or bytes-like object
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\moham\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\bot.py", line 903, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\moham\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 859, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\moham\AppData\Local\Programs\Python\Python38-32\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: TypeError: expected string or bytes-like object
I am still new to all of this so please assume that I don't know a lot about coding, I was just following a tutorial and apparently I'm not even good at that lol.
I've migrating my discord bot to use MySQL instead of storing data in json files. The only problem I got now is when I try to load the music extension of the bot...
Code:
import discord
import lavalink
from discord import Guild
from discord import User
from discord.ext import commands
# from bot import get_musicchannel
# from bot import get_prefix
from bot import mycursor
def get_musicchannel(guild: Guild):
# with open("cogs/music.json") as f:
# channels = json.load(f)
# channel: TextChannel = discord.utils.get(guild.text_channels, id=channels[str(guild.id)])
# return channel.id
sqlcommand = "SELECT channelid FROM musicchannels WHERE guildid = %s"
vals = (guild.id,)
mycursor.execute(sqlcommand, vals)
result = mycursor.fetchall()
strchannelid = str(result[0]).replace("(", "").replace(")", "").replace(",", "")
channelid = int(strchannelid)
return channelid
class Music(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.bot.music = lavalink.Client(self.bot.user.id)
self.bot.music.add_node("IP", 2333, 'PASS', 'eu', 'music-node')
self.bot.add_listener(self.bot.music.voice_update_handler, 'on_socket_response')
self.bot.music.add_event_hook(self.track_hook)
#commands.command(name="music")
async def music(self, ctx, opt, *, arg=None):
if ctx.message.channel.id != get_musicchannel(ctx.guild):
# channel = get_musicchannel(ctx.guild)
actual_channel = discord.utils.get(ctx.guild.text_channels, id=get_musicchannel(ctx.guild))
return await ctx.send(f"Music commands can only be used in the music channel ({actual_channel.mention})")
if opt == "join":
member = discord.utils.find(lambda m: m.id == ctx.author.id, ctx.guild.members)
if member is not None and member.voice is not None:
vc = member.voice.channel
player = self.bot.music.player_manager.create(ctx.guild.id, endpoint=str(ctx.guild.region))
if not player.is_connected:
player.store('channel', ctx.guild.id)
await self.connect_to(ctx.guild.id, str(vc.id))
# Unimportant code
async def track_hook(self, event):
if isinstance(event, lavalink.events.QueueEndEvent):
guild_id = int(event.player.guild_id)
await self.connect_to(guild_id, None)
async def connect_to(self, guild_id: int, channel_id: int):
ws = self.bot._connection._get_websocket(guild_id)
await ws.voice_state(str(guild_id), channel_id)
async def disconnect_from(self, guild_id: int):
ws = self.bot._connection.voice_clients
print(ws)
def setup(bot):
bot.add_cog(Music(bot))
When I try to run the bot it gives me this error:
Ignoring exception in on_ready
Traceback (most recent call last):
File "C:\Users\xlysa\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\client.py", line 668, in run
loop.run_forever()
File "C:\Users\xlysa\AppData\Local\Programs\Python\Python38-32\lib\asyncio\windows_events.py", line 314, in run_forever
assert self._self_reading_future is None
AssertionError
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\xlysa\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\client.py", line 93, in _cleanup_loop
_cancel_tasks(loop)
File "C:\Users\xlysa\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\client.py", line 78, in _cancel_tasks
loop.run_until_complete(asyncio.gather(*tasks, return_exceptions=True))
File "C:\Users\xlysa\AppData\Local\Programs\Python\Python38-32\lib\asyncio\base_events.py", line 592, in run_until_complete
self._check_running()
File "C:\Users\xlysa\AppData\Local\Programs\Python\Python38-32\lib\asyncio\base_events.py", line 552, in _check_running
raise RuntimeError('This event loop is already running')
RuntimeError: This event loop is already running
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\xlysa\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\bot.py", line 607, in _load_from_module_spec
spec.loader.exec_module(lib)
File "<frozen importlib._bootstrap_external>", line 783, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "D:\Ficheiros\Pastas\Tudo\Coding\Python\Projects\Server-Utils\cogs\music.py", line 11, in <module>
from bot import mycursor
File "D:\Ficheiros\Pastas\Tudo\Coding\Python\Projects\Server-Utils\bot.py", line 1383, in <module>
bot.run(TOKEN)
File "C:\Users\xlysa\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\client.py", line 674, in run
_cleanup_loop(loop)
File "C:\Users\xlysa\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\client.py", line 98, in _cleanup_loop
loop.close()
File "C:\Users\xlysa\AppData\Local\Programs\Python\Python38-32\lib\asyncio\proactor_events.py", line 674, in close
raise RuntimeError("Cannot close a running event loop")
RuntimeError: Cannot close a running event loop
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\xlysa\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\client.py", line 312, in _run_event
await coro(*args, **kwargs)
File "D:/Ficheiros/Pastas/Tudo/Coding/Python/Projects/Server-Utils/bot.py", line 421, in on_ready
bot.load_extension('cogs.music')
File "C:\Users\xlysa\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\bot.py", line 664, in load_extension
self._load_from_module_spec(spec, name)
File "C:\Users\xlysa\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\bot.py", line 610, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.music' raised an error: RuntimeError: Cannot close a running event loop
Process finished with exit code 0
The on_ready event just has bot.load_extension('cogs.music') that's where the error comes from
I don't know what can I do to make this run... Help is appreciated.
I was learning some async/await in python, and i wanted to try it, but
I'm getting this error while trying to connect to chatango via websocket and i don't know what means.
I'm using python 3.6.1 and aiohttp 2.2.3
This is my code:
import asyncio
import aiohttp
msgs = []
async def main():
async with aiohttp.ClientSession() as session:
async with session.ws_connect("ws://s12.chatango.com:8081/") as ws:
for msg in ws:
msgs.append(msg)
print(msg)
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()
Full traceback:
Traceback (most recent call last):
File "C:\Program Files\Python36\lib\site-packages\aiohttp\client_reqrep.py", line 559, in start
(message, payload) = yield from self._protocol.read()
File "C:\Program Files\Python36\lib\site-packages\aiohttp\streams.py", line 509, in read
yield from self._waiter
File "C:\Program Files\Python36\lib\site-packages\aiohttp\client_proto.py", line 165, in data_received
messages, upgraded, tail = self._parser.feed_data(data)
File "aiohttp\_http_parser.pyx", line 274, in aiohttp._http_parser.HttpParser.feed_data (aiohttp/_http_parser.c:4364)
aiohttp.http_exceptions.BadHttpMessage: 400, message='invalid constant string'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:/Users/joseh/Desktop/a.ws.py", line 42, in <module>
loop.run_until_complete(main())
File "C:\Program Files\Python36\lib\asyncio\base_events.py", line 466, in run_until_complete
return future.result()
File "C:/Users/joseh/Desktop/a.ws.py", line 34, in main
async with session.ws_connect("ws://s12.chatango.com:8081/") as ws:
File "C:\Program Files\Python36\lib\site-packages\aiohttp\client.py", line 603, in __aenter__
self._resp = yield from self._coro
File "C:\Program Files\Python36\lib\site-packages\aiohttp\client.py", line 390, in _ws_connect
proxy_auth=proxy_auth)
File "C:\Program Files\Python36\lib\site-packages\aiohttp\helpers.py", line 91, in __iter__
ret = yield from self._coro
File "C:\Program Files\Python36\lib\site-packages\aiohttp\client.py", line 241, in _request
yield from resp.start(conn, read_until_eof)
File "C:\Program Files\Python36\lib\site-packages\aiohttp\client_reqrep.py", line 564, in start
message=exc.message, headers=exc.headers) from exc
aiohttp.client_exceptions.ClientResponseError: 400, message='invalid constant string'
invalid constant string is a custom response from chatango, they probably want a protocol or some kind of auth header.
If you don't know much about how chatango uses websockets, reverse engineering their system is probably not a good task for learning asyncio and aiohttp.
Better to use something like httparrot which just echos back the message you send it.
Here's your code modified to use httparrot and send 5 messages, get 5 responses, then exit.
import asyncio
import aiohttp
msgs = []
async def main():
async with aiohttp.ClientSession() as session:
async with session.ws_connect('ws://httparrot.herokuapp.com/websocket') as ws:
ws.send_str('hello')
async for msg in ws:
msgs.append(msg)
print(msg)
ws.send_str('hello')
if len(msgs) >= 5:
break
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()
print(msgs)