Files
.gitignore
bot.py
requirements.txt
Code
3 82
bot.py
import logging
import os
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("talk-bot")
class TalkBot(commands.Bot):
def __init__(self) -> None:
intents = discord.Intents.default()
super().__init__(command_prefix=commands.when_mentioned, intents=intents)
async def setup_hook(self) -> None:
await self.tree.sync()
logger.info("Synced application commands")
async def on_ready(self) -> None:
if self.user is not None:
logger.info("Logged in as %s (%s)", self.user, self.user.id)
bot = TalkBot()
@bot.tree.command(name="talk", description="Send a message between 1 and 5 times")
@app_commands.describe(message="The message to send", times="How many times to send it")
async def talk(
interaction: discord.Interaction,
message: str,
times: app_commands.Range[int, 1, 5],
) -> None:
await interaction.response.send_message(message)
for _ in range(times - 1):
await interaction.followup.send(message)
@bot.tree.error
async def on_app_command_error(
interaction: discord.Interaction,
error: app_commands.AppCommandError,
) -> None:
logger.error("Application command failed", exc_info=error)
response = "Something went wrong while running that command."
if isinstance(error, app_commands.CommandOnCooldown):
response = "Please try again shortly."
if interaction.response.is_done():
await interaction.followup.send(response, ephemeral=True)
else:
await interaction.response.send_message(response, ephemeral=True)
def main() -> None:
token = os.getenv("DISCORD_TOKEN")
if not token:
raise RuntimeError("DISCORD_TOKEN is missing from the environment")
bot.run(token)
if __name__ == "__main__":
main()