Last active
November 21, 2023 01:58
-
-
Save vasilews/00f007f24f4e2437ce461fab83597a3d to your computer and use it in GitHub Desktop.
Revisions
-
vasilews revised this gist
Nov 21, 2023 . 1 changed file with 0 additions and 1 deletion.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -58,7 +58,6 @@ async def main(): BOT_TOKEN, CHAT_ID, list(photos), ) -
vasilews created this gist
Nov 21, 2023 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,66 @@ import asyncio import json from pathlib import Path from typing import Sequence import aiohttp BOT_TOKEN = "" CHAT_ID = 1234 async def send_photos( token: str, chat_id: int, photos: Sequence[Path], caption: str | None = None, ): url = f"https://api.telegram.org/bot{token}/sendMediaGroup" async with aiohttp.ClientSession() as session: data = aiohttp.FormData() data.add_field("chat_id", str(chat_id)) media: list[dict[str, str]] = [] name_prefix = "AttachedFile" for i, photo in enumerate(photos): name = f"{name_prefix}{i}" data.add_field( name, photo.open("rb"), filename=photo.name, content_type="image/jpeg", ) media_item: dict[str, str] = { "type": "photo", "media": f"attach://{name}", } if caption and i == 0: media_item["caption"] = caption media.append(media_item) data.add_field("media", json.dumps(media)) async with session.post(url, data=data) as resp: if resp.status != 200: print(f"Failed to send photo: {resp.status}") else: print("Photo sent successfully!") async def main(): photos = Path(".").glob("*.jpg") await send_photos( BOT_TOKEN, CHAT_ID, list(photos), "You received cool pictures now!", ) if __name__ == "__main__": asyncio.run(main())