]> git.somenet.org - pub/jan/mattermost-bot.git/blob - modules/DialogManagedGuess.py
requirements.txt
[pub/jan/mattermost-bot.git] / modules / DialogManagedGuess.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 from inspect import cleandoc
6 import glob
7 import os
8
9
10 # pylint: disable=wrong-import-position
11 from AbstractCommand import AbstractCommand
12 class DialogManagedGuess(AbstractCommand):
13     TRIGGER = "guess"
14     CONFIG = {"display_name": "somebot-command", "auto_complete": True,
15               "auto_complete_hint": "",
16              }
17     CONFIG["auto_complete_desc"] = CONFIG["description"] = AbstractCommand.ICON_PRIVATE+"Opens dialog to edit/delete your guess."
18
19
20     def __init__(self, team_id, datadir):
21         super().__init__(team_id)
22
23         self.datadir = datadir
24
25
26     def on_POST(self, request, data):
27         #self._open_dialog(request, data)
28         #request.respond_cmd_temp("## :white_check_mark: Success! :)\n#### Opened dialog.")
29         request.respond_cmd_err("No guessing game running.")
30
31
32 #    def dis_on_POST_interactive(self, request, data):
33 #        import pprint
34 #        print("on_POST_interactive")
35 #        pprint.pprint(data)
36
37         #self._open_dialog(request, data)
38         #request.respond()
39
40
41     def dis_on_POST_dialog(self, request, data):
42 #        import pprint
43 #        print("on_POST_dialog")
44 #        pprint.pprint(data)
45
46         errors = {}
47         if data["submission"]["guess_count"] and int(data["submission"]["guess_count"]) < 0:
48             errors["guess_count"] = "Count must be positive."
49
50         if data["submission"]["guess_value"] and int(data["submission"]["guess_value"]) < 0:
51             errors["guess_value"] = "Value must be positive."
52
53         counts = []
54         for f in glob.glob("data/guess/*-guess_count.txt"):
55             if data["callback_id"] in f:
56                 continue
57             with open(f, "r") as fd:
58                 counts.append(int(fd.read()))
59
60         if int(data["submission"]["guess_count"]) in counts:
61             errors["guess_count"] = "Count must be unique. Somebody else already logged this guess before you."
62
63         values = []
64         for f in glob.glob("data/guess/*-guess_value.txt"):
65             if data["callback_id"] in f:
66                 continue
67             with open(f, "r") as fd:
68                 values.append(int(fd.read()))
69
70         if int(data["submission"]["guess_value"]) in values:
71             errors["guess_value"] = "Value must be unique. Somebody else already logged this guess before you."
72
73         if errors:
74             request.respond(200, {"errors": errors})
75             return
76
77
78         user = self.bot.api.get_user(data['user_id'])
79         self._response_store(self.datadir+data["callback_id"], "guess_count.txt", str(int(data["submission"]["guess_count"])), user["username"])
80         self._response_store(self.datadir+data["callback_id"], "guess_value.txt", str(int(data["submission"]["guess_value"])), user["username"])
81
82         request.respond(200, {})
83
84
85     def _open_dialog(self, request, data):
86         callback_id = "res-"+data["user_id"]+"-"
87
88         guess_count = self._response_load(self.datadir+callback_id, "guess_count.txt")
89         guess_value = self._response_load(self.datadir+callback_id, "guess_value.txt")
90
91         dialog = {
92             "callback_id": callback_id,
93             "title": "Guess the coins",
94             "submit_label":"Submit",
95             "elements":[{
96                 "display_name": "Count of all coins?",
97                 "placeholder": "Count. Positive integer.",
98                 "name": "guess_count",
99                 "type": "text",
100                 "subtype": "number",
101                 "optional": True,
102                 "default": guess_count
103             },{
104                 "display_name": "Value of all coins?",
105                 "placeholder": "EUR Value. Positive integer.",
106                 "name": "guess_value",
107                 "type": "text",
108                 "subtype": "number",
109                 "optional": True,
110                 "default": guess_value
111             }]
112         }
113
114         self.bot.api.open_dialog(data["trigger_id"], self.URL+"/dialog", dialog)
115
116
117     def _response_load(self, path, filename, default=""):
118         path = path+filename
119         ret = default
120         if os.path.isfile(path):
121             with open(path, "r") as f:
122                 ret = f.read()
123         return ret
124
125
126     def _response_store(self, path, filename, data, username=""):
127         path = path+filename
128         data = str(data).strip()
129         if data == "" or data == "None" or data == "0":
130             if os.path.isfile(path):
131                 os.remove(path)
132                 self.bot.debug_chan("``guess::"+filename+"`` (**``@"+username+"``**) result deleted.")
133         else:
134             with open(path, "w") as f:
135                 f.write(data)
136             self.bot.debug_chan("``guess::"+filename+"`` by (**``@"+username+"``**) result stored.")