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