Skip to content

Instantly share code, notes, and snippets.

@vasilews
Last active November 21, 2023 01:58
Show Gist options
  • Select an option

  • Save vasilews/00f007f24f4e2437ce461fab83597a3d to your computer and use it in GitHub Desktop.

Select an option

Save vasilews/00f007f24f4e2437ce461fab83597a3d to your computer and use it in GitHub Desktop.

Revisions

  1. vasilews revised this gist Nov 21, 2023. 1 changed file with 0 additions and 1 deletion.
    1 change: 0 additions & 1 deletion send_photos.py
    Original file line number Diff line number Diff line change
    @@ -58,7 +58,6 @@ async def main():
    BOT_TOKEN,
    CHAT_ID,
    list(photos),
    "You received cool pictures now!",
    )


  2. vasilews created this gist Nov 21, 2023.
    66 changes: 66 additions & 0 deletions send_photos.py
    Original 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())