Skip to content
TheChatArchiveThe Chat Archive
gpt-4-0125-preview· openaiHugging Face Suzhen/CodeChat

Could you write a pyrogram code for my telegram bot using mangadex api which can…

  1. User

    Could you write a pyrogram code for my telegram bot using mangadex api which can download desired manga using /search command, when uploading to telegram the bot needs to upload in pdf format

  2. Assistant

    Certainly! First, to interact with both Telegram and the MangaDex API efficiently and securely, you will need to set up a few things:

    • A Telegram Bot (create one via BotFather on Telegram and get your bot token)
    • MangaDex Account and API usage knowledge (be aware of their usage policies and any API key requirements)
    • Python environment, with Pyrogram and other essential libraries installed

    This example assumes you have a basic understanding of handling Telegram Bots and are familiar with Python. We'll also use additional libraries such as requests for API calls, and FPDF for PDF creation. Please ensure you have Pyrogram, requests, and fpdf2 installed in your environment. If not, install them using pip:

    pip install pyrogram tgcrypto requests fpdf2
    

    The following script showcases a basic implementation to search for manga on MangaDex and convert the first chapter available to a PDF file. Note that error handling, rate limiting, and respecting MangaDex's API policies are crucial in a production environment. This example provides a foundation that you'll likely need to adapt and extend.

    from pyrogram import Client, filters
    import requests
    from fpdf import FPDF
    
    # Configure your bot token here
    api_id = 'YOUR_API_ID'
    api_hash = 'YOUR_API_HASH'
    bot_token = 'YOUR_BOT_TOKEN'
    
    # MangaDex API URL
    MANGADEX_API_URL = 'https://api.mangadex.org'
    
    # Your Telegram Bot
    app = Client("my_bot", api_id=api_id, api_hash=api_hash, bot_token=bot_token)
    
    def search_manga(query):
        """Search for manga on MangaDex."""
        response = requests.get(f"{MANGADEX_API_URL}/manga", params={"title": query})
        if response.status_code == 200:
            return response.json()
        return None
    
    def get_chapter_images(chapter_id):
        """Get a list of image URLs for a manga chapter."""
        response = requests.get(f"{MANGADEX_API_URL}/chapter/{chapter_id}")
        if response.status_code == 200:
            baseUrl = response.json()['baseUrl']
            chapter_hash = response.json()['hash']
            filenames = response.json()['data']
            image_urls = [f"{baseUrl}/data/{chapter_hash}/{filename}" for filename in filenames]
            return image_urls
        return []
    
    def images_to_pdf(image_urls, pdf_filename):
        """Convert a list of image URLs to a PDF file."""
        pdf = FPDF()
        for image_url in image_urls:
            pdf.add_page()
            pdf.image(image_url, x = 10, y = 8, w = 190)
        pdf.output(pdf_filename, 'F')
    
    @app.on_message(filters.command(["search"]))
    def handle_search(client, message):
        query = message.text.split(maxsplit=1)[1] if len(message.text.split()) > 1 else ''
        if not query:
            message.reply_text("Please provide a search query.")
            return
        search_results = search_manga(query)
        if search_results and search_results["data"]:
            manga_id = search_results["data"][0]["id"]
            # Assume the first chapter available for simplicity
            chapter_id = "SOME_VALID_CHAPTER_ID" # You need to write logic to find a valid chapter ID
            image_urls = get_chapter_images(chapter_id)
            if image_urls:
                pdf_filename = f"{query}.pdf"
                images_to_pdf(image_urls, pdf_filename)
                with open(pdf_filename, "rb") as pdf_file:
                    message.reply_document(pdf_file)
            else:
                message.reply_text("No images found for the chapter.")
        else:
            message.reply_text("No search results found.")
    
    app.run()
    

    Key Considerations:

    1. MangaDex API Changes: This code assumes a simplified interface with MangaDex's API. Given APIs evolve, details about fetching manga chapters or image URLs may change. Always refer to the latest API documentation.
    2. Chapter ID: You need to implement logic to identify a valid chapter ID from a manga search to download images for that chapter. The example placeholder "SOME_VALID_CHAPTER_ID" must be replaced with actual logic.
    3. Rate Limits & Authentication: For more extensive usage, MangaDex may require authenticated API requests and will have rate limits. Ensure compliance with their guidelines.
    4. Image to PDF Conversion: In the given simplistic example, all images are added to a PDF with fixed dimensions. Depending on the source images, you might need to adjust image sizing and scaling logic for better results.

    This script provides a basic demonstration. For a robust, production-level bot, you will need to handle many edge cases, authentication (if required by MangaDex), data pagination, and more.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.