jellyfishingmatt

Make A Discord Bot For Reaction Roles,Levels,Goodbye and welcome messages,Counting channels and a channel to grow a tree like grow a tree

Kodari AI
KodariAug 23 at 11:45 pm 1
ReactionGroveBot
A Discord bot that manages reaction roles by assigning roles via emoji reactions, tracks user levels with XP and rank progression, sends welcome and goodbye messages for member joins/leaves, counts messages in channels, and features a tree-growing channel where users water a shared tree to help it grow through stages.
  1. Create a secure discord.py bot entry point with reaction roles, leveling, welcome/goodbye, counting, and tree-growth gameplay.

  2. Add dependency and environment templates so the bot can be run without hardcoded credentials.

Created a Discord community bot with:

  • Reaction roles using !reactionrole @Role ๐Ÿ˜€

  • XP and levels with !level and !leaderboard

  • Welcome and goodbye messages

  • Counting channel with automatic reset on incorrect numbers

  • Community tree-growth channel where members send water, ๐ŸŒฑ, ๐ŸŒณ, or ๐Ÿ’ง

  • Persistent SQLite storage in bot.db

  • Permission checks, embeds, logging, and command error handling

  • Secure token loading through .env

Setup:

Shell
pip install -r requirements.txt
cp .env.example .env

Add your token to .env:

Env
DISCORD_TOKEN=your_discord_bot_token_here

Run:

Shell
python bot.py

Enable the Message Content Intent and Server Members Intent in the Discord Developer Portal. The bot also needs Manage Roles for reaction roles and permission to send messages/react in configured channels.

Kodari can make mistakes. Review important code before using.
Files
.gitignore
bot.py
requirements.txt
Code
3 414
bot.py
import logging
import os
import sqlite3
import time
from typing import Optional

import discord
from discord.ext import commands
from dotenv import load_dotenv


load_dotenv()
logging.basicConfig(level=logging.INFO, format="[%(asctime)s] %(levelname)s: %(message)s")
logger = logging.getLogger("community-bot")


class Database:
    def __init__(self, path: str = "bot.db"):
        self.connection = sqlite3.connect(path, check_same_thread=False)
        self.connection.row_factory = sqlite3.Row
        self.connection.execute("PRAGMA journal_mode=WAL")
        self.connection.executescript(
            """
            CREATE TABLE IF NOT EXISTS settings (
                guild_id INTEGER PRIMARY KEY,
                welcome_channel INTEGER,
                goodbye_channel INTEGER,
                counting_channel INTEGER,
                counting_next INTEGER NOT NULL DEFAULT 1,
                tree_channel INTEGER,
                tree_progress INTEGER NOT NULL DEFAULT 0
            );
            CREATE TABLE IF NOT EXISTS reaction_roles (
                message_id INTEGER PRIMARY KEY,
                guild_id INTEGER NOT NULL,
                channel_id INTEGER NOT NULL,
                role_id INTEGER NOT NULL,
                emoji TEXT NOT NULL
            );
            CREATE TABLE IF NOT EXISTS levels (
                guild_id INTEGER NOT NULL,
                user_id INTEGER NOT NULL,
                xp INTEGER NOT NULL DEFAULT 0,
                level INTEGER NOT NULL DEFAULT 0,
                PRIMARY KEY (guild_id, user_id)
            );
            """
        )
        self.connection.commit()

    def settings(self, guild_id: int) -> sqlite3.Row:
        self.connection.execute("INSERT OR IGNORE INTO settings (guild_id) VALUES (?)", (guild_id,))
        self.connection.commit()
        return self.connection.execute("SELECT * FROM settings WHERE guild_id = ?", (guild_id,)).fetchone()

    def set_setting(self, guild_id: int, name: str, value: Optional[int]) -> None:
        allowed = {"welcome_channel", "goodbye_channel", "counting_channel", "tree_channel"}
        if name not in allowed:
            raise ValueError(f"Unsupported setting: {name}")
        self.settings(guild_id)
        self.connection.execute(f"UPDATE settings SET {name} = ? WHERE guild_id = ?", (value, guild_id))
        self.connection.commit()

    def set_next_count(self, guild_id: int, next_count: int) -> None:
        self.connection.execute("UPDATE settings SET counting_next = ? WHERE guild_id = ?", (next_count, guild_id))
        self.connection.commit()

    def add_tree_progress(self, guild_id: int) -> int:
        self.connection.execute(
            "UPDATE settings SET tree_progress = tree_progress + 1 WHERE guild_id = ?", (guild_id,)
        )
        self.connection.commit()
        return self.settings(guild_id)["tree_progress"]

    def add_xp(self, guild_id: int, user_id: int, amount: int = 10) -> tuple[int, int, bool]:
        self.connection.execute(
            "INSERT OR IGNORE INTO levels (guild_id, user_id) VALUES (?, ?)", (guild_id, user_id)
        )
        row = self.connection.execute(
            "SELECT xp, level FROM levels WHERE guild_id = ? AND user_id = ?", (guild_id, user_id)
        ).fetchone()
        xp = row["xp"] + amount
        level = row["level"]
        while xp >= (level + 1) ** 2 * 100:
            level += 1
        changed = level > row["level"]
        self.connection.execute(
            "UPDATE levels SET xp = ?, level = ? WHERE guild_id = ? AND user_id = ?",
            (xp, level, guild_id, user_id),
        )
        self.connection.commit()
        return xp, level, changed

    def get_level(self, guild_id: int, user_id: int) -> sqlite3.Row:
        self.connection.execute(
            "INSERT OR IGNORE INTO levels (guild_id, user_id) VALUES (?, ?)", (guild_id, user_id)
        )
        self.connection.commit()
        return self.connection.execute(
            "SELECT xp, level FROM levels WHERE guild_id = ? AND user_id = ?", (guild_id, user_id)
        ).fetchone()

    def top_levels(self, guild_id: int, limit: int = 10) -> list[sqlite3.Row]:
        return self.connection.execute(
            "SELECT user_id, xp, level FROM levels WHERE guild_id = "
            "? ORDER BY level DESC, xp DESC LIMIT ?",
            (guild_id, limit),
        ).fetchall()

    def add_reaction_role(self, message_id: int, guild_id: int, channel_id: int, role_id: int, emoji: str) -> None:
        self.connection.execute(
            "INSERT OR REPLACE INTO reaction_roles "
            "(message_id, guild_id, channel_id, role_id, emoji) VALUES (?, ?, ?, ?, ?)",
            (message_id, guild_id, channel_id, role_id, emoji),
        )
        self.connection.commit()

    def reaction_role(self, message_id: int) -> Optional[sqlite3.Row]:
        return self.connection.execute(
            "SELECT * FROM reaction_roles WHERE message_id = ?", (message_id,)
        ).fetchone()


