Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import os
- import json
- import requests
- import binance
- import re
- import lxml
- import time
- import time
- import atexit
- from apscheduler.schedulers.background import BackgroundScheduler
- from binance.client import Client
- from bs4 import BeautifulSoup, Tag
- from flask import Flask, request, jsonify
- from flask_sslify import SSLify
- app = Flask(__name__)
- sslify = SSLify(app)
- URL = 'https://api.telegram.org/bot788997844:AAHhO_dpfsBncq6uTMZiUva9GHOOgySKs98/'
- api_key = 'vmPUZE6mv9SD5VNHk4HlWFsOr6aKE2zvsw0MuIgwCIPy6utIco14y7Ju91duEh8A' #https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md
- secret_key = 'NhqPtmdSJYdKjVHjA7PZj4Mge3R5YNiP1e3UZjInClVN65XAbvqqM6A7H5fATj0j' #https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md
- schedulers = {}
- def write_json(data, filename='answer.json'):
- with open(filename, 'w') as f:
- json.dump(data, f, indent=4, ensure_ascii=False)
- def send_message(chat_id, text='Why did you bother me?'):
- url = URL + 'sendMessage'
- answer = {'chat_id': chat_id, 'text': text}
- r = requests.post(url, json=answer)
- return r.json()
- def get_ticker_bitfinex(coin):
- url = f'https://api.bitfinex.com/v1/pubticker/{coin}usd'
- response = requests.request("GET", url)
- return float(re.compile('"last_price":"(.*?)"').findall(response.text)[0])
- def get_trades_bitfinex(coin, another_coin):
- url = f'https://api.bitfinex.com/v1/trades/{coin}{another_coin}'
- response = requests.request("GET", url)
- answer = list(zip(re.compile('"price":"(.*?)"').findall(response.text),
- re.compile('"amount":"(.*?)"').findall(response.text),
- re.compile('"type":"(.*?)"').findall(response.text)))
- value = 'buy'
- if not answer:
- url = f'https://api.bitfinex.com/v1/trades/{another_coin}{coin}'
- response = requests.request("GET", url)
- answer = list(zip(re.compile('"price":"(.*?)"').findall(response.text),
- re.compile('"amount":"(.*?)"').findall(response.text),
- re.compile('"type":"(.*?)"').findall(response.text)))
- value = 'sell'
- return answer, value
- def take_tut_by():
- url = 'https://news.tut.by/tag/2522-kriptovalyuta.html?crnd=45707'
- r = requests.get(url)
- soup = BeautifulSoup(r.text, "lxml")
- news = soup.findAll('div', {'class': 'news-entry big annoticed time ni'})
- answer = []
- for i in news:
- href = i.find('a').get('href')
- title = re.compile('<span.*?>(.*?)</span>').findall(str(i.find('span', {'class': 'entry-head _title'})))[0]
- answer.append((title, href))
- return answer
- def take_bits():
- url = 'https://bits.media/news/'
- r = requests.get(url)
- soup = BeautifulSoup(r.text, "lxml")
- news = soup.findAll('a', {'class': 'news-name'})
- answer = []
- for i in news:
- href = ''.join(('https://bits.media',i.get('href')))
- title = re.compile('<a.*?>(.*?)</a>').findall(str(i))[0]
- answer.append((title, href))
- return answer
- def checker(chat_id, coin, sign, value, another_coin, market):
- rate = get_prices(1, coin, another_coin, market)
- send_message(chat_id, str(rate))
- def get_trades(coin, another_coin, market, number):
- answer = []
- if market == 'bin':
- if coin == 'usd':
- coin = 'TUSD'
- if another_coin == 'usd':
- another_coin = 'USDT'
- client = Client(api_key, secret_key)
- trades = client.get_recent_trades(symbol=''.join((coin.upper(), another_coin.upper())), limit=int(number))
- for i in trades:
- if coin == 'TUSD':
- coin = 'usd'
- if another_coin == 'USDT':
- another_coin = 'usd'
- answer.append(f'{i["qty"]} {coin} were bought for the price of {i["price"]} {another_coin} per one')
- elif market == 'bit':
- trades, value = get_trades_bitfinex(coin.lower(), another_coin.lower())
- new_trades = []
- if value == 'buy':
- for i in trades:
- if i[2] == 'buy':
- new_trades.append(i)
- else:
- for i in trades:
- if i[2] == 'sell':
- new_trades.append(i)
- for i in new_trades[:min(int(number), len(new_trades) - 1)]:
- if value == 'buy':
- answer.append(f'{i[1]} {coin} were bought for the price of {i[0]} {another_coin} per one')
- else:
- answer.append(f'{1/float(i[1])} {coin} were bought for the price of {1/float(i[0])} {another_coin} per one')
- return '\n'.join(answer)
- def get_prices(coeff, coin, another_coin, market):
- if another_coin.upper() in ['EUR', 'BYN', 'RUB', 'USD']:
- url = f'http://free.currencyconverterapi.com/api/v5/convert?q=USD_{another_coin}&compact=y'
- temp = requests.get(url)
- soup = BeautifulSoup(temp.text, "lxml")
- coeff *= float(re.compile('"val":(.*?)\}').findall(str(soup))[0])
- if market == 'bin':
- client = Client(api_key, secret_key)
- all_tickers = client.get_all_tickers()
- for i in all_tickers:
- if i['symbol'] == ''.join((coin.upper(), 'USDT')):
- rate = float(i['price'])
- return coeff * rate
- send_message(chat_id, 'sorry i don\'t understand')
- elif market == 'bit':
- return get_ticker_bitfinex(coin.lower()) * coeff
- else:
- if market == 'bin':
- client = Client(api_key, secret_key)
- all_tickers = client.get_all_tickers()
- good = 0
- for i in all_tickers:
- if i['symbol'] == ''.join((coin.upper(), 'USDT')):
- rate1 = float(i['price'])
- good += 1
- if i['symbol'] == ''.join((another_coin.upper(), 'USDT')):
- rate2 = float(i['price'])
- good += 1
- if good == 2:
- rate = rate1 / rate2
- return coeff * rate
- else:
- send_message(chat_id, 'sorry i don\'t understand')
- elif market == 'bit':
- rate = get_ticker_bitfinex(coin.lower()) / get_ticker_bitfinex(another_coin.lower())
- return coeff * rate
- # @app.route('/788997844:AAHhO_dpfsBncq6uTMZiUva9GHOOgySKs98/api/prices', methods=['POST', 'GET'])
- # def get():
- @app.route('/788997844:AAHhO_dpfsBncq6uTMZiUva9GHOOgySKs98', methods=['POST', 'GET'])
- def index():
- if request.method == 'POST':
- r = request.get_json()
- try:
- chat_id = r['message']['chat']['id']
- except:
- return jsonify(r)
- chat_id = r['message']['chat']['id']
- if float(r['message']['date']) + 100 < time.time():
- return jsonify(r)
- message = r['message']['text']
- if message == 'news':
- all_news = take_tut_by()[:2]
- all_news.extend(take_bits()[:2])
- send_message(chat_id, '\n\n'.join(':\n'.join(i) for i in all_news))
- elif re.match(r'\d+\.*\d*\s+\w+\s+\w+\s+\w+\s+\w+', message) is not None:
- coeff, coin, _, another_coin, market = message.split()
- coeff = float(coeff)
- send_message(chat_id, get_prices(coeff, coin, another_coin, market))
- elif re.match(r'checker:\s*\w+\s*-\s*\w+\s*\w+\s*\d+\.*\d*\s*\w+\s*\w+', message) is not None:
- _, params = message.split(':')
- name, _, coin, sign, value, another_coin, market = params.split()
- if name in schedulers:
- send_message(chat_id, 'choose new checker name please')
- return jsonify(r)
- schedulers[name] = BackgroundScheduler()
- schedulers[name].add_job(lambda: checker(chat_id, coin, sign, value, another_coin, market), trigger="interval", seconds=10)
- schedulers[name].start()
- send_message(chat_id, f'Ok, i create checker: {name}')
- checker(chat_id, coin, sign, value, another_coin, market)
- elif re.match(r'delete:\s*\w+', message) is not None:
- _, name = message.split(':')
- name = "".join(name.split())
- if name in schedulers:
- schedulers[name].shutdown()
- del schedulers[name]
- send_message(chat_id, f'Ok, i delete checker: {name}')
- elif name == "ALL":
- for key, value in schedulers.items():
- value.shutdown()
- schedulers.clear()
- send_message(chat_id, f'Ok, i delete all checkers')
- else:
- send_message(chat_id, 'What is dead is never die')
- elif re.match(r'trades\s*\w+\s*\w+\s*\w+\s*\w+', message) is not None:
- _, coin, another_coin, market, number = message.split()
- send_message(chat_id, get_trades(coin, another_coin, market, number))
- else:
- send_message(chat_id, 'hz')
- # write_json(r)
- return jsonify(r)
- return '<h1>Hi i\'m son of Bot Father<h1>'
- if __name__ == '__main__':
- app.run()
- # https://api.telegram.org/bot788997844:AAHhO_dpfsBncq6uTMZiUva9GHOOgySKs98/setWebhook?url=https://250b480f.ngrok.io
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement