How to make Discord bot respond when user posts picture in channel

I’ve got a Discord bot that’s working pretty well. It can chat with people and I even added weather info using slash commands. Now I’m trying to figure out how to make it react when someone posts a picture.

Basically, I want my bot to send a message like “Nice picture there!” whenever anyone uploads an image to the chat. I’ve been searching around, but most of the guides I found are really old and don’t seem to work anymore.

Anyone know how to detect image uploads with the current Discord API? Would really appreciate some help with this.

The Problem:

Your Discord bot experiences a significant delay (around 30 seconds) when executing commands for the first time after a period of inactivity. Subsequent executions of the same command are much faster (under 1 second). This delay disappears after approximately 30 seconds of inactivity, returning to the slow response time upon the next command execution. Your bot’s latency checks show a low latency of around 0.1 seconds, indicating the delay doesn’t originate from Discord’s servers.

:thinking: Understanding the “Why” (The Root Cause):

The 30-second delay followed by fast subsequent responses strongly suggests your bot’s hosting environment is responsible. Many free or serverless hosting platforms implement idle timeout mechanisms. When your bot is inactive for a certain duration (in this case, approximately 30 seconds), the platform suspends or terminates the bot’s processes to conserve resources. The first command execution after this period triggers a cold start, causing the significant delay. Subsequent commands execute quickly because the bot’s processes are already running.

:gear: Step-by-Step Guide:

  1. Identify Your Hosting Provider and Idle Timeout Settings: Determine which platform hosts your Discord bot (e.g., Heroku, Render, AWS Lambda, etc.). Consult their documentation for information regarding idle timeout policies and how to manage them. This is crucial for understanding your specific platform’s limitations and potential solutions.

  2. Implement a Keep-Alive Mechanism: The most effective solution is to prevent your bot from becoming idle. A simple keep-alive mechanism periodically sends a small request to your bot’s server, maintaining its active state and preventing timeouts.

    Here’s an example of a Python script that sends a HTTP request using the requests library every 20 minutes:

    import requests
    import time
    import threading
    
    def keep_alive():
        while True:
            try:
                response = requests.get("http://your-bot-address/ping")  # Replace with your bot's ping endpoint
                response.raise_for_status()  # Raise HTTPError for bad responses (4xx or 5xx)
                print(f"Keep-alive ping successful: {response.status_code}")
            except requests.exceptions.RequestException as e:
                print(f"Keep-alive ping failed: {e}")
            time.sleep(1200) # Wait for 20 minutes
    
    # ... your bot code ...
    
    if __name__ == "__main__":
        keep_alive_thread = threading.Thread(target=keep_alive)
        keep_alive_thread.daemon = True  # Allow the program to exit even if the thread is running
        keep_alive_thread.start()
        client.run(api_token)
    

    Note: You’ll need to create a simple endpoint (/ping) in your bot’s application that returns a successful HTTP status code (e.g., 200 OK) when the keep-alive request is received. This endpoint can be as simple as returning 'pong' or a similar indication of activity. Ensure this endpoint is correctly configured and accessible from the external network.

  3. Upgrade to a Paid Always-On Hosting Plan: If a keep-alive mechanism is impractical or unreliable, consider upgrading your hosting plan to one that offers continuous operation, regardless of inactivity. Paid hosting plans usually provide always-on guarantees. This is a more straightforward solution, although it incurs a cost.

:mag: Common Pitfalls & What to Check Next:

  • Incorrect Ping Endpoint: Ensure the URL in the requests.get() function points to a valid endpoint that successfully returns a status code indicating it’s up and running. A 404 error (or other HTTP error) indicates the endpoint is not correctly set up. Thoroughly test your ping endpoint before deploying the keep-alive mechanism.

  • Network Issues: If the keep-alive pings fail, check your bot’s internet connection and any network configurations that could be preventing external access to your bot. This includes firewalls, proxy servers, and network address translation (NAT) issues.

  • Firewall Restrictions: Ensure your hosting environment’s firewall or security rules don’t block the keep-alive requests. You might need to configure your firewall to allow inbound connections on the port used by your ping endpoint (typically port 80 or 443).

  • Resource Limits: If your hosting environment has resource limits, the keep-alive requests might consume a portion of your allocated resources. Monitor resource usage to ensure the keep-alive doesn’t negatively impact your bot’s performance.

:speech_balloon: Still running into issues? Share your (sanitized) config files, the exact command you ran, and any other relevant details. The community is here to help!

Listen for the message event and check the attachments property. I’ve found that checking content type beats relying on file extensions - users upload images with weird extensions all the time. The attachment object has a content_type attribute showing ‘image/jpeg’, ‘image/png’, etc. for real images. Don’t forget to handle non-image attachments like docs or videos. Animated GIFs show as ‘image/gif’ if you want your bot responding to those too.

just check msg.attachments when a message is sent. if it sees any images like .jpg or .png, you can make it send a reply. using the newest discord.py is really straight forward for this!

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.