Naki Akbaba

can you make me a discord bot that automatically displaaays the solana coin price every 5 mins

Kodari AI
KodariSep 6 at 2:03 pm 1
SolanaPriceBot
Discord bot that automatically displays the current Solana (SOL) coin price in a designated channel every 5 minutes. Uses CoinGecko API to fetch real-time price data, formats it with current USD value, and posts updates to a configurable Discord channel. Includes error handling for API failures and connection issues, with a simple setup using environment variables for the bot token and channel ID. Features a lightweight scheduler loop that runs continuously, ensuring consistent price updates for community members.

Created a Discord bot that:

  • Displays SOL/USD price in a configured Discord channel

  • Updates the same embed every 5 minutes

  • Shows 24-hour price change

  • Uses CoinGecko for pricing

  • Includes /sol for manual price checks

  • Includes /refresh for server managers

  • Stores the message ID so it survives restarts

  • Loads secrets from .env

Run it with:

Shell
pip install -r requirements.txt
cp .env.example .env
python bot.py

Fill in DISCORD_TOKEN and PRICE_CHANNEL_ID in .env first.

Naki Akbaba

okay so what do u need from me for you to make it in my discord bort

Kodari AI
KodariSep 6 at 2:04 pm 1

To connect it to your Discord, I need:

  1. The channel ID where price updates should appear

    • Discord → User Settings → Advanced → enable Developer Mode

    • Right-click the desired channel → Copy Channel ID

    • You can safely send me the channel ID.

  2. Where you want the bot hosted

    • Your computer

    • A VPS

    • Railway, Render, Replit, etc.

    • The bot must stay running for updates every 5 minutes.

  3. A Discord bot application

    • Create an application and add a bot

    • Invite it using OAuth2 with:

      • bot

      • applications.commands

      • Permissions: View Channel, Send Messages, Embed Links, and Read Message History

Do not send me your bot token. Put it privately in your .env file:

Env
DISCORD_TOKEN=your_token_here
PRICE_CHANNEL_ID=your_channel_id_here

Send me the channel ID and tell me where you want to host it, and I’ll give you the exact setup steps.

Naki Akbaba

DISCORD_TOKEN=l3HCEMg_EqvgI5WHuCuxZykLiKswfijE PRICE_CHANNEL_ID=1546156781439295592

Kodari AI
KodariSep 6 at 2:05 pm 1

Revoke that bot token immediately—it has been exposed and anyone could control your bot.

  1. Select your application → Bot.

  2. Click Reset Token and copy the new token.

  3. Do not send the new token here. Store it in your local .env file:

Env
DISCORD_TOKEN=your_new_token_here
PRICE_CHANNEL_ID=1546156781439295592

The channel ID is fine to share. I still need to know where you’ll run the bot:

  • Your own computer

  • Replit

  • Railway/Render

  • A VPS

For automatic updates every 5 minutes, the bot must run continuously.

Naki Akbaba

my computer

Kodari AI
KodariSep 6 at 2:06 pm 1

Run it on your computer like this:

  1. Reset the exposed Discord token first

    • Discord Developer Portal → your application → Bot → Reset Token

    • Do not send the new token to me.

  2. Install Python 3.11 or newer

    • Download it from python.org/downloads

    • On Windows, check “Add Python to PATH” during installation.

  3. Put the bot files in one folder The folder should contain:

Plain Text
bot.py
requirements.txt
.env

If you have .env.example, copy it and rename the copy to .env.

  1. Put this in .env using your new token privately:

Env
DISCORD_TOKEN=your_new_token_here
PRICE_CHANNEL_ID=1546156781439295592
  1. Open a terminal in the bot folder and install dependencies

Windows:

Powershell
py -m venv .venv
.venv\Scripts\activate
pip install -r requirements.txt
python bot.py

macOS/Linux:

Shell
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
python3 bot.py
  1. Invite the bot to your server through the Developer Portal using these OAuth2 scopes:

Plain Text
bot
applications.commands

Give it these channel permissions:

Plain Text
View Channel
Send Messages
Embed Links
Read Message History

The terminal must remain open for the bot to keep updating every 5 minutes. Closing it stops the bot. Also make sure your computer does not go to sleep while you want updates running.

Kodari can make mistakes. Review important code before using.
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)