I'm trying to send a PIL Image object to a discord chat (I don't want to save the file though) I have a function that gathers images from the internet, joins them together vertically and then return a PIL Image object.
The code below creates a file image from the PIL Image object on my local machine and then sends it to a Discord chat. I don't want to constantly be recreating and saving the file image on my machine. How can I just send the PIL Image object instead of having to save the image every time I send a request?
from PIL import Image
from io import BytesIO
import requests
import discord
# Initializes Discord Client
client = discord.Client()
# List of market indexes
indexes = [
'https://finviz.com/image.ashx?dow',
'https://finviz.com/image.ashx?nasdaq',
'https://finviz.com/image.ashx?sp500'
]
# Returns a vertical image of market indexes
def create_image():
im = []
for index in indexes:
response = requests.get(index)
im.append(Image.open(BytesIO(response.content)))
dst = Image.new('RGB', (im[0].width, im[0].height + im[1].height + im[2].height))
dst.paste(im[0], (0, 0))
dst.paste(im[1], (0, im[0].height))
dst.paste(im[2], (0, im[0].height + im[1].height))
return dst
# Prints when bot is online
@client.event
async def on_ready():
print('{0.user} is online'.format(client))
# Uploads vertical image of market indexes when requested
@client.event
async def on_message(message):
if message.content.startswith('^index'):
create_image().save('index.png')
await message.channel.send(file=discord.File('index.png'))
SOLUTION:
@client.event
async def on_message(message):
if message.content.startswith('^index'):
with BytesIO() as image_binary:
create_image().save(image_binary, 'PNG')
image_binary.seek(0)
await message.channel.send(file=discord.File(fp=image_binary, filename='image.png'))
The first way to upload an image into Discord is that simple- Just drag an image or GIF from another source and drop it into the Discord window. This can be done on the browser or desktop app! Drag & Drop into the client. That simple!
To upload something to Discord you have to use the File object. A File accepts two parameters, the file-like object (or file path) and the filename to pass to Discord when uploading.
Posting my solution as a separate answer. Thanks Ceres for the recommendation.
@client.event
async def on_message(message):
if message.content.startswith('^index'):
with BytesIO() as image_binary:
create_image().save(image_binary, 'PNG')
image_binary.seek(0)
await message.channel.send(file=discord.File(fp=image_binary, filename='image.png'))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With