· 7 years ago · Dec 09, 2018, 07:48 PM
1import os
2import json
3import requests
4import binance
5import re
6import lxml
7from binance.client import Client
8from bs4 import BeautifulSoup, Tag
9from coinmarketcap import CoinMarketCap
10from flask import Flask, request, jsonify
11
12app = Flask(__name__)
13URL = 'https://api.telegram.org/bot788997844:AAHhO_dpfsBncq6uTMZiUva9GHOOgySKs98/'
14api_key = 'vmPUZE6mv9SD5VNHk4HlWFsOr6aKE2zvsw0MuIgwCIPy6utIco14y7Ju91duEh8A' #https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md
15secret_key = 'NhqPtmdSJYdKjVHjA7PZj4Mge3R5YNiP1e3UZjInClVN65XAbvqqM6A7H5fATj0j' #https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md
16
17def write_json(data, filename='answer.json'):
18 with open(filename, 'w') as f:
19 json.dump(data, f, indent=4, ensure_ascii=False)
20
21
22def send_message(chat_id, text='Why did you bother me?'):
23 url = URL + 'sendMessage'
24 answer = {'chat_id': chat_id, 'text': text}
25 r = requests.post(url, json=answer)
26 return r.json()
27
28
29def get_price():
30 market = CoinMarketCap()
31 coins = market.coin_ticker_list(start=1, limit=10, convert="EUR", disable_cache=True)
32 price = None
33 for key, value in coins['data'].items():
34 if value['name'] == 'Bitcoin':
35 price = value['quotes']['USD']['price']
36 break
37 return price
38
39
40def take_tut_by():
41 url = 'https://news.tut.by/tag/2522-kriptovalyuta.html?crnd=45707'
42 r = requests.get(url)
43 soup = BeautifulSoup(r.text, "lxml")
44 news = soup.findAll('div', {'class': 'news-entry big annoticed time ni'})
45 answer = []
46 for i in news:
47 href = i.find('a').get('href')
48 title = re.compile('<span.*?>(.*?)</span>').findall(str(i.find('span', {'class': 'entry-head _title'})))[0]
49 answer.append((title, href))
50 return answer
51
52def take_bits():
53 url = 'https://bits.media/news/'
54 r = requests.get(url)
55 soup = BeautifulSoup(r.text, "lxml")
56 news = soup.findAll('a', {'class': 'news-name'})
57 answer = []
58 for i in news:
59 href = ''.join(('https://bits.media',i.get('href')))
60 title = re.compile('<a.*?>(.*?)</a>').findall(str(i))[0]
61 answer.append((title, href))
62 return answer
63
64
65@app.route('/', methods=['POST', 'GET'])
66def index():
67 if request.method == 'POST':
68 r = request.get_json()
69 chat_id = r['message']['chat']['id']
70 message = r['message']['text']
71
72 if message == 'news':
73 all_news = take_tut_by()[:2]
74 all_news.extend(take_bits()[:2])
75 send_message(chat_id, '\n\n'.join(':\n'.join(i) for i in all_news))
76 if re.match(r'\d+\.*\d*\s+\w+\s+\w+\s+\w+\s+\w+', message) is not None:
77 coeff, coin, _, another_coin, market = message.split()
78 coeff = float(coeff)
79 coin = coin.upper()
80 another_coin = another_coin.upper()
81 if another_coin in ['EUR', 'BYN', 'RUB', 'USD']:
82 another_coin = another_coin.upper()
83 url = f'http://free.currencyconverterapi.com/api/v5/convert?q=USD_{another_coin}&compact=y'
84 temp = requests.get(url)
85 soup = BeautifulSoup(temp.text, "lxml")
86 coeff *= float(re.compile('"val":(.*?)\}').findall(str(soup))[0])
87 if market == 'bin':
88 client = Client(api_key, secret_key)
89 all_tickers = client.get_all_tickers()
90 for i in all_tickers:
91 if i['symbol'] == ''.join((coin, 'USDT')):
92 rate = float(i['price'])
93 send_message(chat_id, str(coeff * rate))
94 return jsonify(r)
95 send_message(chat_id, 'sorry i don\'t understand')
96 else:
97 if market == 'bin':
98 client = Client(api_key, secret_key)
99 all_tickers = client.get_all_tickers()
100 for i in all_tickers:
101 if i['symbol'] == ''.join((coin, 'USDT')):
102 rate1 = float(i['price'])
103 if i['symbol'] == ''.join((another_coin, 'USDT')):
104 rate2 = float(i['price'])
105 rate = rate1 / rate2
106 send_message(chat_id, str(coeff * rate))
107 return jsonify(r)
108 else:
109 send_message(chat_id, 'hz')
110 # write_json(r)
111 return jsonify(r)
112
113 return '<h1>Hi i\'m son of Bot Father<h1>'
114
115
116if __name__ == '__main__':
117 app.run()
118
119
120# https://api.telegram.org/bot788997844:AAHhO_dpfsBncq6uTMZiUva9GHOOgySKs98/setWebhook?url=https://250b480f.ngrok.io