This code saves a discord image to the folder which it is in. I tried to set a destination for the save file, but I haven't found anything on the shutil website which sets the destination. I tried to put a destination in the shutil.copyfileobj brackets, but that didn't work. Also I an relatively new to coding.
This is the code:
import uuid
import requests
import shutil
from discord.ext import commands
class filesaver:
@bot.command()
async def save(ctx):
try:
url = ctx.message.attachments[0].url
except IndexError:
print("Error: No Attachments")
await ctx.send("No Attachments detected!")
else:
if url[0:26] == "https://cdn.discordapp.com":
r= requests.get(url, stream=True)
imageName = str(uuid.uuid4()) '.jpg'
with open(imageName, 'wb') as out_file:
print('saving image: ' imageName)
shutil.copyfileobj(r.raw, out_file)
await ctx.send(f"text")
CodePudding user response:
Your imageName
doesn't contain a path, so it opens in whatever is your current working directory. That's a bit unpredictable. It's also easy to fix.
from pathlib import Path
imageName = str(Path.home() / Path(str(uuid.uuid4()) '.jpg'))
You can of course replace Path.home()
with any destination path you'd prefer.