Files
.gitignore
bot.py
README.md
requirements.txt
Code
4 253
bot.py
import json
import logging
import os
from pathlib import Path
from typing import Optional
import aiohttp
import discord
from discord import app_commands
from discord.ext import commands, tasks
from dotenv import load_dotenv
load_dotenv()
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s | %(levelname)s | %(name)s | %(message)s",
)
logger = logging.getLogger("solana-price-bot")
PRICE_API_URL = "https://api.coingecko.com/api/v3/simple/price"
UPDATE_INTERVAL_MINUTES = 5
STATE_FILE = Path("price_message.json")
def get_required_int(name: str) -> int:
value = os.getenv(name)
if not value:
raise RuntimeError(f"Missing required environment variable: {name}")
try:
return int(value)
except ValueError as exc:
raise RuntimeError(f"{name} must be a Discord ID number") from exc
class SolanaPriceBot(commands.Bot):
def __init__(self) -> None:
intents = discord.Intents.default()
super().__init__(command_prefix="!", intents=intents)
self.price_channel_id = get_required_int("PRICE_CHANNEL_ID")
self.price_message_id: Optional[int] = self._load_message_id()
@staticmethod
def _load_message_id() -> Optional[int]:
if not STATE_FILE.exists():
return None
try:
data = json.loads(STATE_FILE.read_text(encoding="utf-8"))
message_id = data.get("message_id")
return int(message_id) if message_id else None
except (OSError, ValueError, TypeError, json.JSONDecodeError):
logger.warning("Could not read %s; a new price message will be created", STATE_FILE)
return None
def _save_message_id(self, message_id: int) -> None:
STATE_FILE.write_text(
json.dumps({"message_id": message_id}),
encoding="utf-8",
)
async def setup_hook(self) -> None:
await self.tree.sync()
self.update_price_message.start()
async def on_ready(self) -> None:
logger.info("Logged in as %s (%s)", self.user, self.user.id if self.user else "unknown")
async def fetch_solana_price(self) -> tuple[float, Optional[float]]:
params = {
"ids": "solana",
"vs_currencies": "usd",
"include_24hr_change": "true",
}
timeout = aiohttp.ClientTimeout(total=15)
async with aiohttp.ClientSession(timeout=timeout) as session:
async with session.get(PRICE_API_URL, params=params) as response:
response.raise_for_status()
data = await response.json()
solana = data["solana"]
return float(solana["usd"]), solana.get("usd_24h_change")
async def get_price_channel(self) -> Optional[discord.TextChannel]:
channel = self.get_channel(self.price_channel_id)
if channel is None:
try:
channel = await self.fetch_channel(self.price_channel_id)
except (discord.NotFound, discord.Forbidden, discord.HTTPException):
logger.exception("Could not access PRICE_CHANNEL_ID=%s", self.price_channel_id)
return None
return channel if isinstance(channel, discord.TextChannel) else None
@staticmethod
def build_price_embed(price: float, change: Optional[float]) -> discord.Embed:
if change is None:
change_text = "Unavailable"
color = discord.Color.blurple()
else:
change_text = f"{change:+.2f}%"
color = discord.Color.green() if change >= 0 else discord.Color.red()
embed = discord.Embed(
title="Solana (SOL) Price",
color=color,
timestamp=discord.utils.utcnow(),
)
embed.add_field(name="Current price", value=f"${price:,.2f} USD", inline=False)
embed.add_field(name="24-hour change", value=change_text, inline=False)
embed.set_footer(text="Updated every 5 minutes • Data from CoinGecko")
return embed
async def find_or_create_price_message(
self, channel: discord.TextChannel, embed: discord.Embed
) -> discord.Message:
if self.price_message_id is not None:
try:
message = await channel.fetch_message(self.price_message_id)
if message.author == self.user:
await message.edit(embed=embed)
return message
except (discord.NotFound, discord.Forbidden, discord.HTTPException):
self.price_message_id = None
async for message in channel.history(limit=50):
if message.author == self.user and message.embeds:
await message.edit(embed=embed)
self.price_message_id = message.id
self._save_message_id(message.id)
return message
message = await channel.send(embed=embed)
self.price_message_id = message.id
self._save_message_id(message.id)
return message
async def refresh_price_message(self) -> bool:
channel = await self.get_price_channel()
if channel is None:
return False
price, change = await self.fetch_solana_price()
await self.find_or_create_price_message(channel, self.build_price_embed(price, change))
return True
@tasks.loop(minutes=UPDATE_INTERVAL_MINUTES)
async def update_price_message(self) -> None:
try:
await self.refresh_price_message()
except (aiohttp.ClientError, KeyError, TypeError, ValueError, discord.HTTPException):
logger.exception("Unable to update the Solana price")
@update_price_message.before_loop
async def wait_for_bot_ready(self) -> None:
await self.wait_until_ready()
bot = SolanaPriceBot()
@bot.tree.command(name="sol", description="Show the current Solana price")
async def sol(interaction: discord.Interaction) -> None:
await interaction.response.defer()
try:
price, change = await bot.fetch_solana_price()
except (aiohttp.ClientError, KeyError, TypeError, ValueError) as exc:
logger.warning("Manual price request failed: %s", exc)
await interaction.followup.send("I couldn't fetch the Solana price right now. Try again shortly.")
return
await interaction.followup.send(embed=bot.build_price_embed(price, change))
@bot.tree.command(name="refresh", description="Refresh the automatic Solana price message now")
@app_commands.checks.has_permissions(manage_guild=True)
async def refresh(interaction: discord.Interaction) -> None:
await interaction.response.defer(ephemeral=True)
try:
updated = await bot.refresh_price_message()
except (aiohttp.ClientError, KeyError, TypeError, ValueError, discord.HTTPException):
logger.exception("Manual refresh failed")
updated = False
message = "Price message refreshed." if updated else "I couldn't access the configured price channel."
await interaction.followup.send(message, ephemeral=True)
@refresh.error
async def refresh_error(interaction: discord.Interaction, error: app_commands.AppCommandError) -> None:
if isinstance(error, app_commands.errors.MissingPermissions):
message = "You need the Manage Server permission to use this command."
else:
logger.exception("Refresh command failed", exc_info=error)
message = "Something went wrong while refreshing the price message."
if interaction.response.is_done():
await interaction.followup.send(message, ephemeral=True)
else:
await interaction.response.send_message(message, ephemeral=True)