Python3 使用 webhook 将图像 .png 发送到 Discord 频道

时间:2021-05-31 22:16:28

标签: python discord discord.py python-3.6 webhooks

我有一个生成 png 图像文件的 python 3.6 脚本,我只想将此图像发布在 python 脚本末尾的 Discord 频道中。我该怎么做?

这是一项非常具有挑战性的任务,因为以下解决方案似乎都不起作用

  1. 使用 CV2 将图像放入 json 正文中。 OpenCV 库的安装很痛苦。用了1小时还是没能拿到

import cv2

没有错误信息就完成了。干脆放弃 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. 使用 Discord.py,但对于带有 await 的 BOT 来说更多

    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)
    

还有其他方法吗?谢谢!

0 个答案:

没有答案