3

I have a python 3.6 script that generates a png image file and I simply want to post this image in a Discord channel at the end of the python script. How can I do so?

It is a surprisingly challenging task as none of the following solutions seem to work

  1. Use CV2 to put an image in a json body. The OpenCV library installation is way to painful. Spend 1 hour and still cannot get

import cv2

done without an error message. Simply give up on CV2.

Unable to import cv2 module (Python 3.6) Install of opencv-python-headless takes a long time Newbie Python, PyCharm and Anaconda issues

def send_image_to_discord(self, image_file, url):
#   this version requires CV2 which is super painful to install

    
    # this function takes the image and send it to the Discord channel

    img = cv2.imread(image_file)

    string_img = base64.b64encode(cv2.imencode('.png', img)[1]).decode()

    req = {"image": string_img}

    res = requests.post(url, json=req)

    return res

URL = 'Discord channel webhook' 
self.send_image_to_discord(image_file, URL)
  1. Use Discord.py but that is more for a BOT with await

    async def send_image_to_discord(self, image_file, discord_channel_id):
    
         client = discord.Client()
    
         channel = client.get_channel(discord_channel_id)
    
         await channel.send('hello')
    
         await channel.send(file=discord.File(image_file))
    
    URL = 'discord channel id'
    self.send_image_to_discord(image_file, url)
    

Any other ways? Thank you!

Axisnix
  • 2,822
  • 5
  • 19
  • 41
Chubaka
  • 2,933
  • 7
  • 43
  • 58
  • What's the problem with the second method? How do you generate the PNG? Do you have any specific problem? – Sairam May 05 '23 at 14:58

1 Answers1

0

One solution is to use discord.py's SyncWebhook. Create a webhook in the channel you want, get the URL, and something like this should work:

from discord import SyncWebhook, File

wh = SyncWebhook.from_url(<webhook url>)
wh.send(file=File(image_file))

An upside to this solution is that you don't even need a bot application in the server.

CircuitSacul
  • 1,594
  • 12
  • 32