]> git.somenet.org - pub/jan/mattermost-bot.git/blob - modules/WSConvertWebp.py
core/AbstractCommand.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 # pylint: disable=wrong-import-position
11 from AbstractWSHandler import AbstractWSHandler
12 class WSConvertWebp(AbstractWSHandler):
13     NAME = "convertwebp"
14
15     def on_WS_EVENT(self, data):
16         post = json.loads(data["data"]["post"])
17
18         if not "metadata" in post or not "files" in post["metadata"]:
19             return False
20
21         with tempfile.TemporaryDirectory() as tmpdirname:
22             tempfilenames = []
23             for mmfile in post["metadata"]["files"]:
24                 if mmfile["mime_type"] in ["image/webp", "invalid-image/webp"]:
25                     res = self.bot.api.get_file(mmfile["id"])
26                     with open(tmpdirname+"/"+mmfile["id"]+".webp", 'wb') as tmpfile:
27                         tmpfile.write(res.content)
28                         image = Image.open(tmpdirname+"/"+mmfile["id"]+".webp").convert("RGB")
29                         image.save(tmpdirname+"/"+mmfile["id"]+".png", "png")
30                         tempfilenames.append(tmpdirname+"/"+mmfile["id"]+".png")
31
32             if tempfilenames:
33                 root_id = post["id"]
34                 if post["root_id"] != "":
35                     root_id = post["root_id"]
36                 self.bot.api.create_post(post['channel_id'], "Let me convert that webp for you", props={"from_webhook":"true"}, filepaths=tempfilenames, root_id=root_id)
37                 return True