Last active
April 6, 2018 13:57
-
-
Save gaphex/e5de9ef6d723667d9e0e629ad921f1bf to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| import json | |
| import logging | |
| import requests | |
| import telegram | |
| import coinmarketcap | |
| from telegram.ext import Updater, CommandHandler, MessageHandler, Filters | |
| #from config import TOKEN, LOG_FILE | |
| TOKEN = "" | |
| LOG_FILE = "./log.txt" | |
| # Enable logging | |
| formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') | |
| logger = logging.getLogger(__name__) | |
| logger.setLevel(logging.DEBUG) | |
| # Logging to file | |
| fh = logging.FileHandler(LOG_FILE) | |
| fh.setLevel(logging.DEBUG) | |
| fh.setFormatter(formatter) | |
| # Logging to console | |
| ch = logging.StreamHandler() | |
| ch.setLevel(logging.DEBUG) | |
| ch.setFormatter(formatter) | |
| logger.addHandler(fh) | |
| logger.addHandler(ch) | |
| market = coinmarketcap.Market() | |
| symbol_to_id = {t["symbol"].lower(): t['id'] for t in market.ticker(limit=2048)} | |
| keys = ['symbol', 'name', | |
| 'price_btc', 'price_usd', | |
| '24h_volume_usd', 'market_cap_usd', | |
| 'percent_change_1h', 'percent_change_24h', 'percent_change_7d'] | |
| class Bot: | |
| def __init__(self): | |
| self.updater = Updater(TOKEN) | |
| self.dsp = self.updater.dispatcher | |
| # register handler functions which define how the bot reacts to events | |
| self.dsp.add_handler(CommandHandler("start", get_help)) | |
| self.dsp.add_handler(CommandHandler("help", get_help)) | |
| self.dsp.add_handler(CommandHandler("quote", get_quote)) | |
| self.dsp.add_handler(MessageHandler([Filters.command], unknown)) | |
| self.dsp.add_error_handler(error) | |
| logger.info('Im alive!') | |
| def power_on(self): | |
| # start the Bot | |
| self.updater.start_polling() | |
| self.updater.idle() | |
| # define command handlers. These usually take the two arguments: bot and | |
| # update. Error handlers also receive the raised TelegramError object in error. | |
| def get_data_for_symbol(symbol, convert="USD"): | |
| raw = market.ticker(symbol_to_id[symbol], convert=convert)[0] | |
| r = '' | |
| for k in keys: | |
| r += k + ': ' + raw[k] + '\n' | |
| return r | |
| def unknown(bot, update): | |
| logger.info('recieved message: {} from {}'.format(update.message.text, | |
| update.message.from_user.username)) | |
| maybe_ticker = update.message.text | |
| if len(maybe_ticker) > 1 and maybe_ticker[1:] in symbol_to_id: | |
| out_msg = '`{}`'.format(get_data_for_symbol(maybe_ticker[1:])) | |
| bot.sendMessage(chat_id=update.message.chat_id, | |
| text=out_msg, | |
| parse_mode=telegram.ParseMode.MARKDOWN) | |
| def error(bot, update, error): | |
| # all uncaught telegram-related exceptions will be rerouted here | |
| logger.error('Update "%s" caused error "%s"' % (update, error)) | |
| def get_help(bot, update): | |
| logger.info('get_help recieved message: {}'.format(update.message.text)) | |
| help_msg = ('Greetings, {} {}! Name is {}, at your service.\n' | |
| 'My purpose is to provide up-to-date crypto prices from ' | |
| 'coinmarketcap.com\n' | |
| 'I support the following commands: \n' | |
| '/start - begins our chat and prints this message\n' | |
| '/help - prints this message\n' | |
| '/symbol - prints information for symbol, if available').format( | |
| update.message.from_user.first_name, update.message.from_user.last_name, bot.name) | |
| bot.sendMessage(update.message.chat_id, text=help_msg) | |
| def get_quote(bot, update): | |
| def parse_quote(): | |
| response = requests.get("http://api.forismatic.com/api/1.0/?method=getQuote&lang=ru&format=json") | |
| responseJson = json.loads(response.text) | |
| author = responseJson['quoteAuthor'] | |
| quote = responseJson['quoteText'] | |
| if author == "": | |
| return parse_quote() | |
| else: | |
| return author, quote | |
| author, quote = parse_quote() | |
| logger.info('sent quote: {} by {} for {}'.format(quote, author, | |
| update.message.from_user.username)) | |
| bot.send_message(chat_id=update.message.chat_id, | |
| text="*{}*\n\n{}_{}_".format(quote, (100-len(author))*" ", author), | |
| parse_mode=telegram.ParseMode.MARKDOWN) | |
| my_bot = Bot() | |
| my_bot.power_on() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment