The current code uses FastAPI and Pyrogram to create a video streaming server. The server should support HTTP Range requests to allow streaming of video segments but the video client is not able to skip forward or backward during streaming as expected.
from fastapi import FastAPI, Request
from pyrogram import Client
from starlette.responses import StreamingResponse
app = FastAPI()
client = Client("my_account", api_id=......, api_hash="....")
@app.on_event("startup")
async def startup_event():
await client.start()
@app.on_event("shutdown")
async def shutdown_event():
await client.stop()
@app.get('/stream/{file_id}')
async def stream(file_id: str, request: Request):
range_header = request.headers.get('Range', None)
start, end = 0, None
if range_header:
byte1, byte2 = range_header.replace('bytes=', '').split('-')
start = int(byte1)
if byte2:
end = int(byte2)
async def generate():
offset = start // (1024 * 1024) # Convert start to chunks
limit = (1 << 31) - 1 # Default limit
if end is not None:
limit = (end - start) // (1024 * 1024) + 1 # Convert end to chunks
async for chunk in client.stream_media(file_id, offset=offset, limit=limit):
yield chunk
response = StreamingResponse(generate(), media_type='video/mp4')
response.headers['Accept-Ranges'] = 'bytes'
if range_header:
response.status_code = 206
response.headers['Content-Range'] = f'bytes {start}-{end if end else ""}/*'
return response
An example of log
PS C:UsersAdministratorDesktopmixnginx_streamteldriveplaystream> uvicorn editor:app --host 0.0.0.0 --port 11840
INFO: Started server process [10540]
INFO: Waiting for application startup.
INFO: Application startup complete.
INFO: Uvicorn running on http://0.0.0.0:11840 (Press CTRL+C to quit)
INFO: 127.0.0.1:56602 - "GET /stream/BAACAgQAAx0Eb1YTJQABBYGv............ HTTP/1.1" 200 OK
INFO: 127.0.0.1:56601 - "GET /stream/BAACAgQAAx0Eb1YTJQABBYGv............ HTTP/1.1" 206 Partial Content
Example of URL streaming is http://127.0.0.1:11840/stream/BAACAgQAAx0Eb1....
BAACAgQAAx0Eb1....
is file_id
from telegram
New contributor
nathan never is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.