nxy/bot/coins.py

82 lines
2.8 KiB
Python

# -*- coding: utf-8 -*-
import requests
from docopt import Dict
from irc3.plugins.command import command
from irc3.utils import IrcString
from . import Plugin
def _currency(name, prefix=None, suffix=None):
def tostr(value):
return '{prefix}{value:,.2f}{suffix}'.format(
prefix=prefix or '',
suffix=suffix or ('' if (prefix or suffix) else (' ' + name)),
value=value)
return tostr
class Coins(Plugin):
API_URL = 'https://api.cryptowat.ch/markets/{market}/{crypto}{currency}/summary'
CURRENCIES = {
'usd': _currency('usd', prefix='$'),
'eur': _currency('eur', suffix=''),
'eth': _currency('eth', suffix='Ξ'),
'btc': _currency('btc', suffix='฿'),
'xmr': _currency('xmr'),
}
@command
def btc(self, mask: IrcString, target: IrcString, args: Dict):
"""Gets the Bitcoin values from cryptowatch.
%%btc [<currency>]
"""
return self.cryptowat_summary('btc', 'coinbase', args)
@command
def eth(self, mask: IrcString, target: IrcString, args: Dict):
"""Gets the Ethereum values from cryptowatch.
%%eth [<currency>]
"""
return self.cryptowat_summary('eth', 'coinbase', args)
@command
def xmr(self, mask: IrcString, target: IrcString, args: Dict):
"""Gets the Monero values from cryptowatch.
%%xmr [<currency>]
"""
return self.cryptowat_summary('xmr', 'bitfinex', args)
def cryptowat_summary(self, crypto: str, market: str, args: Dict):
currency = args.get('<currency>', 'eur').lower()
if currency not in self.CURRENCIES or crypto == currency:
return '\x02[{}]\x02 Can\'t convert or invalid currency: {}'.format(crypto.upper(), currency)
def get_data(cur):
return requests.get(self.API_URL.format(crypto=crypto, market=market, currency=cur))
data = get_data(currency)
if not data and currency != 'usd':
data = get_data('usd')
if not data:
return '\x02[{}]\x02 No data received for currency {}'.format(crypto, currency)
to_currency = self.CURRENCIES[currency]
result = data.json()['result']
return '\x02[{crypto}]\x02 ' \
'Current: \x02\x0307{last}\x0F - ' \
'High: \x02\x0303{high}\x0F - ' \
'Low: \x02\x0304{low}\x0F - ' \
'Change: \x02\x0307{change:,.2f}%\x0F - ' \
'Volume: \x02\x0307{volume}\x0F' \
.format(crypto=crypto.upper(),
last=to_currency(result['price']['last']),
high=to_currency(result['price']['high']),
low=to_currency(result['price']['low']),
change=result['price']['change']['percentage'] * 100,
volume=result['volume'])