Capturing an image from a link in a Discord message using Discord.py

I'm in the process of developing a bot that can save links sent in messages automatically. When a user sends the command -save test.com/123.png, my bot is designed to download the file named 123.png.

Although I have experience downloading directly attached files, I am currently looking for a way to make it work with links as well. I've searched online for a solution, but haven't come across anything that has proved helpful so far.

Answer №1

After discovering a solution on my own, I stumbled upon an old Python file of mine that happened to have the exact code I needed.

@client.command()
async def test(ctx, url):
    ftype = url.split('/')[-1]
    myfile = requests.get(url)
    open(f'D:\\Tools\\python\\file_{ftype}', 'wb').write(myfile.content)

Answer №2

Instead of loading all messages, this code only downloads images when a user sends a file.

@client.event
async def on_message(message):

    if len(message.attachments) > 0:
        attachment = message.attachments[0]

    if (
        attachment.filename.endswith(".jpg")
        or attachment.filename.endswith(".jpeg")
        or attachment.filename.endswith(".png")
        or attachment.filename.endswith(".webp")
        or attachment.filename.endswith(".gif")
    ):
        img_data = requests.get(attachment.url).content
        with open("image_name.jpg", "wb") as handler:
            handler.write(img_data)

    elif (
        "https://images-ext-1.discordapp.net" in message.content
        or "https://tenor.com/view/" in message.content
    ):
        print(message.content)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The error message "AttributeError: 'module' does not contain a 'document' attribute" indicates that the specified module does not have a

I'm trying to use Python (2.7.10) and Selenium to input a username and password, but I keep encountering the following error. Can anyone help me fix it? CODE:- from selenium import webdriver import selenium driver = webdriver.Chrome("/Users/username ...

Encountering issues with the functionality of the Pyinstaller executable file

After creating an executable using pyinstaller, I faced an issue where the executable file would open a blank cmd window that closes after a few seconds. Interestingly, when I run the python file directly using python file.py in the command prompt, it work ...

Troubleshooting Jinja2 templates with VSCode

I recently discovered the "jinja: "true" option in my launch.json file and have been attempting to get jinja debugging to function properly, but without success so far. Here is what my launch.json currently looks like: { "version&q ...

Scraping from the web: How to selectively crawl and eliminate duplicate items

What is the most effective method for ensuring that Scrapy does not store duplicate items in a database when running periodically to retrieve new content? Would assigning items a hash help prevent this issue? Your advice on avoiding duplicates would be g ...

Utilize Python to extract targeted JSON keys and transform them into CSV format

My code currently converts all data in a JSON file into a CSV, but I need it to only extract specific nested data. Here's the desired process: Load JSON file [done] Extract certain nested data in the JSON file [wip] Convert to CSV [done] Existing Co ...

What could be causing my Python multiprocessing pools to have idle workers?

As I divide a large text file into smaller chunks for further processing, the code utilizes a list of lists named text_chunks, each containing a section of text. The length of these sections varies from ~50 to ~15000 characters. Elsewhere in the code, ther ...

changing the black backdrop with a different picture

I've been experimenting with replacing black pixels in an image with pixels from another image... Here's the code snippet I have come up with: imgFront = cv2.imread('withoutbackground.jpg') imgBack = cv2.imread('background.jpg&ap ...

Generate a personalized report for the Behave Python framework, requiring retrieval of both the Scenario Name and its corresponding status

Looking to generate a personalized report for the Behave and Python framework. The goal is to retrieve the Scenario Name and status. Any suggestions on how to accomplish this? Curious if there is an event listener class available in the behave framework t ...

Showing images from a database using PHP

I'm currently developing a content management system (CMS) that allows users to add articles and optionally upload an image for each article. While the text of the articles is displaying correctly, I am encountering issues with the images not being di ...

Python Selenium: How to locate elements using xpath in the presence of duplicate elements within the HTML code

Currently, I am utilizing selenium to extract data from a liquor sales website to streamline the process of adding product information to a spreadsheet. My workflow involves logging into the website using selenium and searching for the specific product. Wh ...

To access the first element of the list in the instance, simply call instance(0, 0) in Python

Hey there! I'm trying to work with a class called Grid, which has an instance grid. My goal is to have grid(0, 0) return the value of grid.content[0][0]. The content property of the grid object is a list containing other lists. class Grid(): def __i ...

Moving a window in Pyqt5 using QtWebChannel

My goal is to enable the mousePressEvent and mouseMoveEvent events in order to move my app window using QtWebChannel. To achieve this, I am utilizing self.setWindowFlags(QtCore.Qt.FramelessWindowHint) to eliminate the default window flag and create a cust ...

What is the method for specifying a dependency on gi.repository in setup.py, as well as the necessary C library?

I need to package a python application that relies on multiple C libraries via gobject introspection. My main concern is ensuring the presence of the gi module from the glib, also known as python-gi in Debian (not to be confused with PyGObject). However, a ...

Metric count in Datadog decreasing across various containers

When using Python, I am incrementing a Datadog counter: from datadog import initialize from datadog import ThreadStats stats.increment('api.request_count', tags=['environment:' + environment]) I have configured the metric type as "cou ...

Managing disconnection using Python's jsocket

I have implemented a json socket server/client using the jsocket python library. The issue I am facing is that my server crashes after the first time the connection is closed. How can I ensure the server stays running? Below is the code for the server: i ...

Retrieve the name of the subparser program using Python's argparse module to include in the help message

Currently, I am developing an argument parser for a Python module that includes multiple subparsers. My main goal is to create a shared argument whose Argument constructor is passed on to several child components: from argparse import ArgumentParser parse ...

Scheduler sending a barrage of emails

I'm currently utilizing Django RQ scheduler File: scheduled_tasks.py from redis import Redis from rq_scheduler import Scheduler from datetime import datetime scheduler = Scheduler(connection=Redis()) # Creating a scheduler for the "default" queue ...

What is the process of incorporating G-mean into the cross_validate sklearn function?

from sklearn.model_selection import cross_validate scores = cross_validate(LogisticRegression(class_weight='balanced',max_iter=100000), X,y, cv=5, scoring=('roc_auc', 'average_precision','f1', ...

python asyncio.gather incorporates user input into the final result

My function looks something like this: async def funcn(input: input_type) -> output_type: .... return output I am using asyncio.gather to call it in the following way: output = await asyncio.gather(*[funcn(input) for input in input_list]) The retu ...

Reducing the number of features of a single image during the inference process

I am currently working on training a SVM classifier with scikit-learn. During the training process, I need to decrease the dimension of the feature vector. To achieve this, I have utilized PCA for dimensionality reduction. pp = PCA(n_components=400).fit(fe ...