· 5 years ago · Jul 25, 2020, 02:44 PM
1from redbot.core import checks, commands
2import asyncio
3import aiohttp
4import discord
5
6class Finance(commands.Cog):
7 """Get info about stocks/currencies/businesses"""
8 finnhub_base_url='https://finnhub.io/api/v1/'
9 def __init__(self, bot):
10 self.bot = bot
11 self.session = aiohttp.ClientSession()
12 @commands.command()
13 async def stock(self, ctx, *, stock_ticker:str):
14 """Get the price of a US stock."""
15 api_key = await self.bot.get_shared_api_tokens("finnhub")
16 if api_key.get("api_key") is None:
17 return await ctx.send("The Finnhub API key has not been set. Please set it with `s!set api finnhub api_key <your api key>`")
18 else:
19 stock_ticker.upper()
20 async with aiohttp.ClientSession() as session:
21 async with session.get(f'{self.finnhub_base_url}quote?symbol={stock_ticker}',
22 headers={"Accept": "application/json"}) as resp:
23 response = await resp.json()
24 if response == '{}':
25 await ctx.send('An unexpected error occured. Are you sure that is a valid, *US* stock ticker?')
26 percentage_change_a = response['c'] / response['o']
27 percentage_change_b = percentage_change_a - 1
28 percentage_change_final = percentage_change_b * 100
29 embedColor = await ctx.embed_colour()
30 percentage_gain = True
31 if percentage_change_final < 0:
32 percentage_gain = False
33 embed = discord.Embed(
34 title = f"Stock Data for {stock_ticker}",
35 color = embedColor,
36 )
37 if percentage_gain:
38 embed.add_field(name='Prices', value=f"Open: ${response['o']}\nHigh: ${response['h']}\nLow: ${response['l']}\nCurrent: ${response['c']}\nPercentage Gain: <:up_arrow:736390019136356442> %{percentage_change_final}")
39 if not percentage_gain:
40 embed.add_field(name='Prices', value=f"Open: ${response['o']}\nHigh: ${response['h']}\nLow: ${response['l']}\nCurrent: ${response['c']}\nPercentage Loss: <:down_arrow:736390163839844422> %{percentage_change_final}")
41 embed.set_footer(text=f"Requested by {ctx.author.name} | Powered by finnhub.io")
42 await ctx.send(embed=embed)