Files
welcomecenterbot/bot/api.py

34 lines
1.0 KiB
Python
Raw Normal View History

2023-04-23 19:54:58 +03:00
import aiohttp
2023-04-16 17:58:53 +03:00
import json
2024-01-07 12:19:46 +03:00
from urllib.parse import urlencode
from bot.config import BOT_TOKEN
2023-09-11 23:04:53 +03:00
import logging
2023-09-06 13:20:50 +03:00
2023-09-11 23:04:53 +03:00
# Create a logger instance
2024-09-27 09:23:55 +03:00
logger = logging.getLogger("bot.api")
2024-09-27 11:28:41 +03:00
2023-04-16 17:58:53 +03:00
2024-02-12 15:50:35 +03:00
api_base = f"https://api.telegram.org/bot{BOT_TOKEN}/"
2023-04-16 17:58:53 +03:00
2024-02-12 15:50:35 +03:00
async def telegram_api(endpoint: str, json_data=None, **kwargs):
try:
url = api_base + f"{endpoint}?{urlencode(kwargs)}"
2024-09-27 09:23:55 +03:00
is_polling = endpoint == "getUpdates"
headers = {"Content-Type": "application/json"}
2024-02-12 15:50:35 +03:00
async with aiohttp.ClientSession() as session:
url = api_base + f"{endpoint}?{urlencode(kwargs)}"
2024-09-26 14:27:44 +03:00
if not is_polling:
logger.info(f' >>> {url} {json_data if json_data else ""}')
2024-09-27 09:23:55 +03:00
async with session.get(
url, data=json.dumps(json_data), headers=headers
) as response:
2024-02-12 15:50:35 +03:00
data = await response.json()
2024-09-26 14:27:44 +03:00
if not is_polling:
2024-09-27 09:23:55 +03:00
logger.info(f" <<< {data}")
2024-02-12 15:50:35 +03:00
return data
2024-09-27 09:23:55 +03:00
except Exception:
2024-02-12 15:50:35 +03:00
import traceback
2024-09-27 09:23:55 +03:00
2024-02-12 15:50:35 +03:00
traceback.print_exc()