]> git.somenet.org - pub/jan/mattermost-bot.git/blob - modules/DialogManagedInfCoin.py
core/MMBot.py
[pub/jan/mattermost-bot.git] / modules / DialogManagedInfCoin.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 json
7 import os
8 import requests
9
10
11 # pylint: disable=wrong-import-position
12 from AbstractCommand import AbstractCommand
13 class DialogManagedInfCoin(AbstractCommand):
14     TRIGGER = "inf-coin"
15     CONFIG = {"display_name": "somebot-command", "auto_complete": True,
16 #              "auto_complete_hint": "Manage your Inf-Coins",
17              }
18     USEINFO = CONFIG["auto_complete_desc"] = CONFIG["description"] = "Will make @bot send you a Inf-Coin managing post."
19
20
21     def __init__(self, team_id, datadir, infcoin_req_url, infcoin_req_user, infcoin_req_pw, infcoin_req_amount=100):
22         super().__init__(team_id)
23
24         self.datadir = datadir
25         self.infcoin_req_url = infcoin_req_url
26         self.infcoin_req_user = infcoin_req_user
27         self.infcoin_req_pw = infcoin_req_pw
28         self.infcoin_req_amount = infcoin_req_amount
29
30
31     def on_POST(self, request, data):
32 #        self._require_bot_admin(data) # will throw an exception if not. (Dont try-except: Its handled up the stack.)
33
34         msg = cleandoc("""
35             ``AUTODELETE-DAY``
36             ## ``(FS)Inf``:coin: ``Management`` :rocket:
37             **Inf-Coins, previously FSInf-Coins are tokens of gratitude and appreciation without any inherent value.**
38             For more details about Inf-Coin, [visit its professional website!](https://infcoin.jvales.net)
39
40             You will be rewarded 1 Inf-Coin for setting your wallet address for the first time. :rocket:
41
42             To send Inf-Coins to somebody, use the command ``/send-inf-coin @<ACCOUNTNAME>``
43
44             #### How to proceed
45             + Get yourself a NEO wallet which supports NEO2-Testnet. At least these should do:
46               + https://testnet.neotracker.io/wallet (Web)
47               + https://neoline.io/en/ (Extension)
48
49             + Once setup, start tracking the [$Inf (f26c60f640091e2fa8cd15b30bb5f51cd4d2048b) asset on NEO2-testnet](https://testnet.neotube.io/nep5/f26c60f640091e2fa8cd15b30bb5f51cd4d2048b/page/1) in your wallet.
50             + As soon as you get Inf-Coins your wallet should display them to you and you should be able to transfer them.
51
52             :information_source: *Coin minting cannot be done automatically is a secure manner so it might take a while for you to receive your Inf-Coins.*
53             :warning:**If you need to update your addess, because you gave a wrong one, contact @someone so your coins dont get send on the old address. Once sent, there is no undo.**
54             """)
55
56         att = [{
57             "text": "Self-Management",
58             "actions": [
59                 {"name": ":pencil: Set your Inf-Coin wallet address", "integration": {"url": self.URL+"/interactive"}},
60                 #{"name": ":rocket: Claim newly received Inf-Coins", "integration": {"url": self.URL+"/interactive"}}
61             ]
62             #},{
63             #"text": "Off-Chain",
64             #"actions": [{"name": ":package: Send unclaimed coins to somebody", "integration": {"url": self.URL+"/interactive"}}]
65             }]
66
67         c = self.bot.api.create_dm_channel_with(data['user_id'])
68         p = self.bot.api.create_post(c['id'], msg, props={"from_webhook":"true", "attachments":att})
69         request.respond_cmd_temp("@bot has written you a direct message.\n:arrow_right: https://mattermost.fsinf.at/"+data["team_domain"]+"/pl/"+p["id"])
70
71
72     def on_POST_interactive(self, request, data):
73         #import pprint
74         #print("on_POST_interactive")
75         #pprint.pprint(data)
76
77         callback_id = "wallet-"+data["user_id"]
78         infcoin_wallet = json.loads(self._wallet_load(self.datadir+callback_id, ".json", '{"wallet":""}'))
79
80         dialog = {
81             "callback_id": callback_id,
82             "title": "Set your Inf-Coin/NEO2-Testnet wallet address",
83             "submit_label":"Submit",
84             "elements":[{
85                 "display_name": "Your Inf-Coin/NEO2-Testnet wallet address",
86                 "placeholder": "Paste here.",
87                 "name": "infcoin_wallet",
88                 "type": "text",
89                 "help_text": "The wallet address is alphanumeric and 34 characters long.",
90                 "optional": True,
91                 "default": infcoin_wallet['wallet']
92             }]
93         }
94
95         self.bot.api.open_dialog(data["trigger_id"], self.URL+"/dialog", dialog)
96         request.respond()
97
98
99
100     def on_POST_dialog(self, request, data):
101         #import pprint
102         #print("on_POST_dialog")
103         #pprint.pprint(data)
104
105         # Validate address.
106         if data["submission"]["infcoin_wallet"] == "":
107             data["submission"]["infcoin_wallet"] = None
108         if data["submission"]["infcoin_wallet"] is not None and not (data["submission"]["infcoin_wallet"].isascii() and data["submission"]["infcoin_wallet"].isalnum() and len(data["submission"]["infcoin_wallet"]) == 34):
109             request.respond(200, {"errors": {"infcoin_wallet": "This doesnt seem like a valid address."}})
110         else:
111             c = self.bot.api.create_dm_channel_with(data['user_id'])
112             existed = self._wallet_store(self.datadir+data["callback_id"], ".json", json.dumps({"wallet":data["submission"]["infcoin_wallet"]}))
113             if not existed and data["submission"]["infcoin_wallet"] is not None:
114                 self.award_infcoins(data["user_id"], self.infcoin_req_amount, "wallet-set")
115                 p = self.bot.api.create_post(c['id'], "``AUTODELETE-DAY`` Wallet address set. Inf-Coins requested.", props={"from_webhook":"true"})
116             elif not existed:
117                 p = self.bot.api.create_post(c['id'], "``AUTODELETE-DAY`` Did nothing.", props={"from_webhook":"true"})
118             else:
119                 p = self.bot.api.create_post(c['id'], "``AUTODELETE-DAY`` Wallet address updated. No Inf-Coins requested.", props={"from_webhook":"true"})
120
121
122
123     def award_infcoins(self, user_id, amount, reason_part):
124         infcoin_wallet = json.loads(self._wallet_load(self.datadir+"wallet-"+user_id, ".json", '{"wallet":""}'))
125         if infcoin_wallet["wallet"] != "":
126             r = requests.get(self.infcoin_req_url, {"auth_name":self.infcoin_req_user, "auth_secret":self.infcoin_req_pw, "addr":infcoin_wallet["wallet"], "amount":amount, "reason_uniq":"mm-"+reason_part+", uid="+user_id})
127             return True
128         return False
129
130
131
132     def _wallet_load(self, path, filename, default=""):
133         path = path+filename
134         ret = default
135         if os.path.isfile(path):
136             with open(path, "r") as f:
137                 ret = f.read()
138         return ret
139
140
141     def _wallet_store(self, path, filename, data):
142         path = path+filename
143         data = str(data).strip()
144         existed = os.path.isfile(path)
145         if not (not existed and data == json.dumps({"wallet":None})):
146             with open(path, "w") as f:
147                 f.write(data)
148         return existed
149