Created
February 17, 2018 15:54
-
-
Save Bobronium/48a15558bedbe2a670c06cdd43e0d8f6 to your computer and use it in GitHub Desktop.
Currency Bot
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
print("Initializing variables") | |
import requests | |
from settings import token | |
import time | |
tlgrm_url = "https://api.telegram.org/bot{}/".format(token) | |
cryptonator_url = "https://api.cryptonator.com/api/ticker/" | |
greeting = 'Привет, я умею показывать текущий курс криптовалют. Отзываюсь на команды /btc и /eth' | |
offset = 0 | |
def get_updates(offset=0, timeout=30): | |
params = {'offset': offset, 'timeout': timeout} | |
result = requests.get(tlgrm_url + "getUpdates", params=params) | |
for update in result.json()['result']: | |
offset = update['update_id'] | |
return update['result'] | |
update = get_updates(offset=0, timeout=30) | |
def send_message(chat, text): | |
print("Sending message") | |
params = {'chat_id': chat, 'text': text} | |
response = requests.post(tlgrm_url + 'sendMessage', data=params) | |
return response | |
def get_crypto_price(currency_pair): | |
print("Getting crypto price") | |
raw_data = requests.get(url=cryptonator_url+currency_pair) | |
data = raw_data.json() | |
price = data["ticker"]["price"] | |
return price | |
def process_requests(): | |
for message in update: | |
request = message['message']['text'] | |
chat_id = message['message']['chat']['id'] | |
if request == "/btc": | |
text = "Bitcoin стоит ${0}".format(get_crypto_price("btc-usd")) | |
send_message(chat_id, text) | |
print("Sent Bitcoin rate") | |
elif request == "/eth": | |
text = "Etherium стоит ${0}".format(get_crypto_price("eth-usd")) | |
send_message(chat_id, text) | |
print("Sent Etherium rate") | |
elif request == "/start": | |
send_message(chat_id, greeting) | |
else: | |
print(request) | |
send_message(chat_id, 'Отправь /btc or /eth') | |
process_requests() | |
while True: | |
print("Looping get_updates") | |
try: | |
get_updates(offset) | |
process_requests() | |
time.sleep(1) | |
except KeyboardInterrupt: # порождается, если бота остановил пользователь | |
print('Interrupted by the user') | |
break |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment