-
Notifications
You must be signed in to change notification settings - Fork 27
/
frontiers_callback.py
184 lines (160 loc) · 6.42 KB
/
frontiers_callback.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Nano Telegram bot
# @NanoWalletBot https://t.me/NanoWalletBot
#
# Source code:
# https://github.com/SergiySW/NanoWalletBot
#
# Released under the BSD 3-Clause License
#
"""
Usage:
Press Ctrl-C on the command line or send a signal to the process to stop the server.
"""
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
from telegram import Bot, ParseMode
from telegram.error import BadRequest
from telegram.utils.request import Request
import logging
import socket, json
import time, math
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
from SocketServer import ThreadingMixIn
import threading
# Parse config
from six.moves import configparser
config = configparser.ConfigParser()
config.read('bot.cfg')
log_file_frontiers = config.get('main', 'log_file_frontiers')
wallet = config.get('main', 'wallet')
fee_account = config.get('main', 'fee_account')
fee_amount = int(config.get('main', 'fee_amount'))
welcome_account = config.get('main', 'welcome_account')
large_amount_warning = int(config.get('main', 'large_amount_warning'))
callback_port = int(config.get('main', 'callback_port'))
# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO, filename=log_file_frontiers)
logging.getLogger("requests").setLevel(logging.WARNING)
logger = logging.getLogger(__name__)
account_url = 'https://nanocrawler.cc/explorer/account/'
hash_url = 'https://nanocrawler.cc/explorer/block/'
faucet_account = 'nano_13ezf4od79h1tgj9aiu4djzcmmguendtjfuhwfukhuucboua8cpoihmh8byo'
# MySQL requests
from common_mysql import *
# Request to node
from common_rpc import *
# Common functions
from common import push, mrai_text, bot_start
# Translation
with open('language.json') as lang_file:
language = json.load(lang_file)
def lang_text(text_id, lang_id):
try:
return language[lang_id][text_id]
except KeyError:
return language['en'][text_id]
class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
allow_reuse_address = True
"""Handle requests in a separate thread."""
class POST_server(BaseHTTPRequestHandler):
def do_POST(self):
post_string = self.rfile.read(int(self.headers['Content-Length']))
post = json.loads(post_string)
#print(post)
self.send_response(200)
self.send_header('Content-Type','application/json')
self.end_headers()
# Return empty JSON
self.wfile.write('{}\n')
xrb_account = post['account']
account = mysql_select_by_account(xrb_account)
if (account is False):
account = mysql_select_by_account_extra(xrb_account)
if (account is not False):
block = json.loads(post['block'])
if ((block['type'] == 'state') and (block['subtype'] == 'receive')):
bot = bot_start()
raw_received = int(post['amount'])
received_amount = int(math.floor(raw_received / (10 ** 24)))
balance = account_balance(xrb_account)
try:
mysql_balance = int(account[3])
except Exception as e:
mysql_balance = 0
if (mysql_balance == balance): # workaround
logging.warning('Warning receive balance change. Old: {0}, new: {1}'.format(mysql_balance, balance))
time.sleep(1)
balance = account_balance(xrb_account)
if (mysql_balance == balance):
time.sleep(8)
balance = account_balance(xrb_account)
# workaround
frontier = post['hash']
try:
z = account[5]
mysql_update_frontier_extra(account[1], frontier)
except IndexError as e:
mysql_update_frontier(account[1], frontier)
logging.info('{0} --> {1} {2}'.format(mrai_text(account[3]), mrai_text(balance), frontier))
# retrieve sender
send_source = block['link']
block_account = rpc({"action":"block_account","hash":send_source}, 'account')
lang_id = mysql_select_language(account[0])
sender = lang_text('frontiers_sender_account', lang_id).format(block_account)
# Sender info
if (block_account == faucet_account):
sender = lang_text('frontiers_sender_faucet', lang_id)
elif ((block_account == fee_account) or (block_account == welcome_account)):
sender = lang_text('frontiers_sender_bot', lang_id)
elif (block_account == account[1]):
sender = lang_text('frontiers_sender_self', lang_id)
else:
sender_account = mysql_select_by_account(block_account)
if (sender_account is not False):
if ((sender_account[4] is not None) and (sender_account[4])):
sender = lang_text('frontiers_sender_username', lang_id).format(sender_account[4])
else:
sender = lang_text('frontiers_sender_users', lang_id).format(block_account)
else:
sender_account_extra = mysql_select_by_account_extra(block_account)
if (sender_account_extra is not False):
user_sender = mysql_select_user(sender_account_extra[0])
if ((user_sender[8] is not None) and (user_sender[8]) and (account[0] != sender_account_extra[0])):
sender = lang_text('frontiers_sender_username', lang_id).format(user_sender[8])
elif (account[0] != sender_account_extra[0]):
sender = lang_text('frontiers_sender_users', lang_id).format(block_account)
try:
z = account[5]
sender = lang_text('frontiers_sender_by', lang_id).format(sender, account[1].replace("_", "\_"))
mysql_update_balance_extra(account[1], balance)
except IndexError as e:
mysql_update_balance(account[1], balance)
logging.info(sender)
logging.info(block_account)
logging.info('{0} Nano (XRB) received by {1}, hash: {2}'.format(mrai_text(received_amount), account[0], frontier))
text = lang_text('frontiers_receive', lang_id).format(mrai_text(received_amount), mrai_text(balance), mrai_text(0), frontier, hash_url, sender)
mysql_set_sendlist(account[0], text)
#print(text)
try:
push(bot, account[0], text)
if (received_amount >= large_amount_warning):
time.sleep(0.25)
push(bot, account[0], lang_text('frontiers_large_amount_warning', lang_id))
except BadRequest as e:
logging.exception('Bad request account {0}'.format(account[0]))
mysql_delete_sendlist(account[0])
return
def log_message(self, format, *args):
return
try:
#Create a web server and define the handler to manage the incoming request
server = ThreadedHTTPServer(('localhost', callback_port), POST_server)
print 'Starting callback server at localhost:{0}'.format(callback_port)
#Wait forever for incoming POST requests
server.serve_forever()
except KeyboardInterrupt:
print 'Stop callback server'
server.socket.close()