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