]> git.somenet.org - pub/jan/mattermost-bot.git/blob - modules/CommandDrink.py
core/AbstractCommand.py
[pub/jan/mattermost-bot.git] / modules / CommandDrink.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 re
7 import datetime
8
9 import MCAPI
10
11 # pylint: disable=wrong-import-position
12 from AbstractCommand import AbstractCommand
13 class CommandDrink(AbstractCommand):
14     TRIGGER = "drink"
15     CONFIG = {"display_name": "somebot-command", "auto_complete": True,
16               "auto_complete_hint": "['help'|<[count]shortcut>]",
17              }
18     USEINFO = CONFIG["auto_complete_desc"] = CONFIG["description"] = AbstractCommand.ICON_PRIVATE+"Buy a drink."
19
20
21     def __init__(self, team_id, drink_terminal_user, drink_terminal_pass):
22         super().__init__(team_id)
23
24         self.drink_terminal_user = drink_terminal_user
25         self.drink_terminal_pass = drink_terminal_pass
26
27
28     def on_POST(self, request, data, rerun=True):
29         try:
30             apirequest = {}
31             apirequest["act"] = "create_token_secret"
32             handle = MCAPI.API("KEYBOARD", self.drink_terminal_user, self.drink_terminal_pass)
33             token_secret = handle.api_request(apirequest)
34             handle = MCAPI.API("MM", data["user_id"])
35             MCAPI.API.token_secret = token_secret["token_secret"]
36             account_data = handle.get_account_info()
37             msg = ":arrow_right: Available credits:``"+str(account_data["account_info"]["balance"])+"``"
38         except MCAPI.APIException as exc:
39             if exc.message == "CERR_AUTH_FAIL_ACCTOK":
40                 request.respond_cmd_temp(cleandoc("""
41                     :stop_sign: Mattermost account seems to not be bound to any drink-terminal account. :(
42                     Use ``/drink-bind-account <drink-terminal-username> <drink-terminal-password>`` to bind this Mattermost account to your drink-terminal account.
43                     """))
44                 return
45             raise exc
46
47
48         try:
49             cmd = data["text"] = data["text"].strip()
50             if data["text"] == "" or data["text"].lower() == "help":
51                 msg += "\nUse ``/drink [count]<shortcut>`` and one of the following shortcuts to pay for ``$count * $shortcut``.\n\n|shortcut|price|Description|\n|---|---|---|"
52
53                 for s in account_data["shortcuts"]:
54                     if int(s["vislevel"]) >= 2:
55                         msg += "\n|"+s["short"]+"|"+s["amount"]+"|"+s["description"]+"|"
56                 request.respond_cmd_temp(msg)
57                 return
58
59             count = None
60             shortcut = None
61
62             mat = re.match(r"(\d*)\s*(\w+)", cmd)
63             if mat is None:
64                 request.respond_cmd_temp(msg+"\n:stop_sign: Invalid input: Nothing useful matched.")
65                 return
66
67             (count, sc) = mat.groups()
68
69             if count == "":
70                 count = 1
71
72             count = int(count)
73             if count < 1:
74                 request.respond_cmd_temp(msg+"\n:stop_sign: Invalid input: count < 1")
75                 return
76
77             for s in account_data["shortcuts"]:
78                 if s["short"] == sc:
79                     shortcut = s
80                     break
81
82             if shortcut is None:
83                 request.respond_cmd_temp(msg+"\n:stop_sign: Invalid input: no such shortcut :(\nUse ``/drink`` without any parameters for a list of shortcuts.")
84                 return
85             else:
86                 handle.do_transaction(shortcut["target"], str(int(shortcut["amount"])*count), shortcut["reason"])
87                 account_data = handle.get_account_info(True)
88
89                 # Infcoin-IPC
90                 self.bot.modules[self.TEAM_ID]["inf-coin"].award_infcoins(data["user_id"], 100, "drink-use, ts="+str(datetime.datetime.now().replace(microsecond=0).isoformat()))
91
92                 self.bot.debug_chan("``/drink success: @"+data["user_name"]+' --'+str(int(shortcut["amount"])*count)+'--> '+str(shortcut["target"])+'``')
93                 request.respond_cmd_temp("## :white_check_mark: Success! :)\n:arrow_right:Available credits:``"+str(account_data["account_info"]["balance"])+"``"+
94                     "\n:white_check_mark: Sucessfully paid **``"+str(int(shortcut["amount"])*count)+"``** TO **``"+str(shortcut["target"])+"``** FOR **``"+str(shortcut["reason"])+"``** :beers:"
95                     )
96
97         except MCAPI.APIException as exc:
98             if exc.message == "CERR_AUTH_FAIL_ACCTOK":
99                 msg += "\n:stop_sign: Mattermost account seems to not be bound to any drink-terminal account. :("
100
101             elif exc.message == "CERR_FAILED_TO_SEND":
102                 msg += "\n:stop_sign: Failed to send drink-credits. Balance exceeded? Sending too much? :(\nTried to send **``"+str(int(shortcut["amount"])*count)+"``** TO **``"+str(shortcut["target"])+"``** FOR **``"+str(shortcut["reason"])+"``**"
103
104             request.respond_cmd_err(msg)