Skip to content

Commit

Permalink
Merge pull request #2 from antonionardella/main
Browse files Browse the repository at this point in the history
Enhancements to Discord Bot: Dynamic Timestamp, Shimmer Data Refresh Command, and Ephemeral Responses
  • Loading branch information
Phyloiota authored Nov 9, 2023
2 parents 6a533ea + 68ee811 commit 799632c
Show file tree
Hide file tree
Showing 7 changed files with 58 additions and 17 deletions.
5 changes: 4 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -150,4 +150,7 @@ discord.log
config.json

# Tests folder
tests/
tests/

# PKL files
*.pkl
Binary file modified assets/embed_shimmer_market_data.pkl
Binary file not shown.
10 changes: 5 additions & 5 deletions bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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."
Expand All @@ -291,23 +291,23 @@ 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) `"
+ ", ".join(error.missing_permissions)
+ "` 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!",
# We need to capitalize because the command arguments have no capital letter in the code.
description=str(error).capitalize(),
color=0xE02B2B,
)
await context.send(embed=embed)
await context.send(embed=embed, ephemeral=True)
else:
raise error

Expand Down
33 changes: 29 additions & 4 deletions cogs/smr_market.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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

Expand All @@ -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):
Expand Down
16 changes: 13 additions & 3 deletions helpers/formatting.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
Version: 5.5.0
"""
import logging
import datetime

logger = logging.getLogger("discord_bot")

Expand All @@ -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]
Expand Down Expand Up @@ -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
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'<t:{unix_timestamp}:f>')
return timestamp
2 changes: 1 addition & 1 deletion helpers/logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
9 changes: 6 additions & 3 deletions helpers/smr_market_data_embed.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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'])
Expand Down Expand Up @@ -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:
Expand Down

0 comments on commit 799632c

Please sign in to comment.