Search code examples
python-3.xdiscord.pyemail-attachmentsnextcord

How would I save a file received by discord.py


I was working on my discord bot trying to implement a email feature where you imbed a file and then the discord bot downloads it and sends it back out to the server. I came across the issue where I have no idea how I would begin to save the file. You can find my code at https://github.com/Omar-Alabdalla/DiscordBot. the specific files that have the emailing feature are mailFunctions(discord commands part) and basicMail(email commands part).

I looked through the docs of nextcord.py and couldn't find any simple way that I could understand. I probably just missed what I was supposed to find though.

discord command Code:

@commands.command()
    async def mailFile(self, ctx, *stuff):
        # received if else statement from stackoverflow: https://stackoverflow.com/questions/65169339/download-csv-file-sent-by-user-discord-py
        if str(ctx.attachments) == "[]":  # This checks if there is an attachment on the message
            return "You didn't include a file"
        else:
            await save("mailFile

The mailing class code:

def sendFileMail(rmail, message):
    mail_content = '''Hello,
    This is a test mail.
    In this mail we are sending some attachments.
    The mail is sent using Python SMTP library.
    Thank You
    '''
    # Setup the MIME
    message = MIMEMultipart()
    message['From'] = sender_email
    message['To'] = rmail
    message['Subject'] = 'A test mail sent by Python. It has an attachment.'

    # The subject line
    # The body and the attachments for the mail
    message.attach(MIMEText(mail_content, 'plain'))
    attach_file_name = 'TP_python_prev.pdf'
    attach_file = open(attach_file_name, 'rb')  # Open the file as binary mode
    payload = MIMEBase('application', 'octate-stream')
    payload.set_payload(attach_file.read())
    encoders.encode_base64(payload)  # encode the attachment

    # add payload header with filename
    payload.add_header('Content-Decomposition', 'attachment', filename=attach_file_name)
    message.attach(payload)

    # Create SMTP session for sending the mail
    session = smtplib.SMTP('smtp.gmail.com', 587)  # use gmail with port
    session.starttls()  # enable security
    session.login(sender_email, password)  # login with mail_id and password
    text = message.as_string()
    session.sendmail(sender_email, rmail, text)
    session.quit()
    print('Mail Sent')

Apologies for not including code prior First time posting on stack overflow


Solution

  • See Attachment.save: https://nextcord.readthedocs.io/en/latest/api.html?highlight=attachment#nextcord.Attachment.save

    for attachment in ctx.message.attachments:
        await attachment.save(attachment.filename)