sopel/modules/currency.py

52 lines
1.5 KiB
Python
Raw Normal View History

2017-11-22 19:26:40 -05:00
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
from module import commands, example
import wolfram
import requests
@commands('cur', 'currency', 'exchange')
@example('.cur 20 EUR in USD')
def exchange(bot, trigger):
"""Show the exchange rate between two currencies"""
if not trigger.group(2):
bot.say('You must provide a query.')
return
if not bot.config.wolfram.app_id:
bot.say('Wolfram|Alpha API app ID not configured.')
return
lines = wolfram.wa_query(bot.config.wolfram.app_id, trigger.group(2), bot.config.wolfram.units)
bot.say(lines)
@commands('btc', 'bitcoin')
@example('.btc 20 EUR')
def bitcoin(bot, trigger):
args = trigger.args[1].split(' ') # because trigger.group() is stupid
if len(args) == 3: # two arguments were supplied
amount = args[1]
to = args[2]
if not amount.replace('.','').isdigit():
bot.say("Stop being dumb.")
return
elif len(args) == 2: # one argument was supplied
if args[1].replace('.','').isdigit(): # argument is the amount
amount = args[1]
to = 'USD'
else:
to = args[1]
amount = 1
else: # no arguments were supplied
amount = 1
to = 'USD'
to = to.upper()
res = requests.get("https://api.coindesk.com/v1/bpi/currentprice/{}.json".format(to), verify=True)
if res.text[:5] == "Sorry":
bot.say(res.text)
return
rate = res.json()['bpi'][to]['rate_float']
calc = float(amount) * rate
bot.say('\x0310' + str(amount) + ' BTC\x03 = \x0312' + str(calc) + ' ' + to + ' (' + res.json()['bpi'][to]['description'] + ')')