Files
assets
.gitignore
bot.py
README.md
requirements.txt
Code
5 221
bot.py
import logging
import os
from typing import Optional
import discord
from discord import app_commands
from discord.ext import commands
from dotenv import load_dotenv
load_dotenv()
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s | %(levelname)s | %(name)s | %(message)s",
)
logger = logging.getLogger("celestial-vision")
BRAND_COLOR = discord.Colour.from_rgb(15, 76, 152)
ACCENT_COLOR = discord.Colour.from_rgb(255, 174, 0)
class CelestialVisionBot(commands.Bot):
def __init__(self) -> None:
intents = discord.Intents.default()
intents.members = True
super().__init__(command_prefix="!", intents=intents)
async def setup_hook(self) -> None:
synced_commands = await self.tree.sync()
logger.info("Synced %d application command(s)", len(synced_commands))
bot = CelestialVisionBot()
def logo_url() -> Optional[str]:
value = os.getenv("LOGO_URL", "").strip()
return value or None
def welcome_embed(member: discord.Member) -> discord.Embed:
embed = discord.Embed(
title="Welcome to Celestial Vision ✨",
description=(
f"Welcome {member.mention}!\n\n"
"We’re glad you’re here. Take a look around, meet the community, "
"and enjoy the view."
),
colour=ACCENT_COLOR,
)
embed.set_footer(text="Celestial Vision • See beyond the ordinary")
if logo := logo_url():
embed.set_thumbnail(url=logo)
return embed
@bot.event
async def on_ready() -> None:
if bot.user is not None:
logger.info("Logged in as %s (%s)", bot.user, bot.user.id)
@bot.event
async def on_member_join(member: discord.Member) -> None:
channel_id = os.getenv("WELCOME_CHANNEL_ID", "").strip()
if not channel_id:
return
try:
channel = member.guild.get_channel(int(channel_id))
except ValueError:
logger.warning("WELCOME_CHANNEL_ID is not a valid channel ID")
return
if not isinstance(channel, discord.abc.Messageable):
logger.warning("Configured welcome channel was not found or is not messageable")
return
try:
await channel.send(embed=welcome_embed(member))
except discord.Forbidden:
logger.warning("Cannot send a welcome message in channel %s", channel_id)
except discord.HTTPException:
logger.exception("Discord rejected the automatic welcome message")
@bot.tree.command(name="text", description="Send a message as Celestial Vision")
@app_commands.describe(message="The message to send")
@app_commands.guild_only()
@app_commands.checks.cooldown(1, 5.0, key=lambda interaction: interaction.user.id)
async def text_command(interaction: discord.Interaction, message: str) -> None:
await interaction.response.send_message(
message,
allowed_mentions=discord.AllowedMentions.none(),
)
@bot.tree.command(name="welcome", description="Welcome a member with Celestial Vision branding")
@app_commands.describe(member="The member to welcome")
@app_commands.guild_only()
@app_commands.checks.cooldown(1, 10.0, key=lambda interaction: interaction.user.id)
async def welcome_command(interaction: discord.Interaction, member: discord.Member) -> None:
await interaction.response.send_message(embed=welcome_embed(member))
@bot.tree.error
async def on_app_command_error(
interaction: discord.Interaction,
error: app_commands.AppCommandError,
) -> None:
if isinstance(error, app_commands.CommandOnCooldown):
message = f"Please wait {error.retry_after:.1f} seconds before using that command again."
elif isinstance(error, app_commands.NoPrivateMessage):
message = "This command can only be used inside a server."
elif isinstance(error, app_commands.CheckFailure):
message = "You cannot use that command right now."
else:
logger.exception("Unhandled application command error", exc_info=error)
message = "Something went wrong while running that command."
if interaction.response.is_done():
await interaction.followup.send(message, ephemeral=True)
else:
await interaction.response.send_message(message, ephemeral=True)
def main() -> None:
token = os.getenv("DISCORD_TOKEN", "").strip()
if not token:
raise RuntimeError("DISCORD_TOKEN is missing from the environment")
bot.run(token, log_handler=None)
if __name__ == "__main__":
main()