Skip to content

Commit

Permalink
Merge pull request #16 from rssnyder/logging-exceptions
Browse files Browse the repository at this point in the history
more logging
  • Loading branch information
rssnyder authored Mar 1, 2021
2 parents 584b72f + c65b11f commit ae23dbb
Show file tree
Hide file tree
Showing 4 changed files with 61 additions and 71 deletions.
6 changes: 5 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,9 @@ Live stock tickers for your discord server.

![Discord Sidebar w/ Bots](https://s3.oc0.rileysnyder.org/public/assets/sidebar.png)

## Add tickers to your servers
## Add tickers to your servers (click the image to add)

Don't see a stock or crypto that you need? Join our discord or open a github issue to get new ones added!

### Stocks

Expand All @@ -40,6 +42,8 @@ Live stock tickers for your discord server.
[![FCEL](https://logo.clearbit.com/fuelcellenergy.com)](https://discord.com/api/oauth2/authorize?client_id=812041645008093186&permissions=0&scope=bot)
[![IPOD](https://s3.oc0.rileysnyder.org/public/assets/ipod.jpg)](https://discord.com/api/oauth2/authorize?client_id=814168658082791454&permissions=0&scope=bot)
[![IPOF](https://s3.oc0.rileysnyder.org/public/assets/ipof.jpg)](https://discord.com/api/oauth2/authorize?client_id=814169320233369640&permissions=0&scope=bot)
[![AMD](https://logo.clearbit.com/amd.com)](https://discord.com/api/oauth2/authorize?client_id=816049122850897923&permissions=0&scope=bot)
[![NIO](https://logo.clearbit.com/nio.com)](https://discord.com/api/oauth2/authorize?client_id=816049780546994196&permissions=0&scope=bot)

### Crypto

Expand Down
120 changes: 50 additions & 70 deletions main.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
'''discord-stock-ticker'''
from os import getenv
from datetime import datetime
from random import choice
import logging

import asyncio
Expand All @@ -12,17 +10,7 @@
from utils.coin_gecko import get_crypto_price_async

CURRENCY = 'usd'
WEEKEND = [
5,
6
]
ALERTS = [
'discord.gg/CQqnCYEtG7',
'markets be closed',
'gme to the moon',
'what about second breakfast',
'subscribe for real time prices!'
]
NAME_CHANGE_DELAY = 3600


class Ticker(discord.Client):
Expand Down Expand Up @@ -115,12 +103,6 @@ async def stock_update_name(self, ticker: str, name: str):
# Loop as long as the bot is running
while not self.is_closed():

# Dont bother updating if markets closed
if (datetime.now().hour >= 17) or (datetime.now().hour < 8) or (datetime.today().weekday() in WEEKEND):
logging.info('markets are closed')
await asyncio.sleep(3600)
continue

logging.info('stock name update started')

# Grab the current price data
Expand All @@ -136,19 +118,19 @@ async def stock_update_name(self, ticker: str, name: str):
await self.user.edit(
username=f'{name} - ${price}'
)
except discord.HTTPException as e:
logging.error(f'updating name failed: {e.status}: {e.text}')

old_price = price
logging.info('name updated')
old_price = price
logging.info('name updated')
except discord.HTTPException as e:
logging.warning(f'updating name failed: {e.status}: {e.text}')

else:
logging.info('no price change')

# Only update every hour
await asyncio.sleep(3600)

logging.info('name sleep ended')
logging.info(f'stock name sleeping for {NAME_CHANGE_DELAY}s')
await asyncio.sleep(NAME_CHANGE_DELAY)
logging.info('stock name sleep ended')


async def stock_update_activity(self, ticker: str, name: str, change_nick: bool = False, frequency: int = 60):
Expand All @@ -169,40 +151,30 @@ async def stock_update_activity(self, ticker: str, name: str, change_nick: bool
# Loop as long as the bot is running
while not self.is_closed():

# If markets are closed, utilize activity for other messages
hour = datetime.now().hour
day = datetime.today().weekday()
if (hour >= 17) or (hour < 8) or (day in WEEKEND):

logging.info('markets are closed')

try:
await self.change_presence(
activity=discord.Activity(
type=discord.ActivityType.watching,
name=choice(ALERTS)
)
)
except discord.InvalidArgument as e:
logging.error(f'updating activity failed: {e.status}: {e.text}')

await asyncio.sleep(600)
continue

logging.info('stock activity update started')

# Grab the current price data w/ day difference
data = await get_stock_price_async(ticker)
price_data = data.get('quoteSummary', {}).get('result', []).pop().get('price', {})
price = price_data.get('regularMarketPrice', {}).get('raw', 0.00)
raw_diff = price - data.get('regularMarketPreviousClose', {}).get('raw', 0.00)
diff = round(raw_diff, 2)
if diff > 0:
diff = '+' + str(diff)

logging.info(f'stock activity price retrived {price}')
# If after hours, get change
if price_data.get('postMarketChange'):
raw_diff = price_data.get('postMarketChange', {}).get('raw', 0.00)
diff = round(raw_diff, 2)
if diff > 0:
diff = '+' + str(diff)

activity_content = f'${price} / {diff}'
activity_content = f'After Hours: {diff}'
logging.info(f'stock activity after hours price retrived: {activity_content}')
else:
raw_diff = price_data.get('regularMarketChange', {}).get('raw', 0.00)
diff = round(raw_diff, 2)
if diff > 0:
diff = '+' + str(diff)

activity_content = f'${price} / {diff}'
logging.info(f'stock activity price retrived: {activity_content}')

# Only update on price change
if old_price != price:
Expand All @@ -223,8 +195,13 @@ async def stock_update_activity(self, ticker: str, name: str, change_nick: bool

logging.info(f'stock updated nick in {server.name}')

# Do not include price in activity now
activity_content = f'Day Diff: {diff}'
# Check what price we are displaying
if price_data.get('postMarketChange'):
activity_content_header = 'After Hours'
else:
activity_content_header = 'Day Diff'

activity_content = f'{activity_content_header}: {diff}'


# Change activity
Expand All @@ -235,19 +212,21 @@ async def stock_update_activity(self, ticker: str, name: str, change_nick: bool
name=activity_content
)
)

old_price = price
logging.info('activity updated')

except discord.InvalidArgument as e:
logging.error(f'updating activity failed: {e.status}: {e.text}')

logging.info('activity updated')

old_price = price

else:
logging.info('no price change')

# Only update every min
await asyncio.sleep(frequency)
logging.info('activity sleep ended')
logging.info(f'stock activity sleeping for {frequency}s')
await asyncio.sleep(int(frequency))
logging.info('stock activity sleep ended')


async def crypto_update_name(self, ticker: str, crypto_name: str):
Expand Down Expand Up @@ -279,17 +258,18 @@ async def crypto_update_name(self, ticker: str, crypto_name: str):
await self.user.edit(
username=f'{ticker} - ${price}'
)

old_price = price
logging.info('crypto name updated')
except discord.HTTPException as e:
logging.error(f'updating name failed: {e.status}: {e.text}')

old_price = price
logging.info('crypto name updated')
logging.warning(f'updating name failed: {e.status}: {e.text}')

else:
logging.info('no price change')

# Only update every hour
await asyncio.sleep(3600)
logging.info(f'crypto name sleeping for {NAME_CHANGE_DELAY}s')
await asyncio.sleep(NAME_CHANGE_DELAY)
logging.info('crypto name sleep ended')


Expand Down Expand Up @@ -354,25 +334,25 @@ async def crypto_update_activity(self, ticker: str, crypto_name: str, change_nic
name=activity_content
)
)

old_price = price
logging.info('crypto activity updated')
except discord.InvalidArgument as e:
logging.error(f'updating activity failed: {e.status}: {e.text}')

logging.info('crypto activity updated')

old_price = price

else:
logging.info('no price change')

# Only update every min
await asyncio.sleep(frequency)
logging.info(f'crypto sleeping for {frequency}s')
await asyncio.sleep(int(frequency))
logging.info('crypto activity sleep ended')


if __name__ == "__main__":

logging.basicConfig(
filename='discord-stock-ticker.log',
filename=getenv('LOG_FILE'),
level=logging.INFO,
datefmt='%Y-%m-%d %H:%M:%S',
format='%(asctime)s %(levelname)-8s %(message)s',
Expand Down
3 changes: 3 additions & 0 deletions utils/coin_gecko.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,6 @@ async def get_crypto_price_async(ticker: str) -> dict:
except asyncio.TimeoutError as e:
print(f'Unable to get coingecko prices: {e}')
return {}
except aiohttp.client_exceptions.ClientConnectorError:
print(f'Unable to get yahoo prices: {e}')
return {}
3 changes: 3 additions & 0 deletions utils/yahoo.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,3 +26,6 @@ async def get_stock_price_async(ticker: str) -> dict:
except asyncio.TimeoutError as e:
print(f'Unable to get yahoo prices: {e}')
return {}
except aiohttp.client_exceptions.ClientConnectorError:
print(f'Unable to get yahoo prices: {e}')
return {}

0 comments on commit ae23dbb

Please sign in to comment.