Skip to content

Commit

Permalink
[Conversions] 1.3.2 Ensure CoinBase only pulls keys it knows exists i…
Browse files Browse the repository at this point in the history
…gnore others
  • Loading branch information
TrustyJAID committed Oct 29, 2022
1 parent 8cad111 commit 9f1d6ae
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 9 deletions.
20 changes: 17 additions & 3 deletions conversions/coin.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
from __future__ import annotations

from datetime import datetime
from typing import Any, List, Dict, Optional
from dataclasses import dataclass
from datetime import datetime
from typing import Any, Dict, List, Optional


@dataclass
Expand Down Expand Up @@ -46,6 +46,20 @@ class CoinBase:
last_historical_data: datetime
platform: Optional[Dict[Any, Any]]

@classmethod
def from_json(cls, data: Dict[Any, Any]) -> CoinBase:
return cls(
id=data["id"],
name=data["name"],
symbol=data["symbol"],
slug=data["slug"],
rank=data["rank"],
is_active=data["is_active"],
first_historical_data=data["first_historical_data"],
last_historical_data=data["last_historical_data"],
platform=data.get("platform"),
)


@dataclass
class Coin:
Expand Down Expand Up @@ -80,5 +94,5 @@ def from_json(cls, data: Dict[Any, Any]) -> Coin:
platform=data["platform"],
cmc_rank=data["cmc_rank"],
last_updated=datetime.strptime(data["last_updated"], "%Y-%m-%dT%H:%M:%S.000Z"),
quote={k: Quote.from_json(v) for k, v in data["quote"].items()}
quote={k: Quote.from_json(v) for k, v in data["quote"].items()},
)
15 changes: 9 additions & 6 deletions conversions/conversions.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import datetime
import logging
from typing import Dict, Optional, Union, List
from typing import Dict, List, Optional, Union

import aiohttp
import discord
Expand All @@ -20,7 +20,7 @@ class Conversions(commands.Cog):
"""

__author__ = ["TrustyJAID"]
__version__ = "1.3.1"
__version__ = "1.3.2"

def __init__(self, bot: Red) -> None:
self.bot = bot
Expand Down Expand Up @@ -172,7 +172,7 @@ async def get_coins(self, coins: List[str]) -> List[Coin]:
url = "https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest"
async with self.session.get(url, headers=await self.get_header(), params=params) as resp:
data = await resp.json()
coins_data = data.get("data", {})
coins_data = data.get("data", {})
for coin_id, coin_data in coins_data.items():
to_ret.append(Coin.from_json(coin_data))
return to_ret
Expand Down Expand Up @@ -206,7 +206,7 @@ async def checkcoins(self) -> None:
async with self.session.get(url, headers=await self.get_header()) as resp:
data = await resp.json()
if resp.status == 200:
self.coin_index = {c["id"]: CoinBase(**c) for c in data.get("data", [])}
self.coin_index = {c["id"]: CoinBase.from_json(c) for c in data.get("data", [])}
elif resp.status == 401:
raise CoinMarketCapError(
"The bot owner has not set an API key. "
Expand Down Expand Up @@ -352,7 +352,8 @@ async def crypto_embed(

msg = f"{amount} {coin.symbol} is **{price:,.2f} {currency}**\n"
embed = discord.Embed(
description=msg, colour=coin_colour.get(coin.name, discord.Colour.dark_grey())
description=msg,
colour=coin_colour.get(coin.name, discord.Colour.dark_grey()),
)
embed.set_footer(text="As of")
embed.set_author(name=coin.name, url=coin_url, icon_url=coin_image)
Expand Down Expand Up @@ -424,7 +425,9 @@ async def stock(self, ctx: commands.Context, ticker: str, currency: str = "USD")
last_updated = datetime.datetime.utcfromtimestamp(ticker_data["regularMarketTime"])
msg = "{0} is {1:,.2f} {2}".format(ticker.upper(), price, currency.upper())
embed = discord.Embed(
description="Stock Price", colour=discord.Colour.lighter_grey(), timestamp=last_updated
description="Stock Price",
colour=discord.Colour.lighter_grey(),
timestamp=last_updated,
)
embed.set_footer(text="Last Updated")
embed.add_field(name=ticker.upper(), value=msg)
Expand Down

0 comments on commit 9f1d6ae

Please sign in to comment.