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