]> git.somenet.org - pub/jan/mattermost-bot.git/blob - modules/WSConvertWebp.py
modules/CommandDSACheck.py
[pub/jan/mattermost-bot.git] / modules / WSConvertWebp.py
1 # Mattermost Bot module.
2 #  Copyright (c) 2016-2022 by Someone <someone@somenet.org> (aka. Jan Vales <jan@jvales.net>)
3 #  published under MIT-License
4
5 import json
6 import tempfile
7 from PIL import Image
8
9
10 from AbstractWSHandler import *
11 class WSConvertWebp(AbstractWSHandler):
12     NAME = "convertwebp"
13
14     def on_WS_EVENT(self, data):
15         post = json.loads(data["data"]["post"])
16
17         if not "metadata" in post or not "files" in post["metadata"]:
18             return False
19
20         with tempfile.TemporaryDirectory() as tmpdirname:
21             tempfilenames = []
22             for mmfile in post["metadata"]["files"]:
23                 if mmfile["mime_type"] == "image/webp":
24                     res = self.bot.api.get_file(mmfile["id"])
25                     open(tmpdirname+"/"+mmfile["id"]+".webp", 'wb').write(res.content)
26                     image = Image.open(tmpdirname+"/"+mmfile["id"]+".webp").convert("RGB")
27                     image.save(tmpdirname+"/"+mmfile["id"]+".png", "png")
28                     tempfilenames.append(tmpdirname+"/"+mmfile["id"]+".png")
29
30             if tempfilenames:
31                 root_id = post["id"]
32                 if post["root_id"] != "":
33                     root_id = post["root_id"]
34                 self.bot.api.create_post(post['channel_id'], "Let me convert that for you", props={"from_webhook":"true"}, filepaths=tempfilenames, root_id=root_id)
35                 return True