import csv
import asyncio
from telethon import TelegramClient
from telethon.tl.functions.messages import GetDialogFiltersRequest
from telethon.tl.functions.channels import GetFullChannelRequest


# Replace the following values with your own API ID and hash obtained from https://my.telegram.org
api_id = "..."
api_hash = "..."


async def main():
    # Initialize the Telegram client
    async with TelegramClient("anon", api_id, api_hash) as client:
        # Get the list of dialog filters
        response = await client(GetDialogFiltersRequest())

        with open(
            "telegram_channels.csv", mode="w", newline="", encoding="utf-8"
        ) as csv_file:
            fieldnames = ["id", "folder", "url", "name", "description"]
            writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
            writer.writeheader()

            # Iterate through the filters
            for dialog_filter in response:
                if hasattr(dialog_filter, "include_peers"):
                    # print(dialog_filter)
                    for entity in await client.get_entity(dialog_filter.include_peers):
                        if hasattr(entity, "deleted") and (entity.deleted):
                            continue

                        description = ""
                        try:
                            full = await client(GetFullChannelRequest(entity))
                            full_channel = full.full_chat
                            description = str(full_channel.about).replace("\n", " ")
                        except:
                            print(entity)
                            print("Failed to get description")

                        writer.writerow(
                            {
                                "id": entity.id,
                                "folder": dialog_filter.title,
                                "url": f"https://t.me/{entity.username}"
                                if entity.username is not None
                                else "",
                                "name": entity.title
                                if hasattr(entity, "title")
                                else "",
                                "description": description,
                            }
                        )


# Run the main function asynchronously
asyncio.run(main())