feat: add github repo lookup command

This commit is contained in:
2021-07-29 12:58:47 -04:00
parent 5b0e8d3bee
commit a9985f4b4c
4 changed files with 60 additions and 19 deletions

View File

@@ -1,4 +1,5 @@
import os import os
from typing import List
import requests import requests
import json import json
from discord.ext import commands from discord.ext import commands
@@ -6,13 +7,12 @@ from discord.ext import commands
class Finance(commands.Cog): class Finance(commands.Cog):
"""Commands to query stock and crypto prices.""" """Commands to query stock and crypto prices."""
@commands.command(usage="[tickers]") @commands.command(usage="<tickers>")
async def stock(self, ctx, *tickers): async def stock(self, ctx, *tickers: List[str]) -> None:
""" """Get prices for the given stock tickers. Will default tickers to AAPL, GOOG, MSFT and AMZN if none provided."""
Get prices for the given stock tickers. Will default tickers to AAPL, GOOG, MSFT and AMZN if none provided.
"""
ALPHAVANTAGE_API_KEY = os.getenv('ALPHAVANTAGE_API_KEY') ALPHAVANTAGE_API_KEY = os.getenv('ALPHAVANTAGE_API_KEY')
# default tickers
if len(tickers) == 0: if len(tickers) == 0:
tickers = ["AAPL", "GOOG", "MSFT", "AMZN"] tickers = ["AAPL", "GOOG", "MSFT", "AMZN"]
@@ -22,7 +22,7 @@ class Finance(commands.Cog):
# make the call for stock prices # make the call for stock prices
for ticker in tickers: for ticker in tickers:
http_response = requests.get(f'https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol={ticker}&apikey={ALPHAVANTAGE_API_KEY}') http_response = requests.get(f"https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol={ticker}&apikey={ALPHAVANTAGE_API_KEY}")
stock_data = json.loads(http_response.text) stock_data = json.loads(http_response.text)
# check if stock exists # check if stock exists
@@ -30,7 +30,7 @@ class Finance(commands.Cog):
continue continue
# get the stock price # get the stock price
stock_price = stock_data['Global Quote']['05. price'] stock_price = stock_data["Global Quote"]["05. price"]
msg_response += f'**{ticker}**: ${round(float(stock_price), 2)}\n' msg_response += f'**{ticker}**: ${round(float(stock_price), 2)}\n'
stock_found = True stock_found = True
@@ -41,12 +41,10 @@ class Finance(commands.Cog):
await ctx.send(msg_response) await ctx.send(msg_response)
@commands.command(usage="[tickers]") @commands.command(usage="<tickers>")
async def crypto(self, ctx, *tickers): async def crypto(self, ctx, *tickers: List[str]) -> None:
""" """Get prices for the given crypto tickers. Will default tickers to BTC, ETH and LTC if none provided."""
Get prices for the given crypto tickers. Will default tickers to BTC, ETH and LTC if none provided. LUNAR_CRUSH_API_KEY = os.getenv("LUNAR_CRUSH_API_KEY")
"""
LUNAR_CRUSH_API_KEY = os.getenv('LUNAR_CRUSH_API_KEY')
# default tickers # default tickers
if len(tickers) == 0: if len(tickers) == 0:

43
cogs/fun.py Normal file
View File

@@ -0,0 +1,43 @@
import random
import discord
import requests
import json
from discord.ext import commands
class Fun(commands.Cog):
"""Commands that are good for the soul!"""
@commands.command()
async def flip(self, ctx) -> None:
"""Will flip a coin and return either heads or tails."""
coin = random.randint(0, 1)
message = "heads!" if coin else "tails!"
await ctx.send(f"<@!{ctx.author.id}> {message}")
@commands.command(usage="<repo_name>")
async def github(self, ctx, repo_name: str = "") -> None:
"""Returns the github repo information for a given repo name."""
if len(repo_name.strip()) == 0:
await ctx.send("**Please provide a repo name. ex.** `gio101046/pyvis`")
return
http_response = requests.get(f"https://api.github.com/repos/{repo_name}")
repo_info = json.loads(http_response.text)
if http_response.status_code == 404:
await ctx.send(f"**Couldn't find repo:** `{repo_name}`")
return
# construct embed response
github_embed = discord.Embed(title=repo_info["full_name"], description=repo_info["description"], color=0x3DCCDD) # TODO: extract harcoded color
github_embed.set_thumbnail(url=repo_info["owner"]["avatar_url"])
github_embed.add_field(name="Repository", value=f"[{repo_info['name']}]({repo_info['html_url']})", inline=True)
github_embed.add_field(name="Language", value=repo_info['language'], inline=True)
github_embed.add_field(name="Forks", value=repo_info['forks'], inline=True)
github_embed.add_field(name="Watchers", value=repo_info['watchers'], inline=True)
github_embed.add_field(name="Open Issues", value=repo_info['open_issues'], inline=True)
github_embed.set_footer(text=f"Repo created at • {repo_info['created_at'].split('T')[0]}")
await ctx.send(embed=github_embed)

View File

@@ -4,8 +4,6 @@ class Python(commands.Cog):
"""General commands about python programming.""" """General commands about python programming."""
@commands.command() @commands.command()
async def resources(self, ctx): async def resources(self, ctx) -> None:
""" """Will provide resources for python programming."""
Will provide resources for python programming.
"""
await ctx.send("Some resources for you here!") # TODO: Add resources await ctx.send("Some resources for you here!") # TODO: Add resources

View File

@@ -1,7 +1,8 @@
import discord import discord
import os import os
from cogs.finance import Finance
from cogs.python import Python from cogs.python import Python
from cogs.fun import Fun
from cogs.finance import Finance
from discord.ext import commands from discord.ext import commands
from dotenv import load_dotenv from dotenv import load_dotenv
from pretty_help import DefaultMenu, PrettyHelp from pretty_help import DefaultMenu, PrettyHelp
@@ -26,7 +27,7 @@ async def on_ready():
@bot.event @bot.event
async def on_member_join(member): async def on_member_join(member):
pass # TODO pass # TODO send new member welcome message on join
@bot.event @bot.event
async def on_message(message): async def on_message(message):
@@ -47,6 +48,7 @@ bot.help_command = PrettyHelp(navigation=menu, color=discord.Colour.green())
# commands by category a.k.a. cogs # commands by category a.k.a. cogs
bot.add_cog(Python()) bot.add_cog(Python())
bot.add_cog(Fun())
bot.add_cog(Finance()) bot.add_cog(Finance())
# start up bot # start up bot