Hello! How can I assist you today? If you have any questions or need information on a topic, feel free to ask.
User
Assistant
User
New Error -:
Pyrogram client started successfully
Server started at http://localhost:8080
Exception ignored in: <function StreamWriter.del at 0x0000026A30195080>
Traceback (most recent call last):
File "C:\Python312\Lib\asyncio\streams.py", line 397, in del
File "C:\Python312\Lib\asyncio\streams.py", line 343, in close
File "C:\Python312\Lib\asyncio\proactor_events.py", line 109, in close
File "C:\Python312\Lib\asyncio\base_events.py", line 772, in call_soon
File "C:\Python312\Lib\asyncio\base_events.py", line 519, in _check_closed
RuntimeError: Event loop is closed
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
import asyncio
from aiohttp import web
from pyrogram import Client, filters
Create an instance of the Pyrogram client
client = None
Global variable to hold the current streaming task
current_task = None
async def start_client():
global client
try:
client = Client('my_account')
await client.start()
print("Pyrogram client started successfully")
except Exception as e:
print(f"Failed to create Pyrogram client: {e}")
async def stream_video(request):
global current_task
global client
code
if current_task and not current_task.done():
current_task.cancel()
async def handle_request():
# Extract the Range header, if exists
range_header = request.headers.get('Range', None)
# Default values if Range is not provided
start = 0
end = None
cid = int(request.match_info['cid'])
mid = int(request.match_info['mid'])
message = await client.get_messages(cid, mid)
video_size = message.video.file_size
# Default values if Range is not provided
start = 0
end = video_size - 1
if range_header:
# Parse the range headers
start, end = range_header.replace('bytes=', '').split('-')
start = int(start)
# Convert to int, if end is not empty
end = int(end) if end else video_size - 1
# Now that you have start and end, calculate offset and limit
chunk_size = 1024 * 1024
offset = start // chunk_size
# Calculate the number of chunk_sizes to limit the stream
limit = ((end - start) // chunk_size) + 1
response = web.StreamResponse()
response.headers['Content-Type'] = 'video/mp4'
response.headers['Accept-Ranges'] = 'bytes'
response_content_length = end - start + 1
response.headers['Content-Length'] = str(response_content_length)
response.headers['Content-Range'] = f'bytes {start}-{end}/{video_size}'
if range_header:
response.set_status(206, reason='Partial Content')
else:
response.set_status(200, reason='OK')
await response.prepare(request)
try:
# Stream the media from pyrogram
async for chunk in client.stream_media(message, limit=limit, offset=offset):
# Check if chunk needs to be trimmed
chunk_start = offset * chunk_size
chunk_end = chunk_start + len(chunk) - 1
# Trim front
if chunk_start < start:
chunk = chunk[start - chunk_start:]
# Trim end
if end and chunk_end > end:
chunk = chunk[:end - chunk_start + 1]
# Write chunk to response
await response.write(chunk)
offset += 1 # Move to the next chunk
if chunk_end >= end:
break
await response.write_eof()
except Exception:
pass
return response
current_task = asyncio.create_task(handle_request())
try:
# The Calling coroutine will wait until the task is done or canceled.
await current_task
except asyncio.CancelledError:
pass # Ignoring cancellation.
return web.Response(status=204)
async def serve_player(request):
# Serve the player.html file
with open('player.html', 'rb') as f:
content = f.read()
async def main():
# Start the Pyrogram client before running the app
await start_client()
# Rest of your server startup code, like routing and web.run_app
I'm getting this error when I go to /video/{cid}/{mid} route.
This is the errror-:
Traceback (most recent call last):
File "C:\Python312\Lib\site-packages\aiohttp\web_protocol.py", line 452, in _handle_request
resp = await request_handler(request)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python312\Lib\site-packages\aiohttp\web_app.py", line 543, in _handle
resp = await handler(request)
^^^^^^^^^^^^^^^^^^^^^^
File "c:\Users\win\Documents\Python Scripts\PyTeleServer\test2.py", line 106, in stream_video
await current_task
File "c:\Users\win\Documents\Python Scripts\PyTeleServer\test2.py", line 40, in handle_request
message = await client.get_messages(cid, mid)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python312\Lib\site-packages\pyrogram\methods\messages\get_messages.py", line 115, in get_messages
r = await self.invoke(rpc, sleep_threshold=-1)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python312\Lib\site-packages\pyrogram\methods\advanced\invoke.py", line 79, in invoke
r = await self.session.invoke(
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python312\Lib\site-packages\pyrogram\session\session.py", line 389, in invoke
return await self.send(query, timeout=timeout)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python312\Lib\site-packages\pyrogram\session\session.py", line 326, in send
payload = await self.loop.run_in_executor(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
RuntimeError: Task <Task pending name='Task-38' coro=<stream_video..handle_request() running at c:\Users\win\Documents\Python Scripts\PyTeleServer\test2.py:40> cb=[Task.task_wakeup()]> got Future <Future pending cb=[_chain_future.._call_check_cancel() at C:\Python312\Lib\asyncio\futures.py:387]> attached to a different loop
Error handling request
Traceback (most recent call last):
File "C:\Python312\Lib\site-packages\aiohttp\web_protocol.py", line 452, in _handle_request
resp = await request_handler(request)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python312\Lib\site-packages\aiohttp\web_app.py", line 543, in _handle
resp = await handler(request)
^^^^^^^^^^^^^^^^^^^^^^
File "c:\Users\win\Documents\Python Scripts\PyTeleServer\test2.py", line 106, in stream_video
await current_task
File "c:\Users\win\Documents\Python Scripts\PyTeleServer\test2.py", line 40, in handle_request
message = await client.get_messages(cid, mid)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python312\Lib\site-packages\pyrogram\methods\messages\get_messages.py", line 115, in get_messages
r = await self.invoke(rpc, sleep_threshold=-1)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python312\Lib\site-packages\pyrogram\methods\advanced\invoke.py", line 79, in invoke
r = await self.session.invoke(
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python312\Lib\site-packages\pyrogram\session\session.py", line 389, in invoke
return await self.send(query, timeout=timeout)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python312\Lib\site-packages\pyrogram\session\session.py", line 326, in send
payload = await self.loop.run_in_executor(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
RuntimeError: Task <Task pending name='Task-42' coro=<stream_video..handle_request() running at c:\Users\win\Documents\Python Scripts\PyTeleServer\test2.py:40> cb=[Task.task_wakeup()]> got Future <Future pending cb=[_chain_future.._call_check_cancel() at C:\Python312\Lib\asyncio\futures.py:387]> attached to a different loop
I really hate this crap error. I just don't understand these Asycio nonsense! PLEASE HELP ME!
The error message you're encountering is telling you that there is an issue with event loops in your asyncio application. Specifically, it suggests that a Future object (a low-level awaitable object that represents an eventual result of an asynchronous operation) is attached to a different event loop than the running Task.
This sort of error usually occurs when you're trying to run a coroutine that was created in a different context (another event loop) or when the event loop has been changed after setting up the asyncio objects. In your code, it seems this error might stem from how you are initializing the Pyrogram client and/or how the stream_video handler is being executed.
You have a global variable client that is initialized by the start_client() coroutine, and you're getting the event loop and running that coroutine with run_until_complete() outside of the main() coroutine. This could cause the event loop to be different from the one which the web server runs on.
Let's try restructuring the code to ensure that all async operations are happening in the context of the same event loop:
python
import asyncio
from aiohttp import web
from pyrogram import Client
# Rest of your code remains the same...
async def main():
global client # Declare client as global to initialize it in this context
# Start the Pyrogram client before running the app
client = Client('my_account')
await client.start()
print("Pyrogram client started successfully")
app = web.Application()
# Set up the web server routes
app.router.add_get('/video/{cid}/{mid}', stream_video)
app.router.add_route('GET', '/player', serve_player)
# Run the web application
runner = web.AppRunner(app)
await runner.setup()
site = web.TCPSite(runner, 'localhost', 8080)
await site.start()
print("Server started at http://localhost:8080")
if __name__ == '__main__':
asyncio.run(main())
Notable changes:
The initialization of the Pyrogram client is now within the main() coroutine.
The creation of the web application and the running of the server now happens after the Pyrogram client has been initialized within the main() coroutine.
asyncio.run(main()) is used to run the main() coroutine, which takes care of creating the event loop and will ensure that all async operations are performed within the same loop.
Make sure to follow the proper documentation for aiohttp to setup runners as the aiohttp API may change over time.
Ensure you replace 'my_account' with your actual session name or session configuration for Pyrogram.
Also, note that any resources, such as file descriptors or network connections, are properly cleaned up before the program exits. You may need additional cleanup code at the end of your application.
Finally, using global variables and functions in a web server can potentially lead to race conditions if multiple requests try to access or modify them at the same time. It might be worthwhile to investigate thread-safe programming paradigms like using asyncio.Lock to manage concurrent access to global state, or restructuring your application's architecture to avoid global mutable state where possible.
The error message you're encountering indicates an asynchronous resource (StreamWriter) is being garbage collected, and its finalizer (__del__) is attempting to schedule a close operation (close) on the event loop, but the loop has already been closed. This is somewhat of a common issue with asyncio where resources are not explicitly closed before the event loop shuts down.
This error typically doesn't affect the functionality of the code—it usually arises during the cleanup phase when the program is exiting. However, it does point to the fact that there might be a better way to manage your resources.
To prevent this type of warning, you should ensure that all StreamWriter objects (or other asynchronous resources) are properly closed before the program finishes. You can do this by explicitly closing the stream in your code when you're done with it, using appropriate context managers or by calling close() method followed by await writer.wait_closed() to close the resource gracefully.
Here's what you should be doing conceptually with StreamWriter (not directly applicable to your code as you don't explicitly handle a StreamWriter):
python
writer.close()
await writer.wait_closed()
Since the resource cleanup issue likely stems from the use of aiohttp and pyrogram (you're streaming the video using aiohttp and pyrogram's API likely uses streams internally), make sure that you're closing the Pyrogram client properly when your application shuts down. For aiohttp's AppRunner, you should gracefully shut down the runner and close the site. Here’s how to properly close everything down:
python
# At the end of your `main()` coroutine, where you're starting the server:
try:
# Run server forever
await asyncio.Event().wait()
except KeyboardInterrupt:
pass
finally:
await runner.cleanup()
await client.stop() # Properly disconnect the Pyrogram client
The above code allows you to run the event loop indefinitely until a KeyboardInterrupt (Ctrl+C) is caught, after which it will properly clean up the resources by closing the runner and stopping the Pyrogram client.
If you choose to implement a proper shutdown sequence, ensure that you manually call cleanup routines for the resources you've used, so they are closed before the program exits, and thus prevent the event loop from being accessed after it’s closed.
Remember, the error you shared is typically benign (usually just a warning about cleanup when exiting the program), but it does indicate that it would be better to tidy up your resources. Note that if you're running the application in a more complex environment or long-lived service, failing to close resources properly can lead to leaking resources over time, which is something you'd want to avoid.