Skip to content

Commit

Permalink
Replaced prints with logging
Browse files Browse the repository at this point in the history
  • Loading branch information
StephanAkkerman committed Jul 31, 2024
1 parent 75a1f2f commit 30b77f8
Show file tree
Hide file tree
Showing 35 changed files with 152 additions and 131 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ scraped/*
logs/*
curl.txt
data/
temp/

# Byte-compiled / optimized / DLL files
__pycache__/
Expand Down
3 changes: 3 additions & 0 deletions config.yaml
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
# Set to "INFO" if you want less clutter in your terminal
LOGGING_LEVEL: DEBUG

# This is used for the user channels
# For instance 👨┃elonmusk
CHANNEL_SEPARATOR:
Expand Down
18 changes: 18 additions & 0 deletions data/bitcoin_data.csv
Original file line number Diff line number Diff line change
Expand Up @@ -5680,3 +5680,21 @@ Date,Value
2024-07-12,57889.1
2024-07-13,59204.02
2024-07-14,60797.91
2024-07-14,60797.91
2024-07-15,64724.14
2024-07-16,65043.99
2024-07-17,64087.99
2024-07-18,63987.92
2024-07-19,66660.0
2024-07-20,67139.96
2024-07-21,68165.34
2024-07-22,67532.01
2024-07-23,65936.01
2024-07-24,65376.0
2024-07-25,65799.95
2024-07-26,67907.99
2024-07-27,67896.5
2024-07-28,68249.88
2024-07-28,68249.88
2024-07-29,66784.69
2024-07-30,66188.0
3 changes: 2 additions & 1 deletion src/cogs/commands/earnings.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@

# Local dependencies
from util.confirm_stock import confirm_stock
from util.vars import logger


class Earnings(commands.Cog):
Expand Down Expand Up @@ -82,7 +83,7 @@ async def earnings_error(self, ctx: ApplicationContext, error: Exception):
error : Exception
The exception that was raised when using the `!earnings` command.
"""
print(error)
logger.error(error)
if isinstance(error, commands.UserInputError):
await ctx.send(
f"{ctx.author.mention} You must specify a stock to request the next earnings of!"
Expand Down
7 changes: 3 additions & 4 deletions src/cogs/commands/portfolio.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
from cogs.loops.assets import Assets
from cogs.loops.trades import Trades
from util.db import update_db
from util.vars import logger


class Portfolio(commands.Cog):
Expand Down Expand Up @@ -199,7 +200,6 @@ async def show(

@add.error
async def add_error(self, ctx: ApplicationContext, error: Exception) -> None:
# print(traceback.format_exc())
if isinstance(error, commands.BadArgument):
await ctx.respond(
f"The exchange you specified is currently not supported! \nSupported exchanges: Kucoin, Binance"
Expand All @@ -209,17 +209,16 @@ async def add_error(self, ctx: ApplicationContext, error: Exception) -> None:
f"If using `/portfolio add` with Kucoin, you must specify a passphrase!"
)
else:
print(error)
logger.error(error)
await ctx.respond(f"An error has occurred. Please try again later.")

@remove.error
async def remove_error(self, ctx: ApplicationContext, error: Exception) -> None:
# print(traceback.format_exc())
await ctx.respond(f"An error has occurred. Please try again later.")

@show.error
async def show_error(self, ctx: ApplicationContext, error: Exception) -> None:
print(traceback.format_exc())
logger.error(traceback.format_exc())
if isinstance(error, commands.PrivateMessageOnly):
await ctx.respond(
"Please only use the `/portfolio` command in private messages for security reasons."
Expand Down
6 changes: 2 additions & 4 deletions src/cogs/commands/sentiment.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
from util.confirm_stock import confirm_stock

# > Local dependencies
from util.vars import get_json_data
from util.vars import get_json_data, logger


class Sentiment(commands.Cog):
Expand Down Expand Up @@ -122,7 +122,7 @@ async def sentiment_error(self, ctx: ApplicationContext, error: Exception) -> No
error : Exception
The exception that was raised when using the `!sentiment` command.
"""
print(error)
logger.error(error)
await ctx.respond(f"An error has occurred. Please try again later.")

async def get_news(self, ticker: str) -> pd.DataFrame:
Expand All @@ -148,8 +148,6 @@ async def get_news(self, ticker: str) -> pd.DataFrame:
text=True,
)

print(html)

# Get everything part of id='news-table'
html = html[html.find('id="news-table"') :]
html = html[: html.find("</table>")]
Expand Down
6 changes: 3 additions & 3 deletions src/cogs/listeners/on_raw_reaction_add.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

# > Local dependencies
from util.disc_util import get_channel, get_webhook
from util.vars import config
from util.vars import config, logger


class On_raw_reaction_add(commands.Cog):
Expand Down Expand Up @@ -54,7 +54,7 @@ async def on_raw_reaction_add(
await channel.history(limit=100).flatten(), id=reaction.message_id
)
except Exception as e:
print(f"Error getting channel.history for {channel}. Error:", e)
logger.error(f"Error getting channel.history for {channel}. Error:", e)
return

if reaction.user_id != self.bot.user.id:
Expand All @@ -70,7 +70,7 @@ async def on_raw_reaction_add(
await self.send_dm(message, reaction.member)

except commands.CommandError as e:
print(e)
logger.error(e)

async def classify_reaction(
self, reaction: discord.RawReactionActionEvent, message: discord.Message
Expand Down
8 changes: 4 additions & 4 deletions src/cogs/loops/assets.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
from util.disc_util import get_channel, get_guild, get_user
from util.exchange_data import get_data
from util.formatting import format_change, format_embed_length
from util.vars import config
from util.vars import config, logger
from util.yf_data import get_stock_info


Expand Down Expand Up @@ -93,7 +93,7 @@ async def assets(self) -> None:
}

if util.vars.portfolio_db.empty:
print("No portfolios in the database.")
logger.warn("No portfolios in the database.")
return

# Drop all crypto assets, so we can update them
Expand Down Expand Up @@ -340,7 +340,7 @@ async def get_user_channel(self, name: str) -> discord.TextChannel:
channel = await guild.create_text_channel(
channel_name, category=config["CATEGORIES"]["USERS"]
)
print(f"Created channel {channel_name}")
logger.info(f"Created channel {channel_name}")

return channel

Expand All @@ -352,7 +352,7 @@ async def get_user(self, assets):
try:
disc_user = await get_user(self.bot, id)
except Exception as e:
print(f"Could not get user with id: {id}.\n{assets} \nError:", e)
logger.error(f"Could not get user with id: {id}.\n{assets} \nError:", e)

return disc_user

Expand Down
4 changes: 2 additions & 2 deletions src/cogs/loops/earnings_overview.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
from discord.ext.tasks import loop

from util.disc_util import get_channel, get_tagged_users
from util.vars import config, data_sources, get_json_data
from util.vars import config, data_sources, get_json_data, logger


class Earnings_Overview(commands.Cog):
Expand Down Expand Up @@ -141,7 +141,7 @@ async def earnings(self) -> None:
date_string = date.strftime("%Y-%m-%d")

if earnings_df.empty:
print(f"No earnings found for {date_string}")
logger.warn(f"No earnings found for {date_string}")
continue

# Only use the top 10 per dataframe
Expand Down
6 changes: 3 additions & 3 deletions src/cogs/loops/funding.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
from util.disc_util import get_channel

# Local dependencies
from util.vars import config, data_sources, get_json_data
from util.vars import config, data_sources, get_json_data, logger


class Funding(commands.Cog):
Expand Down Expand Up @@ -46,14 +46,14 @@ async def funding(self) -> None:

# If the call did not work
if not binance_data:
print("Could not get funding data...")
logger.warn("Could not get funding data...")
return

# Cast to dataframe
try:
df = pd.DataFrame(binance_data)
except Exception as e:
print(f"Could not cast to dataframe, error: {e}")
logger.error(f"Could not cast to dataframe, error: {e}")
return

# Keep only the USDT pairs
Expand Down
4 changes: 2 additions & 2 deletions src/cogs/loops/funding_heatmap.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@

from util.cg_data import get_top_vol_coins
from util.disc_util import get_channel
from util.vars import config, data_sources
from util.vars import config, data_sources, logger

FIGURE_SIZE = (20, 10)
NUM_COINS = 30
Expand Down Expand Up @@ -128,7 +128,7 @@ def fund_rating(self, symbol: str, rows: int = 100):
df = pd.DataFrame(response.json()["data"])

if df.empty:
print(f"No data found for {symbol}")
logger.warn(f"No data found for {symbol}")
return df

# Convert timestamp to datetime
Expand Down
7 changes: 3 additions & 4 deletions src/cogs/loops/gainers.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from util.formatting import format_embed

# Local dependencies
from util.vars import config, get_json_data
from util.vars import config, get_json_data, logger


class Gainers(commands.Cog):
Expand Down Expand Up @@ -61,7 +61,7 @@ async def crypto(self) -> None:
try:
df = pd.DataFrame(binance_data)
except Exception as e:
print(f"Could not cast to dataframe, error: {e}")
logger.error(f"Could not cast to dataframe, error: {e}")
return

# Keep only the USDT pairs
Expand Down Expand Up @@ -153,8 +153,7 @@ async def stocks(self) -> None:
await self.stocks_channel.purge(limit=1)
await self.stocks_channel.send(embed=e)
except Exception as e:
print("Error posting stocks gainers: ", e)
# print(traceback.format_exc())
logger.error("Error posting stocks gainers: ", e)


def setup(bot: commands.Bot) -> None:
Expand Down
4 changes: 2 additions & 2 deletions src/cogs/loops/ideas.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
import util.vars
from util.db import update_db
from util.disc_util import get_channel, get_tagged_users
from util.vars import config, data_sources, get_json_data
from util.vars import config, data_sources, get_json_data, logger


class TradingView_Ideas(commands.Cog):
Expand Down Expand Up @@ -332,7 +332,7 @@ async def scraper(type: str) -> pd.DataFrame:
)

if content is None:
print(f"No content found for {type} ideas")
logger.warn(f"No content found for {type} ideas")
return pd.DataFrame()

# Save the Timestamps
Expand Down
1 change: 0 additions & 1 deletion src/cogs/loops/index.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,6 @@ async def crypto(self) -> None:
for index in self.crypto_indices:
price, change, _, exchange, _ = await tv.get_tv_data(index, "crypto")
if price == 0:
print(index)
continue
change = round(change, 2)
change = f"+{change}% 📈" if change > 0 else f"{change}% 📉"
Expand Down
12 changes: 5 additions & 7 deletions src/cogs/loops/liquidations.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@

from util.disc_util import get_channel
from util.formatting import human_format
from util.vars import config, data_sources
from util.vars import config, data_sources, logger

BACKGROUND_COLOR = "#0d1117"
FIGURE_SIZE = (15, 7)
Expand Down Expand Up @@ -51,7 +51,7 @@ async def post_liquidations(self):
market = "um"
new_data = get_new_data(coin, market=market)
if new_data:
print(f"Downloaded {len(new_data)} new files.")
logger.info(f"Downloaded {len(new_data)} new files.")
# Recreate the summaryf
summarize_liquidations(coin=coin, market=market)
# Load the summary
Expand Down Expand Up @@ -278,12 +278,10 @@ def download_and_extract_zip(
# Step 2: Extract the contents of the ZIP file
with zipfile.ZipFile(BytesIO(response.content)) as zip_ref:
zip_ref.extractall(extract_to)

# print(f"Extracted all contents to {extract_to} for date {date_str}")
except requests.RequestException as e:
print(f"Failed to download {url}: {e}")
logger.error(f"Failed to download {url}: {e}")
except zipfile.BadZipFile as e:
print(f"Failed to extract {url}: {e}")
logger.error(f"Failed to extract {url}: {e}")


def get_new_data(
Expand Down Expand Up @@ -313,7 +311,7 @@ def get_new_data(
try:
future.result()
except Exception as e:
print(f"Error occurred: {e}")
logger.error(f"Error occurred: {e}")

return missing_dates

Expand Down
7 changes: 2 additions & 5 deletions src/cogs/loops/losers.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
# Standard libraries
import traceback

# > 3rd party dependencies
import yahoo_fin.stock_info as si

Expand All @@ -13,7 +11,7 @@
from util.formatting import format_embed

# Local dependencies
from util.vars import config
from util.vars import config, logger


class Losers(commands.Cog):
Expand Down Expand Up @@ -53,8 +51,7 @@ async def losers(self) -> None:
e = await format_embed(si.get_day_losers().head(10), "Losers", "yahoo")
await self.channel.send(embed=e)
except Exception as e:
print("Error getting or posting stock losers, error:", e)
print(traceback.format_exc())
logger.error("Error getting or posting stock losers, error:", e)


def setup(bot: commands.Bot) -> None:
Expand Down
Loading

0 comments on commit 30b77f8

Please sign in to comment.