class CommunityBot(commands.Bot):
    def __init__(self):
        intents = discord.Intents.default()
        intents.members = True
        intents.message_content = True
        intents.reactions = True
        super().__init__(command_prefix="!", intents=intents, help_command=None)
        self.database = Database()
        self.xp_cooldowns: dict[tuple[int, int], float] = {}
        self.tree_cooldowns: dict[tuple[int, int], float] = {}

    async def setup_hook(self):
        logger.info("Bot setup complete")

    async def on_ready(self):
        logger.info("Logged in as %s (%s)", self.user, self.user.id if self.user else "unknown")
        await self.change_presence(activity=discord.Game(name="!help | community games"))

    async def on_member_join(self, member: discord.Member):
        channel_id = self.database.settings(member.guild.id)["welcome_channel"]
        channel = member.guild.get_channel(channel_id) if channel_id else None
        if channel:
            await channel.send(
                f"๐Ÿ‘‹ Welcome {member.mention} to **{member.guild.name}**! "
                "Read the rules and enjoy your stay."
            )

    async def on_member_remove(self, member: discord.Member):
        channel_id = self.database.settings(member.guild.id)["goodbye_channel"]
        channel = member.guild.get_channel(channel_id) if channel_id else None
        if channel:
            await channel.send(f"๐Ÿ‘‹ **{member}** has left the server. We hope to see you again!")

    async def on_raw_reaction_add(self, payload: discord.RawReactionActionEvent):
        if not payload.guild_id or payload.user_id == self.user.id:
            return
        record = self.database.reaction_role(payload.message_id)
        if not record or record["emoji"] != str(payload.emoji):
            return
        guild = self.get_guild(payload.guild_id)
        member = guild.get_member(payload.user_id) if guild else None
        role = guild.get_role(record["role_id"]) if guild else None
        if member and role and role not in member.roles:
            try:
                await member.add_roles(role, reason="Reaction role")
            except discord.HTTPException:
                logger.warning("Could not add reaction role %s in guild %s", role.id, guild.id)

    async def on_raw_reaction_remove(self, payload: discord.RawReactionActionEvent):
        if not payload.guild_id:
            return
        record = self.database.reaction_role(payload.message_id)
        if not record or record["emoji"] != str(payload.emoji):
            return
        guild = self.get_guild(payload.guild_id)
        member = guild.get_member(payload.user_id) if guild else None
        role = guild.get_role(record["role_id"]) if guild else None
        if member and role and role in member.roles:
            try:
                await member.remove_roles(role, reason="Reaction role removed")
            except discord.HTTPException:
                logger.warning("Could not remove reaction role %s in guild %s", role.id, guild.id)

    async def on_message(self, message: discord.Message):
        if message.author.bot or not message.guild:
            await self.process_commands(message)
            return

        settings = self.database.settings(message.guild.id)
        if settings["counting_channel"] == message.channel.id:
            await self.handle_counting(message, settings["counting_next"])

        if settings["tree_channel"] == message.channel.id and message.content.strip().lower() in {
            "water", "๐ŸŒฑ", "๐ŸŒณ", "๐Ÿ’ง"
        }:
            await self.handle_tree(message)