53 lines
1.5 KiB
Python
53 lines
1.5 KiB
Python
import requests, json
|
|
from urllib.parse import urlencode
|
|
from bot import IRCLine
|
|
BOT = None
|
|
|
|
def respond(event,msg):
|
|
is_pub = event.target.startswith("#")
|
|
BOT.socket.send(IRCLine("PRIVMSG",event.target if is_pub else event.hostmask.nick,":"+(event.hostmask.nick+": " if is_pub else "")+msg))
|
|
|
|
def get_delta(fv,tv):
|
|
d = (tv-fv)
|
|
d = d/fv
|
|
return d
|
|
|
|
TOKEN=""
|
|
try:
|
|
with open(".finnhub_token") as f: TOKEN=f.read().strip()
|
|
except: print("Token not found!")
|
|
|
|
def on_get_stock(event):
|
|
if not BOT: return
|
|
if not TOKEN:
|
|
respond(event,"khuxkm is an idiot and forgot to supply an API token. I can't do anything about that!")
|
|
return
|
|
if len(event.parts)!=1:
|
|
respond(event,"You can only request 1 symbol at a time.")
|
|
return
|
|
symbol = event.parts[0].upper()
|
|
r = requests.get("https://finnhub.io/api/v1/quote?"+urlencode(dict(symbol=symbol,token=TOKEN)))
|
|
if r.status_code!=200:
|
|
respond(event,"The finnhub API returned a status code of "+str(r.status_code)+".")
|
|
return
|
|
try:
|
|
res = r.json()
|
|
except:
|
|
respond(event,r.text)
|
|
return
|
|
if "pc" not in res:
|
|
respond(event,f"No such stock ticker {symbol}!")
|
|
return
|
|
try:
|
|
previous_close, current_value = res["pc"], res["c"]
|
|
delta = "{:+0.2%}".format(get_delta(previous_close,current_value))
|
|
respond(event,f"{symbol} is currently valued at {current_value} ({delta} from previous close)")
|
|
except:
|
|
respond(event,"Error calculating delta!")
|
|
print(json.dumps(res,indent=2))
|
|
|
|
def register(bot):
|
|
global BOT
|
|
BOT=bot
|
|
bot.event_manager.on("command_getStock",on_get_stock)
|