· 7 years ago · Dec 10, 2018, 09:50 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
14from threading import Thread
15
16app = Flask(__name__)
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
49def send_message(chat_id, text='Why did you bother me?'):
50 url = URL + 'sendMessage'
51 answer = {'chat_id': chat_id, 'text': text}
52 r = requests.post(url, json=answer)
53 return r.json()
54
55def get_ticker_bitfinex(coin):
56 url = f'https://api.bitfinex.com/v1/pubticker/{coin}usd'
57 response = requests.request("GET", url)
58 return float(re.compile('"last_price":"(.*?)"').findall(response.text)[0])
59
60
61def get_trades_bitfinex(coin, another_coin):
62 url = f'https://api.bitfinex.com/v1/trades/{coin}{another_coin}'
63 response = requests.request("GET", url)
64 answer = list(zip(re.compile('"price":"(.*?)"').findall(response.text),
65 re.compile('"amount":"(.*?)"').findall(response.text),
66 re.compile('"type":"(.*?)"').findall(response.text)))
67 value = 'buy'
68 if not answer:
69 url = f'https://api.bitfinex.com/v1/trades/{another_coin}{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 = 'sell'
75 return answer, value
76
77def take_tut_by():
78 url = 'https://news.tut.by/tag/2522-kriptovalyuta.html?crnd=45707'
79 r = requests.get(url)
80 soup = BeautifulSoup(r.text, "lxml")
81 news = soup.findAll('div', {'class': 'news-entry big annoticed time ni'})
82 answer = []
83 for i in news:
84 href = i.find('a').get('href')
85 title = re.compile('<span.*?>(.*?)</span>').findall(str(i.find('span', {'class': 'entry-head _title'})))[0]
86 answer.append((title, href))
87 return answer
88
89
90def take_bits():
91 url = 'https://bits.media/news/'
92 r = requests.get(url)
93 soup = BeautifulSoup(r.text, "lxml")
94 news = soup.findAll('a', {'class': 'news-name'})
95 answer = []
96 for i in news:
97 href = ''.join(('https://bits.media',i.get('href')))
98 title = re.compile('<a.*?>(.*?)</a>').findall(str(i))[0]
99 answer.append((title, href))
100 return answer
101
102
103def checker(chat_id, coin, sign, value, another_coin, market, name):
104 rate = get_prices(1, coin, another_coin, market)
105 if sign == 'more':
106 if rate > float(value):
107 send_message(chat_id, f'{coin} = {rate} {another_coin} (you want it and i delete checker)')
108 schedulers[name].shutdown()
109 del schedulers[name]
110 if sign == 'less':
111 if rate < float(value):
112 send_message(chat_id, f'{coin} = {rate} {another_coin} (you want it and i delete checker)')
113 schedulers[name].shutdown()
114 del schedulers[name]
115
116
117def get_trades(coin, another_coin, market, number):
118 answer = []
119 if market == 'bin':
120 if coin == 'usd':
121 coin = 'TUSD'
122 if another_coin == 'usd':
123 another_coin = 'USDT'
124 client = Client(api_key, secret_key)
125 trades = client.get_recent_trades(symbol=''.join((coin.upper(), another_coin.upper())), limit=int(number))
126 for i in trades:
127 if coin == 'TUSD':
128 coin = 'usd'
129 if another_coin == 'USDT':
130 another_coin = 'usd'
131 answer.append(f'{i["qty"]} {coin} were bought for the price of {i["price"]} {another_coin} per one')
132 elif market == 'bit':
133 trades, value = get_trades_bitfinex(coin.lower(), another_coin.lower())
134 new_trades = []
135 if value == 'buy':
136 for i in trades:
137 if i[2] == 'buy':
138 new_trades.append(i)
139 else:
140 for i in trades:
141 if i[2] == 'sell':
142 new_trades.append(i)
143 for i in new_trades[:min(int(number), len(new_trades) - 1)]:
144 if value == 'buy':
145 answer.append(f'{i[1]} {coin} were bought for the price of {i[0]} {another_coin} per one')
146 else:
147 answer.append(f'{1/float(i[1])} {coin} were bought for the price of {1/float(i[0])} {another_coin} per one')
148 return '\n'.join(answer)
149
150
151def get_prices(coeff, coin, another_coin, market):
152 if another_coin.upper() in ['EUR', 'BYN', 'RUB', 'USD']:
153 url = f'http://free.currencyconverterapi.com/api/v5/convert?q=USD_{another_coin}&compact=y'
154 temp = requests.get(url)
155 soup = BeautifulSoup(temp.text, "lxml")
156 coeff *= float(re.compile('"val":(.*?)\}').findall(str(soup))[0])
157 if market == 'bin':
158 client = Client(api_key, secret_key)
159 all_tickers = client.get_all_tickers()
160 for i in all_tickers:
161 if i['symbol'] == ''.join((coin.upper(), 'USDT')):
162 rate = float(i['price'])
163 return coeff * rate
164 send_message(chat_id, 'sorry i don\'t understand')
165 elif market == 'bit':
166 return get_ticker_bitfinex(coin.lower()) * coeff
167 else:
168 if market == 'bin':
169 client = Client(api_key, secret_key)
170 all_tickers = client.get_all_tickers()
171 good = 0
172 for i in all_tickers:
173 if i['symbol'] == ''.join((coin.upper(), 'USDT')):
174 rate1 = float(i['price'])
175 good += 1
176 if i['symbol'] == ''.join((another_coin.upper(), 'USDT')):
177 rate2 = float(i['price'])
178 good += 1
179 if good == 2:
180 rate = rate1 / rate2
181 return coeff * rate
182 else:
183 send_message(chat_id, 'sorry i don\'t understand')
184 elif market == 'bit':
185 rate = get_ticker_bitfinex(coin.lower()) / get_ticker_bitfinex(another_coin.lower())
186 return coeff * rate
187
188def get_updates():
189 url = URL + 'getUpdates'
190 r = requests.get(url)
191 return r.json()
192
193
194def get_message():
195 data = get_updates()
196 last_object = data['result'][-1]
197 global last_update_id
198 if last_update_id != last_object['update_id']:
199 chat_id = last_object['message']['chat']['id']
200 message_text = last_object["message"]['text']
201 last_update_id = last_object['update_id']
202 return {'message': message_text, 'chat_id': chat_id}
203 return None
204
205
206def index():
207 while True:
208 try:
209 answer = get_message()
210 if answer != None:
211 chat_id = answer['chat_id']
212 message = answer['message']
213
214 if message == 'news':
215 all_news = take_tut_by()[:3]
216 all_news.extend(take_bits()[:3])
217 send_message(chat_id, '\n\n'.join(':\n'.join(i) for i in all_news))
218 elif message == 'help':
219 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 '
220 send_message(chat_id, comands)
221 elif re.match(r'\d+\.*\d*\s+\w+\s+\w+\s+\w+\s+\w+', message) is not None:
222 coeff, coin, _, another_coin, market = message.split()
223 coeff = float(coeff)
224 send_message(chat_id, get_prices(coeff, coin, another_coin, market))
225
226 elif re.match(r'checker:\s*\w+\s*-\s*\w+\s*\w+\s*\d+\.*\d*\s*\w+\s*\w+', message) is not None:
227 _, params = message.split(':')
228 name, _, coin, sign, value, another_coin, market = params.split()
229 if name in schedulers:
230 send_message(chat_id, 'choose new checker name please')
231 time.sleep(2)
232 continue
233 # return jsonify(r)
234 schedulers[name] = BackgroundScheduler()
235 schedulers[name].add_job(lambda: checker(chat_id, coin, sign, value, another_coin, market, name), trigger="interval", seconds=100)
236 schedulers[name].start()
237 send_message(chat_id, f'Ok, i create checker: {name}')
238 checker(chat_id, coin, sign, value, another_coin, market, name)
239 elif re.match(r'delete:\s*\w+', message) is not None:
240 _, name = message.split(':')
241 name = "".join(name.split())
242 if name in schedulers:
243 schedulers[name].shutdown()
244 del schedulers[name]
245 send_message(chat_id, f'Ok, i delete checker: {name}')
246 elif name == "ALL":
247 for key, value in schedulers.items():
248 value.shutdown()
249 schedulers.clear()
250 send_message(chat_id, f'Ok, i delete all checkers')
251 else:
252 send_message(chat_id, 'What is dead is never die')
253 elif re.match(r'trades\s*\w+\s*\w+\s*\w+\s*\w+', message) is not None:
254 _, coin, another_coin, market, number = message.split()
255 send_message(chat_id, get_trades(coin, another_coin, market, number))
256 else:
257 send_message(chat_id, 'hz')
258 time.sleep(2)
259 except:
260 continue
261
262
263if __name__ == '__main__':
264 Thread(target = index).start()
265 Thread(target = app.run).start()