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