m4pl1mp/plugins/crypto_plugin.py
2022-02-01 22:44:42 -06:00

112 lines
6.5 KiB
Python

# -*- coding: utf-8 -*-
from irc3.plugins.command import command
import irc3
import aiohttp
import asyncio
import async_timeout
headers = { 'authorization': 'Apikey 94e50805f19646893ee16424918998caad5ec6accff539a23ffee8e546eda4e3' }
###########################################################################################
###########################################################################################
@irc3.plugin
class Plugin:
#######################################################################################
#######################################################################################
def __init__(self, bot):
self.bot = bot
#######################################################################################
#######################################################################################
@command(permission='view')
def cc(self, mask, target, args):
"""Show Crypto Value
%%cc <coin>
"""
###################################################################################
###################################################################################
coin = args['<coin>'].upper()
async def fetch(session, url):
async with async_timeout.timeout(10):
async with session.get(url) as response:
return await response.json()
###################################################################################
###################################################################################
async def grab_url(url):
async with aiohttp.ClientSession(headers=headers) as session:
json_response = await fetch(session, url)
return json_response
###################################################################################
###################################################################################
def parse_coin(response):
try:
task_result, _ = response.result()
task1, task2, task3 = task_result
rlist = sorted([task1.result(), task2.result(), task3.result()], key=lambda item: len(item.keys()))
if rlist[1].get("USD"):
price = rlist[1].get("USD")
price_multi = rlist[2].get("DISPLAY")[coin].get("USD", {})
daily_avg = rlist[0].get("USD")
elif rlist[2].get("USD"):
price_multi = rlist[1].get("DISPLAY")[coin].get("USD", {})
price = rlist[2].get("USD")
daily_avg = rlist[0].get("USD")
data_dict = {}
for k, v in price_multi.items():
if isinstance(v, str):
v = v.replace("$","").replace(" ","").replace(",","")
data_dict[k] = v
price_multi = data_dict
X = float(daily_avg) # AVERAGE OF THE DAY
P = float(price_multi.get('PRICE')) # PRICE CURRENTLY
H = float(price_multi.get('HIGHDAY')) # HIGH OF THE DAY
L = float(price_multi.get('LOWDAY')) # LOW OF THE DAY
A = float(price) # AGGREGATED EXCHANGE
Y = float(price_multi.get('CHANGE24HOUR')) # PRICE PERCENT DIFFERENTIAL 24 HOURS AGO
C = float(price_multi.get('CHANGEPCT24HOUR'))
if C <= 0:
C = "\x0304{}\x0F".format(C)
else:
C = "\x0303{}\x0F".format(C)
if Y <= 0:
Y = "\x0304{}\x0F".format(Y)
else:
Y = "\x0303{}\x0F".format(Y)
symbol = price_multi.get('FROMSYMBOL')
msg = "\x02\x0302[ {coin:}/{symbol:} ]\x0F @\x0303${p:,}\x0F ::: H\x0303${h:,}\x0F L\x0303${l:,}\x0F ::: Y${y:} @ %{c:} ::: X\x0303${x:,}\x0F A\x0303${a:,}\x0F".format(coin=coin, symbol=symbol, p=P, h=H, l=L, y=Y,c=C, x=X, a=A)
msg = self.bot.emo(msg)
self.bot.privmsg(target, msg)
except Exception as e:
msg = self.bot.emo('their api is glitching: check back later')
self.bot.privmsg(target, msg)
###################################################################################
###################################################################################
def process_lookups(response):
try:
html = response.result()
except Exception as e:
msg = self.bot.emo('site error: {}'.format(e.message))
self.bot.privmsg(target, msg)
return
coin_result = html.get("Data",{}).get(coin, None)
if not coin_result:
msg = self.bot.emo('Invalid coin - see https://min-api.cryptocompare.com/data/all/coinlist data keys')
self.bot.privmsg(target, msg)
return
day_avg_url = "https://min-api.cryptocompare.com/data/dayAvg?fsym={}&tsym=USD&api_key=94e50805f19646893ee16424918998caad5ec6accff539a23ffee8e546eda4e3".format(coin)
price_multi_url = "https://min-api.cryptocompare.com/data/pricemultifull?fsyms={}&tsyms=USD&api_key=94e50805f19646893ee16424918998caad5ec6accff539a23ffee8e546eda4e3".format(coin)
price_url = "https://min-api.cryptocompare.com/data/price?fsym={}&tsyms=USD&api_key=94e50805f19646893ee16424918998caad5ec6accff539a23ffee8e546eda4e3".format(coin)
tasks = [asyncio.ensure_future(grab_url(day_avg_url)),
asyncio.ensure_future(grab_url(price_multi_url)),
asyncio.ensure_future(grab_url(price_url))]
task = self.bot.create_task(asyncio.wait(tasks))
task.add_done_callback(parse_coin)
###################################################################################
###################################################################################
url = "https://min-api.cryptocompare.com/data/all/coinlist"
asyncio.ensure_future(grab_url(url), loop=self.bot.loop).add_done_callback(process_lookups)
#######################################################################################
#######################################################################################
###########################################################################################
###########################################################################################