Skip to content

Instantly share code, notes, and snippets.

@thevickypedia
Last active September 11, 2023 07:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thevickypedia/a44d23e3ed35eb15bbe1e557479835e5 to your computer and use it in GitHub Desktop.
Save thevickypedia/a44d23e3ed35eb15bbe1e557479835e5 to your computer and use it in GitHub Desktop.
Asynchronous calls for long polling Telegram API - A better broken state
import asyncio
from typing import Dict
from urllib.parse import urljoin
import aiohttp
from pydantic import HttpUrl
from pydantic_settings import BaseSettings
class Settings(BaseSettings):
bot_token: str
webhook: HttpUrl
class Config:
extra = "allow"
env_file = ".env"
settings = Settings()
BASE_URL = f"https://api.telegram.org/bot{settings.bot_token}/"
async def fetch_updates(session: aiohttp.ClientSession, payload: Dict[str, int]):
async with session.post(urljoin(BASE_URL, "getUpdates"), params=payload) as response:
if response.ok:
return await response.json()
else:
print(await response.json())
return None
async def main():
offset = 0
async with aiohttp.ClientSession() as session:
major, minor = session.version
print(f"Polling with v{major}.{minor}")
while True:
response = await fetch_updates(session, {'offset': offset, 'timeout': 60})
if response:
for result in response.get('result', []):
message = result.get('message')
await respond(session, {'chat_id': message.get('chat').get('id'), 'text': message.get('text')})
offset = result['update_id'] + 1
else:
break
async def respond(session, payload):
async with session.post(url=urljoin(BASE_URL, "sendMessage"), params=payload) as response:
res = await response.json()
print(res)
if __name__ == "__main__":
asyncio.run(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment