· 7 years ago · Dec 10, 2018, 05:16 PM
1import os
2import json
3import requests
4import binance
5import re
6import lxml
7import time
8import atexit
9from apscheduler.schedulers.background import BackgroundScheduler
10from binance.client import Client
11from bs4 import BeautifulSoup, Tag
12from flask import Flask, request, jsonify
13from flask_sslify import SSLify
14
15app = Flask(__name__)
16# sslify = SSLify(app)
17global last_update_id
18last_update_id = -1
19URL = 'https://api.telegram.org/bot788997844:AAHhO_dpfsBncq6uTMZiUva9GHOOgySKs98/'
20api_key = 'vmPUZE6mv9SD5VNHk4HlWFsOr6aKE2zvsw0MuIgwCIPy6utIco14y7Ju91duEh8A' #https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md
21secret_key = 'NhqPtmdSJYdKjVHjA7PZj4Mge3R5YNiP1e3UZjInClVN65XAbvqqM6A7H5fATj0j' #https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md
22schedulers = {}
23
24# http://127.0.0.1:5000/788997844:AAHhO_dpfsBncq6uTMZiUva9GHOOgySKs98/prices?coeff=1&coin=btc&another_coin=usd&market=bin
25# http://127.0.0.1:5000/788997844:AAHhO_dpfsBncq6uTMZiUva9GHOOgySKs98/trades?coin=btc&another_coin=usd&market=bin&number=7
26# http://127.0.0.1:5000/788997844:AAHhO_dpfsBncq6uTMZiUva9GHOOgySKs98/news
27
28@app.route('/788997844:AAHhO_dpfsBncq6uTMZiUva9GHOOgySKs98/prices', methods=['GET'])
29def prices():
30 if request.method == 'GET':
31 return str(get_prices(float(request.args.get('coeff')), request.args.get('coin'), request.args.get('another_coin'), request.args.get('market')))
32
33
34@app.route('/788997844:AAHhO_dpfsBncq6uTMZiUva9GHOOgySKs98/trades', methods=['GET'])
35def trades():
36 if request.method == 'GET':
37 return get_trades(request.args.get('coin'), request.args.get('another_coin'), request.args.get('market'), int(request.args.get('number')))
38
39
40@app.route('/788997844:AAHhO_dpfsBncq6uTMZiUva9GHOOgySKs98/news', methods=['GET'])
41def news():
42 if request.method == 'GET':
43 all_news = take_tut_by()[:3]
44 all_news.extend(take_bits()[:3])
45 return '\n\n'.join(':\n'.join(i) for i in all_news)
46
47
48
49
50
51def write_json(data, filename='answer.json'):
52 with open(filename, 'w') as f:
53 json.dump(data, f, indent=4, ensure_ascii=False)
54
55
56def send_message(chat_id, text='Why did you bother me?'):
57 url = URL + 'sendMessage'
58 answer = {'chat_id': chat_id, 'text': text}
59 r = requests.post(url, json=answer)
60 return r.json()
61
62def get_ticker_bitfinex(coin):
63 url = f'https://api.bitfinex.com/v1/pubticker/{coin}usd'
64 response = requests.request("GET", url)
65 return float(re.compile('"last_price":"(.*?)"').findall(response.text)[0])
66
67
68def get_trades_bitfinex(coin, another_coin):
69 url = f'https://api.bitfinex.com/v1/trades/{coin}{another_coin}'
70 response = requests.request("GET", url)
71 answer = list(zip(re.compile('"price":"(.*?)"').findall(response.text),
72 re.compile('"amount":"(.*?)"').findall(response.text),
73 re.compile('"type":"(.*?)"').findall(response.text)))
74 value = 'buy'
75 if not answer:
76 url = f'https://api.bitfinex.com/v1/trades/{another_coin}{coin}'
77 response = requests.request("GET", url)
78 answer = list(zip(re.compile('"price":"(.*?)"').findall(response.text),
79 re.compile('"amount":"(.*?)"').findall(response.text),
80 re.compile('"type":"(.*?)"').findall(response.text)))
81 value = 'sell'
82 return answer, value
83
84def take_tut_by():
85 url = 'https://news.tut.by/tag/2522-kriptovalyuta.html?crnd=45707'
86 r = requests.get(url)
87 soup = BeautifulSoup(r.text, "lxml")
88 news = soup.findAll('div', {'class': 'news-entry big annoticed time ni'})
89 answer = []
90 for i in news:
91 href = i.find('a').get('href')
92 title = re.compile('<span.*?>(.*?)</span>').findall(str(i.find('span', {'class': 'entry-head _title'})))[0]
93 answer.append((title, href))
94 return answer
95
96
97def take_bits():
98 url = 'https://bits.media/news/'
99 r = requests.get(url)
100 soup = BeautifulSoup(r.text, "lxml")
101 news = soup.findAll('a', {'class': 'news-name'})
102 answer = []
103 for i in news:
104 href = ''.join(('https://bits.media',i.get('href')))
105 title = re.compile('<a.*?>(.*?)</a>').findall(str(i))[0]
106 answer.append((title, href))
107 return answer
108
109
110def checker(chat_id, coin, sign, value, another_coin, market):
111 rate = get_prices(1, coin, another_coin, market)
112 send_message(chat_id, str(rate))
113
114
115def get_trades(coin, another_coin, market, number):
116 answer = []
117 if market == 'bin':
118 if coin == 'usd':
119 coin = 'TUSD'
120 if another_coin == 'usd':
121 another_coin = 'USDT'
122 client = Client(api_key, secret_key)
123 trades = client.get_recent_trades(symbol=''.join((coin.upper(), another_coin.upper())), limit=int(number))
124 for i in trades:
125 if coin == 'TUSD':
126 coin = 'usd'
127 if another_coin == 'USDT':
128 another_coin = 'usd'
129 answer.append(f'{i["qty"]} {coin} were bought for the price of {i["price"]} {another_coin} per one')
130 elif market == 'bit':
131 trades, value = get_trades_bitfinex(coin.lower(), another_coin.lower())
132 new_trades = []
133 if value == 'buy':
134 for i in trades:
135 if i[2] == 'buy':
136 new_trades.append(i)
137 else:
138 for i in trades:
139 if i[2] == 'sell':
140 new_trades.append(i)
141 for i in new_trades[:min(int(number), len(new_trades) - 1)]:
142 if value == 'buy':
143 answer.append(f'{i[1]} {coin} were bought for the price of {i[0]} {another_coin} per one')
144 else:
145 answer.append(f'{1/float(i[1])} {coin} were bought for the price of {1/float(i[0])} {another_coin} per one')
146 return '\n'.join(answer)
147
148
149def get_prices(coeff, coin, another_coin, market):
150 if another_coin.upper() in ['EUR', 'BYN', 'RUB', 'USD']:
151 url = f'http://free.currencyconverterapi.com/api/v5/convert?q=USD_{another_coin}&compact=y'
152 temp = requests.get(url)
153 soup = BeautifulSoup(temp.text, "lxml")
154 coeff *= float(re.compile('"val":(.*?)\}').findall(str(soup))[0])
155 if market == 'bin':
156 client = Client(api_key, secret_key)
157 all_tickers = client.get_all_tickers()
158 for i in all_tickers:
159 if i['symbol'] == ''.join((coin.upper(), 'USDT')):
160 rate = float(i['price'])
161 return coeff * rate
162 send_message(chat_id, 'sorry i don\'t understand')
163 elif market == 'bit':
164 return get_ticker_bitfinex(coin.lower()) * coeff
165 else:
166 if market == 'bin':
167 client = Client(api_key, secret_key)
168 all_tickers = client.get_all_tickers()
169 good = 0
170 for i in all_tickers:
171 if i['symbol'] == ''.join((coin.upper(), 'USDT')):
172 rate1 = float(i['price'])
173 good += 1
174 if i['symbol'] == ''.join((another_coin.upper(), 'USDT')):
175 rate2 = float(i['price'])
176 good += 1
177 if good == 2:
178 rate = rate1 / rate2
179 return coeff * rate
180 else:
181 send_message(chat_id, 'sorry i don\'t understand')
182 elif market == 'bit':
183 rate = get_ticker_bitfinex(coin.lower()) / get_ticker_bitfinex(another_coin.lower())
184 return coeff * rate
185
186def get_updates():
187 url = URL + 'getUpdates'
188 r = requests.get(url)
189 return r.json()
190
191
192def get_message():
193 data = get_updates()
194 last_object = data['result'][-1]
195 global last_update_id
196 if last_update_id != last_object['update_id']:
197 chat_id = last_object['message']['chat']['id']
198 message_text = last_object["message"]['text']
199 last_update_id = last_object['update_id']
200 return {'message': message_text, 'chat_id': chat_id}
201 return None
202
203
204def index():
205 while True:
206 answer = get_message()
207 if answer != None:
208 chat_id = answer['chat_id']
209 message = answer['message']
210
211 if message == 'news':
212 all_news = take_tut_by()[:3]
213 all_news.extend(take_bits()[:3])
214 send_message(chat_id, '\n\n'.join(':\n'.join(i) for i in all_news))
215 elif message == 'help':
216 comands = '\'coefficient\' \'cryptocurrency\' to \'currency\' bin - check curs;\n\n news - get news abot cryptocurrency;\n\n trades \'cryptocurrency\' \'currency\' bit \'number of trades\' - check current cryptocurrency trades; \n\n checker: \'checker name\' - \'cryptocurrency\' more\\less \'number\' \'currency\' bin - check current cryptocurrency rate;\n\n delete: \'checker name\' - delete checker;\n '
217 send_message(chat_id, comands)
218 elif re.match(r'\d+\.*\d*\s+\w+\s+\w+\s+\w+\s+\w+', message) is not None:
219 coeff, coin, _, another_coin, market = message.split()
220 coeff = float(coeff)
221 send_message(chat_id, get_prices(coeff, coin, another_coin, market))
222
223 elif re.match(r'checker:\s*\w+\s*-\s*\w+\s*\w+\s*\d+\.*\d*\s*\w+\s*\w+', message) is not None:
224 _, params = message.split(':')
225 name, _, coin, sign, value, another_coin, market = params.split()
226 if name in schedulers:
227 send_message(chat_id, 'choose new checker name please')
228 time.sleep(2)
229 continue
230 # return jsonify(r)
231 schedulers[name] = BackgroundScheduler()
232 schedulers[name].add_job(lambda: checker(chat_id, coin, sign, value, another_coin, market), trigger="interval", seconds=10)
233 schedulers[name].start()
234 send_message(chat_id, f'Ok, i create checker: {name}')
235 checker(chat_id, coin, sign, value, another_coin, market)
236 elif re.match(r'delete:\s*\w+', message) is not None:
237 _, name = message.split(':')
238 name = "".join(name.split())
239 if name in schedulers:
240 schedulers[name].shutdown()
241 del schedulers[name]
242 send_message(chat_id, f'Ok, i delete checker: {name}')
243 elif name == "ALL":
244 for key, value in schedulers.items():
245 value.shutdown()
246 schedulers.clear()
247 send_message(chat_id, f'Ok, i delete all checkers')
248 else:
249 send_message(chat_id, 'What is dead is never die')
250 elif re.match(r'trades\s*\w+\s*\w+\s*\w+\s*\w+', message) is not None:
251 _, coin, another_coin, market, number = message.split()
252 send_message(chat_id, get_trades(coin, another_coin, market, number))
253 else:
254 send_message(chat_id, 'hz')
255 # write_json(r)
256 # return jsonify(r)
257 time.sleep(2)
258
259
260if __name__ == '__main__':
261 # app.run()
262 index()