1
0
mirror of https://gitlab.com/simple-stock-bots/simple-stock-bot.git synced 2025-06-16 15:17:28 +00:00

Fixed Inline #55

This commit is contained in:
Anson Biggs 2021-03-30 11:36:52 -07:00
parent 8dd3ef772f
commit 144dd1d218
4 changed files with 75 additions and 8 deletions

View File

@ -1,3 +1,4 @@
import functools
import requests as r import requests as r
@ -35,6 +36,7 @@ coins = r.get("https://api.coingecko.com/api/v3/coins/list").json()
class Coin(Symbol): class Coin(Symbol):
@functools.cache
def __init__(self, symbol: str) -> None: def __init__(self, symbol: str) -> None:
self.symbol = symbol self.symbol = symbol
self.get_data() self.get_data()
@ -48,4 +50,4 @@ class Coin(Symbol):
self.name = data["name"] self.name = data["name"]
self.description = data["description"] self.description = data["description"]
self.price = data["market_data"]["current_price"][self.currency] # self.price = data["market_data"]["current_price"][self.currency]

18
bot.py
View File

@ -8,6 +8,8 @@ import json
import traceback import traceback
import mplfinance as mpf import mplfinance as mpf
from uuid import uuid4
import telegram import telegram
from telegram import ( from telegram import (
InlineQueryResultArticle, InlineQueryResultArticle,
@ -383,18 +385,19 @@ def inline_query(update: Update, context: CallbackContext):
Does a fuzzy search on input and returns stocks that are close. 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]) 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 = [] results = []
print(update.inline_query.query)
for match, price in zip(matches, prices): for match, price in zip(matches, prices):
print(match)
try: try:
results.append( results.append(
InlineQueryResultArticle( InlineQueryResultArticle(
match[0], str(uuid4()),
title=match[1], title=match[1],
input_message_content=InputTextMessageContent( input_message_content=InputTextMessageContent(
price, parse_mode=telegram.ParseMode.MARKDOWN price, parse_mode=telegram.ParseMode.MARKDOWN
@ -404,10 +407,11 @@ def inline_query(update: Update, context: CallbackContext):
except TypeError: except TypeError:
logging.warning(str(match)) logging.warning(str(match))
pass pass
print(match[0], "\n\n\n")
if len(results) == 10: if len(results) == 5:
update.inline_query.answer(results) update.inline_query.answer(results)
return return
update.inline_query.answer(results)
def rand_pick(update: Update, context: CallbackContext): def rand_pick(update: Update, context: CallbackContext):

View File

@ -278,3 +278,28 @@ class cg_Crypto:
] ]
return [f"$${c['item']['symbol'].upper()}: {c['item']['name']}" for c in coins] 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

View File

@ -319,3 +319,39 @@ class Router:
).strftime("%b %d, %Y") ).strftime("%b %d, %Y")
return f"{choice}\nBuy and hold until: {hold}" 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