From 144dd1d218babfe0e6f3f050b0d0ea7fe2b3cd4f Mon Sep 17 00:00:00 2001 From: Anson Biggs Date: Tue, 30 Mar 2021 11:36:52 -0700 Subject: [PATCH] Fixed Inline #55 --- Symbol.py | 4 +++- bot.py | 18 +++++++++++------- cg_Crypto.py | 25 +++++++++++++++++++++++++ symbol_router.py | 36 ++++++++++++++++++++++++++++++++++++ 4 files changed, 75 insertions(+), 8 deletions(-) diff --git a/Symbol.py b/Symbol.py index 22bb11c..3e204c6 100644 --- a/Symbol.py +++ b/Symbol.py @@ -1,3 +1,4 @@ +import functools import requests as r @@ -35,6 +36,7 @@ coins = r.get("https://api.coingecko.com/api/v3/coins/list").json() class Coin(Symbol): + @functools.cache def __init__(self, symbol: str) -> None: self.symbol = symbol self.get_data() @@ -48,4 +50,4 @@ class Coin(Symbol): self.name = data["name"] self.description = data["description"] - self.price = data["market_data"]["current_price"][self.currency] + # self.price = data["market_data"]["current_price"][self.currency] diff --git a/bot.py b/bot.py index e9dc768..2165c70 100644 --- a/bot.py +++ b/bot.py @@ -8,6 +8,8 @@ import json import traceback import mplfinance as mpf +from uuid import uuid4 + import telegram from telegram import ( InlineQueryResultArticle, @@ -383,18 +385,19 @@ def inline_query(update: Update, context: CallbackContext): Does a fuzzy search on input and returns stocks that are close. """ - matches = s.search_symbols(update.inline_query.query) + matches = s.search_symbols(update.inline_query.query)[:] symbols = " ".join([match[1].split(":")[0] for match in matches]) - prices = s.price_reply(s.find_symbols(symbols)) - + prices = s.batch_price_reply(s.find_symbols(symbols)) + # print(len(matches), len(prices)) + # print(prices) results = [] + print(update.inline_query.query) for match, price in zip(matches, prices): - print(match) try: results.append( InlineQueryResultArticle( - match[0], + str(uuid4()), title=match[1], input_message_content=InputTextMessageContent( price, parse_mode=telegram.ParseMode.MARKDOWN @@ -404,10 +407,11 @@ def inline_query(update: Update, context: CallbackContext): except TypeError: logging.warning(str(match)) pass - - if len(results) == 10: + print(match[0], "\n\n\n") + if len(results) == 5: update.inline_query.answer(results) return + update.inline_query.answer(results) def rand_pick(update: Update, context: CallbackContext): diff --git a/cg_Crypto.py b/cg_Crypto.py index 7123fa2..e1f9ad8 100644 --- a/cg_Crypto.py +++ b/cg_Crypto.py @@ -278,3 +278,28 @@ class cg_Crypto: ] return [f"$${c['item']['symbol'].upper()}: {c['item']['name']}" for c in coins] + + def batch_price(self, coins: list[Coin]) -> list[str]: + query = ",".join([c.id for c in coins]) + + prices = r.get( + f"https://api.coingecko.com/api/v3/simple/price?ids={query}&vs_currencies=usd&include_24hr_change=true" + ).json() + + replies = [] + for name, val in prices.items(): + if price := val.get("usd"): + price = val.get("usd") + else: + replies.append(f"{name} price data unavailable.") + break + + change = 0 + if val.get("usd_24h_change") is not None: + change = val.get("usd_24h_change") + + replies.append( + f"{name}: ${price:,} and has moved {change:.2f}% in the past 24 hours." + ) + + return replies diff --git a/symbol_router.py b/symbol_router.py index db81772..bbca1ed 100644 --- a/symbol_router.py +++ b/symbol_router.py @@ -319,3 +319,39 @@ class Router: ).strftime("%b %d, %Y") return f"{choice}\nBuy and hold until: {hold}" + + def batch_price_reply(self, symbols: list[Symbol]) -> List[str]: + """Returns current market price or after hours if its available for a given stock symbol. + + Parameters + ---------- + symbols : list + List of stock symbols. + + Returns + ------- + Dict[str, str] + Each symbol passed in is a key with its value being a human readable + markdown formatted string of the symbols price and movement. + """ + replies = [] + stocks = [] + coins = [] + + for symbol in symbols: + if isinstance(symbol, Stock): + stocks.append(symbol) + elif isinstance(symbol, Coin): + coins.append(symbol) + else: + print(f"{symbol} is not a Stock or Coin") + + if stocks: + for ( + stock + ) in stocks: # IEX batch endpoint doesnt seem to be working right now + replies.append(self.stock.price_reply(stock)) + if coins: + replies.append(self.crypto.batch_price(coins)) + + return replies