This repository has been archived by the owner on Jun 3, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 13
/
bot.py
206 lines (160 loc) · 7.09 KB
/
bot.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
import json
import logging
import time
import requests
import telegram
from telegram import ParseMode
from telegram.ext import Updater
from telegram.ext.callbackcontext import CallbackContext
from telegram.ext.commandhandler import CommandHandler
from telegram.ext.filters import Filters
from telegram.ext.messagehandler import MessageHandler
from telegram.update import Update
from utils import Utils
BASE_URL_MIXNODE = "https://validator.nymtech.net/api/v1/status/mixnode/"
#BASE_URL_EXPLORER = "https://explorer.nymtech.net/api/v1/mix-node/"
BASE_URL_EXPLORER = "https://mixnet.explorers.guru/mixnode/"
BASE_URL_STAKE = "/stake-saturation"
NG_APY = "https://mixnet.api.explorers.guru/api/mixnodes"
STATE_INACTIVE = "🟥"
STATE_STANDBY = "🟦"
STATE_ACTIVE = "🟩"
STATE_ERROR = "🟨"
TIME_FORMAT = "%d.%m.%y %H:%M:%S"
UNYM = 10 ** 6
class TelegramBot:
def __init__(self, telegramToken, filePath, queryApi):
with open(filePath, "r") as fp:
self.mixnodes = json.load(fp)
self.token = telegramToken
self.queryApi = queryApi
self.updater = Updater(self.token, use_context=True)
self.updater.dispatcher.add_handler(CommandHandler('start', self.start))
self.updater.dispatcher.add_handler(CommandHandler('help', self.help))
self.updater.dispatcher.add_handler(CommandHandler('mixnodes', self.getMixnodes))
self.updater.dispatcher.add_handler(CommandHandler('m', self.getMixnodes))
# self.updater.dispatcher.add_handler(MessageHandler(Filters.text, self.unknown))
# self.updater.dispatcher.add_handler(MessageHandler(Filters.command, self.unknown))
# Filters out unknown messages.
# self.updater.dispatcher.add_handler(MessageHandler(Filters.text, self.unknown_text))
print(f"Start {__name__}")
def startBot(self):
try:
self.updater.start_polling(bootstrap_retries=50, timeout=30)
except Exception as e:
print(e)
def send(self, user, msg):
for __ in range(10):
try:
bot = telegram.Bot(token=self.token)
bot.sendMessage(int(user), text=msg, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True)
except telegram.error.RetryAfter as ra:
print(e)
if int(ra.retry_after) > 60:
print("Flood control exceeded. Retry in 60 seconds")
time.sleep(60)
else:
time.sleep(int(ra.retry_after))
continue
except Exception as e:
print(e)
else:
break
@staticmethod
def getData(url, session):
try:
req = session.get(url)
if req.ok:
return req
except requests.exceptions.RequestException as e:
print(e)
return 0.0
@staticmethod
def formatMixnodes(mixnodes, queryApi):
msg = "\n🪢 Mixnodes 🪢"
s = requests.session()
for mixnode in mixnodes['mixnodes']:
amountStake = 0.0
stake = 0.0
apy = 0.0
if queryApi:
try:
amountStake = float(
TelegramBot.getData(BASE_URL_EXPLORER + mixnode['idkey'], s).json()['total_delegation'][
'amount'])
except KeyError as e:
print(e)
try:
amountStake /= UNYM
except ZeroDivisionError as e:
print(e)
try:
stake = TelegramBot.getData(BASE_URL_MIXNODE + mixnode['idkey'] + BASE_URL_STAKE, s).json()[
'saturation']
except KeyError as e:
print(e)
try:
apy = \
list(filter(lambda x: x["identityKey"] == mixnode['idkey'],
TelegramBot.getData(NG_APY, s).json()))[0][
'apy']
except KeyError as e:
print(e)
try:
msg += "\n"
for user in mixnode.get('user'):
msg += f"[{user}](https://t.me/{user}) - "
except TypeError as e:
print(e)
msg += f"{mixnode['name']}"
msg += f"\nIdentity Key: `{mixnode['idkey']}`"
if stake > 0.0:
msg += f"\nStake saturation: {stake * 100:.2f}% ({Utils.humanFormat(amountStake, 2)} NYM)"
msg += f"\n**Delegations accepted: {STATE_INACTIVE if stake > 0.99 else STATE_ACTIVE}**"
if apy > 0.0:
msg += f"\nAPY: {apy * 100:.2f}%"
msg += f"\n[Explorer](https://mixnet.explorers.guru/mixnode/{mixnode['idkey']})\n"
return msg
@staticmethod
def formatGateways(mixnodes):
msg = "\n\n🚪 Passerelles francophones 🚪"
for gateway in mixnodes['gateways']:
try:
msg += "\n"
for user in gateway.get('user'):
msg += f"[{user}](https://t.me/{user}) - "
except TypeError as e:
print(e)
msg += f"{gateway['name']}"
msg += f"\nIdentity Key: `{gateway['idkey']}`"
msg += f"\n[Explorer](https://explorer.nymtech.net/network-components/gateways)\n"
return msg
@staticmethod
def formatLinks(links):
msg = ""
for link in links['links']:
msg += f"\n🔗 [{link['description']}]({link['link']})\n"
return msg
def start(self, update: Update, context: CallbackContext):
username = update.message.from_user.username
update.message.reply_text(
f"Hello!\nLes mixnodes de la [communauté francophone](https://t.me/nymfrench) sont \n\n{TelegramBot.formatMixnodes(self.mixnodes, self.queryApi)}\nRejoignez-nous sur [Telegram](https://t.me/nymfrench)",
parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True)
def help(self, update: Update, context: CallbackContext):
update.message.reply_text("Available Commands :"
"\n\t/mixnodes - Retrieve mixnodes")
def getMixnodes(self, update: Update, context: CallbackContext):
print(f"mixnode, Data {context.args}")
msg = TelegramBot.formatMixnodes(self.mixnodes, self.queryApi)
msg += TelegramBot.formatGateways(self.mixnodes)
if self.mixnodes.get('links') is not None:
msg += TelegramBot.formatLinks(self.mixnodes)
update.message.reply_text(msg, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True)
def unknown_text(self, update: Update, context: CallbackContext):
print(f"unknown_text: {update.message.text}")
update.message.reply_text(
"Sorry I can't recognize you , you said '%s'" % update.message.text)
def unknown(self, update: Update, context: CallbackContext):
print(f"unknown: {update.message.text}")
update.message.reply_text(
"Sorry '%s' is not a valid command" % update.message.text)