ocr
This commit is contained in:
23
bot/api.py
23
bot/api.py
@@ -1,4 +1,6 @@
|
||||
import aiohttp
|
||||
import aiofiles
|
||||
import os
|
||||
import json
|
||||
from urllib.parse import urlencode
|
||||
from bot.config import BOT_TOKEN
|
||||
@@ -7,7 +9,6 @@ import logging
|
||||
# Create a logger instance
|
||||
logger = logging.getLogger("bot.api")
|
||||
|
||||
|
||||
api_base = f"https://api.telegram.org/bot{BOT_TOKEN}/"
|
||||
|
||||
|
||||
@@ -31,3 +32,23 @@ async def telegram_api(endpoint: str, json_data=None, **kwargs):
|
||||
import traceback
|
||||
|
||||
traceback.print_exc()
|
||||
|
||||
|
||||
async def download_file(file_id):
|
||||
"""Asynchronously download a file from Telegram and yield the temporary file path."""
|
||||
download_url = f"{api_base}/{file_path}"
|
||||
|
||||
# Get the file path of the file using the telegram_api method
|
||||
file = await telegram_api("getFile", file_id=file_id)
|
||||
file_path = file["result"]["file_path"]
|
||||
|
||||
async with aiohttp.ClientSession() as session:
|
||||
async with session.get(download_url) as response:
|
||||
if response.status == 200:
|
||||
# Save the downloaded file to a temporary location
|
||||
async with aiofiles.tempfile.NamedTemporaryFile(delete=True) as temp_file:
|
||||
await temp_file.write(await response.read())
|
||||
await temp_file.flush()
|
||||
yield temp_file.name # Yield the path of the temporary file
|
||||
else:
|
||||
raise Exception(f"Failed to download file: {response.status}")
|
Reference in New Issue
Block a user