From e100a76d5cd60b3e7e6284c35d159dafeba7d49f Mon Sep 17 00:00:00 2001 From: Antonio Nardella Date: Thu, 9 Nov 2023 08:29:14 +0100 Subject: [PATCH 1/2] embed with timestamp, new: update smd data (admin) --- .gitignore | 5 +++- assets/embed_shimmer_market_data.pkl | Bin 1348 -> 1368 bytes cogs/smr_market.py | 33 +++++++++++++++++++++++---- helpers/formatting.py | 16 ++++++++++--- helpers/logger.py | 2 +- helpers/smr_market_data_embed.py | 9 +++++--- 6 files changed, 53 insertions(+), 12 deletions(-) diff --git a/.gitignore b/.gitignore index 078c5fe..fe0de8f 100644 --- a/.gitignore +++ b/.gitignore @@ -150,4 +150,7 @@ discord.log config.json # Tests folder -tests/ \ No newline at end of file +tests/ + +# PKL files +*.pkl \ No newline at end of file diff --git a/assets/embed_shimmer_market_data.pkl b/assets/embed_shimmer_market_data.pkl index a1e5a09ecc6a8215354cec02556445f7a004ee06..6ef481bbbd359616e7bb61b53eb721fc03647979 100644 GIT binary patch delta 431 zcmY+AyGjF56h)cLC^%T8iI1Q#O&|_8*ZY2qFOaB(20^2(3_6lvjFL$BI|oAd0xxX!h6SL!+s)@Ju{qWgJabB@e`l^<0YaE8pS zwQmvgVFlw7NW}ry6mn|(6fG(u01*gc)N5V!@|EeEO16_Dtl|};^{Q8Hg!N{47+25g zO)tL@9iE((qsD2q9@gf1m2}6!SaEZoA}+y+muX0ud9x?XSE@L(;QIxV^ZmeGZCwW5 zZfVDp3TVtA$7b8kj4=wR)KGKtYR{Oqot<4u5dI&*N&%WMLYgN#<6^-9mJ%YJK$|{E zjFc#dnCp7JkI?|$jcT=FAr%N{tstRE9IX+Q>(5^4FB?XGr!j#66B5dy>F4}sl9B_# z1=K7tO__J6G(UJ)J9$`oD{RJIF^ofR@BAo?qkc(xF%GcMnq#I23yzmfVPx_fP#|)^ delta 448 zcmZ9Ize)o^5Qn+kX>nLssAy1F3n4i+=kDy@&fY2bFKA;xjo2S1lHetZNdyZ)I}4kz z@hL3yA)>FKov-30R|Ktp^Zn+V`F4k{^WeOMedpD>?7uIN4U)v2F6mv@;%>bb5nv!n zoR^p;EQ|pApSL#CXtu1vG%AW(n3i>Bp&44yjHDot>X7*gjhho&JX91o`Vt4d`$3_x z^wh{duYzola(%x^PH*CNCqC~sui70_DAzBVhe_Oui-X4OvyB?eV-8%-1Vt%*Db1Uc zH($B!jZM!h!J6kq?r!fcBGt+X;Sf-e%nt(BC7ze1)q0X-u~1Z}9s!zTTaEePFAsuK zgwRJl=CgFdYfUi(U$K;5Hb3@yQ3#*_=p!EkoQ?Y?gk*{;C46m;?3I+5I{>yeI&5bo jpG{BfDT8zaSLvrR|NnJiASh^_`lSYo=EJF&y{Y+MTPbi8 diff --git a/cogs/smr_market.py b/cogs/smr_market.py index f5f51bc..eea17f4 100644 --- a/cogs/smr_market.py +++ b/cogs/smr_market.py @@ -10,6 +10,7 @@ from discord.ext.commands import Context from helpers import checks import helpers.configuration_manager as configuration_manager +from helpers.smr_market_data_embed import build_embed import logging import pickle import traceback @@ -28,25 +29,24 @@ def __init__(self, bot): # Here you can just add your own commands, you'll always need to provide "self" as first parameter. - @commands.cooldown(1, 3600, commands.BucketType.user) + @commands.cooldown(1, 360, commands.BucketType.user) @commands.hybrid_command( name="smr-market", description="Shares the Shimmer market data", ) # This will only allow non-blacklisted members to execute the command @checks.not_blacklisted() - async def shimmer_market_data(self, context: Context): + async def shimmer_market_data(self, context: Context) -> None: """ This command prints an embed with the Shimmer Market data :param context: The application command context. """ global bot_reply_channel_id - # Do your stuff here if context.message.channel.id != int(bot_reply_channel_id): await context.send( - f"This command can only be used in the <#{bot_reply_channel_id}> channel." + f"This command can only be used in the <#{bot_reply_channel_id}> channel.", ephemeral=True ) return @@ -58,6 +58,31 @@ async def shimmer_market_data(self, context: Context): except Exception: print(traceback.format_exc()) + @commands.cooldown(1, 360, commands.BucketType.user) + @commands.hybrid_command( + name="updatesmd", + description="Force updates the Shimmer market data (Admin only)", + ) + # This will only allow owners to execute the command + @checks.is_owner() + async def updatesmd(self, context: Context) -> None: + """ + This command forces an update of Shimmer Market data + + :param context: The application command context. + """ + try: + await context.send( + "Hello! Shimmer Market Data update launced...", ephemeral=True + ) + await build_embed() + + except Exception: + print(traceback.format_exc()) + + await context.send( + "Hello! Shimmer Market Data update finished.", ephemeral=True + ) # And then we finally add the cog to the bot so that it can load, unload, reload and use it's content. async def setup(bot): diff --git a/helpers/formatting.py b/helpers/formatting.py index 4c6ea47..f44ec3d 100644 --- a/helpers/formatting.py +++ b/helpers/formatting.py @@ -5,6 +5,7 @@ Version: 5.5.0 """ import logging +import datetime logger = logging.getLogger("discord_bot") @@ -20,7 +21,7 @@ async def format_currency(value, currency_symbol="$"): Returns: str: Formatted currency string. """ - logger.info("Formatting for USD currency") + # logger.info("Formatting for USD currency") # Split integer and decimal parts if there is a decimal point parts = str(value).split('.') integer_part = parts[0] @@ -59,7 +60,16 @@ async def format_shimmer_amount(value): Returns: str: Formatted Shimmer token string with 2 decimal places. """ - logger.info("Formatting glow to SMR") + # logger.info("Formatting glow to SMR") # Convert the number to a float and then format it with 2 decimal places formatted_value = '{:.2f}'.format(float(value) / 1000000) - return formatted_value \ No newline at end of file + return formatted_value + + +async def generate_discord_timestamp(): + current_time = datetime.datetime.now() + # Convert current time to UNIX timestamp + unix_timestamp = int(current_time.timestamp()) + # Format the current time in Discord timestamp format + timestamp = current_time.strftime(f'') + return timestamp \ No newline at end of file diff --git a/helpers/logger.py b/helpers/logger.py index d630370..3738e63 100644 --- a/helpers/logger.py +++ b/helpers/logger.py @@ -42,7 +42,7 @@ def format(self, record): def setup_logger(): logger = logging.getLogger("discord_bot") - logger.setLevel(logging.DEBUG) + logger.setLevel(logging.INFO) # Console handler console_handler = logging.StreamHandler() diff --git a/helpers/smr_market_data_embed.py b/helpers/smr_market_data_embed.py index 24fddda..d463b39 100644 --- a/helpers/smr_market_data_embed.py +++ b/helpers/smr_market_data_embed.py @@ -11,13 +11,14 @@ import pickle import traceback import helpers.configuration_manager as configuration_manager -from helpers.formatting import format_currency, format_shimmer_amount +from helpers.formatting import format_currency, format_shimmer_amount, generate_discord_timestamp from helpers.smr_market_data.smd_bitfinex import calculate_total_bitfinex_depth from helpers.smr_market_data.smd_coingecko import get_coingecko_exchange_data from helpers.smr_market_data.smd_shimmer import get_shimmer_data from helpers.smr_market_data.smd_geckoterminal import get_geckoterminal_data from helpers.smr_market_data.smd_defillama import get_defillama_data + logger = logging.getLogger("discord_bot") # Load configuration @@ -32,13 +33,14 @@ async def build_embed(): try: # Get data from API calls - current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M") + # current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M") coingecko_data = await get_coingecko_exchange_data() defillama_data = await get_defillama_data() geckoterminal_data = await get_geckoterminal_data() shimmer_data = await get_shimmer_data() total_defi_tx_24h = geckoterminal_data["total_defi_tx_24h"] shimmer_rank = defillama_data["shimmer_rank"] + discord_timestamp = await generate_discord_timestamp() # Set up Bitfinex order book depth bitfinex_order_book_data = await calculate_total_bitfinex_depth(coingecko_data['usd_price']) @@ -114,7 +116,8 @@ async def build_embed(): # Add additional information embed.add_field(name="Sources", value="Bitfinex, Coingecko, DefiLlama, GeckoTerminal, Shimmer API", inline=False) - embed.set_footer(text="Data updated every 24h; last updated: " + current_time + "\nMade with IOTA-❤️ by Antonio\nOut of beta SOON™") + embed.add_field(name="Last Data Update", value=f"{discord_timestamp}", inline=False) + embed.set_footer(text="Data updated every 24h\nMade with IOTA-❤️ by Antonio\nOut of beta SOON™") # Save the embed to a pickle file with open("assets/embed_shimmer_market_data.pkl", "wb") as f: From fb00bdade5fd100fd6f14011e23c4e034056c491 Mon Sep 17 00:00:00 2001 From: Antonio Nardella Date: Thu, 9 Nov 2023 08:36:42 +0100 Subject: [PATCH 2/2] set commands errors to ephemeral --- assets/embed_shimmer_market_data.pkl | Bin 1368 -> 1368 bytes bot.py | 10 +++++----- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/assets/embed_shimmer_market_data.pkl b/assets/embed_shimmer_market_data.pkl index 6ef481bbbd359616e7bb61b53eb721fc03647979..c95560ae896c279dbb75be0effe22624d11edc36 100644 GIT binary patch delta 251 zcmZ9@F-`+95I|9_;}q+fA_^4SAjoQDjb}XeI1*4IAyL4d0f{1%9Dtr~4g#0p092&o zDy$-^)c^f`*oV)n&SkNiZnG4qMeL>f?iryJj3wKxQ`gYm9QTC4twkmK@N4^V(*Hcx31gTN1*&Y^mmn4u>BJsh>kxf+qndUs>Gy7fOCe1_B wDD5yLJUTch&|G7p|Kr4-{b|olK~W>yyI=K9fO3vnXS1>||LTQR?RvTX0~sDVi~s-t delta 243 zcmZ9^F-`+95QSl_*O6GC00PA}1Xx+tj6E~9BLO8+q)5P?AySG^asYa|IS3qqh67NM zj;pXrnfiVI+q=E{ylo7F-ZwWh^h}^H%}*D_M}dH#52l#H`essxJnc0k(hob=Uo&3i z;ww^MbgmzUcsUG9H*R*jWk0T;drCg#8Y=5kySgsLr^!k_SU$2S>@nv6b;1|=*TP~t yPq74`Lx6BpBmrM*(XTe?)}D7H=t*+O`fg88GJ9bORUg|k{kE@`N+i9T&Hn*c!8p_a diff --git a/bot.py b/bot.py index d506620..63f51de 100644 --- a/bot.py +++ b/bot.py @@ -250,7 +250,7 @@ async def on_command_error(context: Context, error) -> None: description=f"**Please slow down** - You can use this command again in {f'{round(hours)} hours' if round(hours) > 0 else ''} {f'{round(minutes)} minutes' if round(minutes) > 0 else ''} {f'{round(seconds)} seconds' if round(seconds) > 0 else ''}.", color=0xE02B2B, ) - await context.send(embed=embed) + await context.send(embed=embed, ephemeral=True) elif isinstance(error, exceptions.UserBlacklisted): """ The code here will only execute if the error is an instance of 'UserBlacklisted', which can occur when using @@ -275,7 +275,7 @@ async def on_command_error(context: Context, error) -> None: embed = discord.Embed( description="You are not the owner of the bot!", color=0xE02B2B ) - await context.send(embed=embed) + await context.send(embed=embed, ephemeral=True) if context.guild: bot.logger.warning( f"{context.author} (ID: {context.author.id}) tried to execute an owner only command in the guild {context.guild.name} (ID: {context.guild.id}), but the user is not an owner of the bot." @@ -291,7 +291,7 @@ async def on_command_error(context: Context, error) -> None: + "` to execute this command!", color=0xE02B2B, ) - await context.send(embed=embed) + await context.send(embed=embed, ephemeral=True) elif isinstance(error, commands.BotMissingPermissions): embed = discord.Embed( description="I am missing the permission(s) `" @@ -299,7 +299,7 @@ async def on_command_error(context: Context, error) -> None: + "` to fully perform this command!", color=0xE02B2B, ) - await context.send(embed=embed) + await context.send(embed=embed, ephemeral=True) elif isinstance(error, commands.MissingRequiredArgument): embed = discord.Embed( title="Error!", @@ -307,7 +307,7 @@ async def on_command_error(context: Context, error) -> None: description=str(error).capitalize(), color=0xE02B2B, ) - await context.send(embed=embed) + await context.send(embed=embed, ephemeral=True) else: raise error