]> git.somenet.org - pub/jan/mattermost-bot.git/blob - modules/CommandDrink.py
core/MMBot.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 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"] = "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 = dict()
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 e:
39             if e.message == "CERR_AUTH_FAIL_INVALID_token":
40                 request.cmd_respond_text_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
46         try:
47             cmd = data["text"] = data["text"].strip()
48             if data["text"] == "" or data["text"].lower() == "help":
49                 msg += "\nUse ``/drink [count]<shortcut>`` and one of the following shortcuts to pay for ``$count * $shortcut``.\n\n|shortcut|price|Description|\n|---|---|---|"
50
51                 for s in account_data["shortcuts"]:
52                     if int(s["vislevel"]) >= 2:
53                         msg += "\n|"+s["short"]+"|"+s["amount"]+"|"+s["description"]+"|"
54                 request.cmd_respond_text_temp(msg)
55                 return
56
57             count = None
58             shortcut = None
59
60             mat = re.match(r"(\d*)\s*(\w+)", cmd)
61             if mat is None:
62                 request.cmd_respond_text_temp(msg+"\n:stop_sign: Invalid input: Nothing useful matched.")
63                 return
64
65             (count, sc) = mat.groups()
66
67             if count == "":
68                 count = 1
69
70             count = int(count)
71             if count < 1:
72                 request.cmd_respond_text_temp(msg+"\n:stop_sign: Invalid input: count < 1")
73                 return
74
75             for s in account_data["shortcuts"]:
76                 if s["short"] == sc:
77                     shortcut = s
78                     break
79
80             if shortcut is None:
81                 request.cmd_respond_text_temp(msg+"\n:stop_sign: Invalid input: no such shortcut :(\nUse ``/drink-shortcuts`` for a list of shortcuts.")
82                 return
83             else:
84                 handle.do_transaction(shortcut["target"], str(int(shortcut["amount"])*count), shortcut["reason"])
85                 account_data = handle.get_account_info(True)
86
87                 # Infcoin-IPC
88                 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()))
89
90                 msg = (":arrow_right:Available credits:``"+str(account_data["account_info"]["balance"])+"``"+
91                        "\n:white_check_mark: Sucessfully paid **``"+str(int(shortcut["amount"])*count)+"``** TO **``"+str(shortcut["target"])+"``** FOR **``"+str(shortcut["reason"])+"``** :beers:")
92                 self.bot.debug_chan("``/drink success: @"+data["user_name"]+' --'+str(int(shortcut["amount"])*count)+'--> '+str(shortcut["target"])+'``')
93
94         except MCAPI.APIException as e:
95             if e.message == "CERR_AUTH_FAIL_ACCTOK":
96                 msg += "\n:stop_sign: Mattermost account seems to not be bound to any drink-terminal account. :("
97
98             elif e.message == "CERR_FAILED_TO_SEND":
99                 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"])+"``**"
100
101         request.cmd_respond_text_temp(msg)