weridboy_47

Life line medical management bot.anti raid system and auto mod. A command to dm users.have some emojis for stuff and daily reminders to certain ranks with editable message templates for everything.aswell for a ticket system and ticket access role

Kodari AI
KodariJul 16 at 2:32 pm 7
LifelineGuardianBot
A Discord medical management and community safety bot for Lifeline servers. It provides protected medical records, staff-only user DMs, anti-raid detection with lockdown controls, configurable automoderation, emoji-based responses, scheduled daily reminders for selected ranks, and a private ticket system with configurable access roles. Server administrators can edit message templates, emojis, reminder settings, moderation thresholds, and ticket behavior through config.json or administrator commands.
weridboy_47

Done?

Kodari AI
KodariJul 16 at 2:34 pm 1

Yes—the starter bot files have been created:

  • bot.py

  • config.json

  • requirements.txt

  • .env.example

  • .gitignore

Add your Discord token to .env, install the requirements, configure the roles/channels/templates, then run bot.py.

weridboy_47

i dont see any commands

Kodari AI
KodariJul 16 at 3:58 pm 5
  1. Make slash commands sync instantly to a configured server.

  2. Fix the /raid-status runtime error.

  3. Add the server ID setting to .env.example.

Commands are now configured to sync instantly to your server.

  1. Create or edit .env:

    Env
    DISCORD_TOKEN=your_new_bot_token
    DISCORD_GUILD_ID=your_server_id
    
  2. Restart the bot.

  3. Ensure it was invited with both scopes:

    • bot

    • applications.commands

Available commands include:

  • /medical-add

  • /medical-view

  • /medical-list

  • /medical-delete

  • /dm-user

  • /ticket-panel

  • /ticket-close

  • /ticket-role

  • /template-set

  • /raid-status

  • /raid-lockdown

  • /raid-unlock

  • /remind-now

The token currently visible in .env.example should be regenerated immediately in the Discord Developer Portal, then placed only in .env.

weridboy_47

make sure all commands are synced

Kodari AI
KodariJul 18 at 3:26 am 4

All slash commands are registered and synced in setup_hook().

For instant visibility, set this in .env:

Env
DISCORD_TOKEN=your_bot_token
DISCORD_GUILD_ID=your_server_id

Then restart the bot. It will sync every command directly to that server. The bot must also be invited with both OAuth scopes:

  • bot

  • applications.commands

Without DISCORD_GUILD_ID, commands sync globally and Discord may take up to an hour to display them.

Kodari can make mistakes. Review important code before using.
Files
.gitignore
bot.py
config.json
requirements.txt
Code
4 1,015
bot.py
import asyncio
import json
import logging
import os
import re
import sqlite3
from collections import defaultdict, deque
from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import Optional

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("lifeline")


CONFIG_PATH = Path("config.json")
DEFAULT_CONFIG = {
    "medical_role_ids": [],
    "log_channel_id": 0,
    "ticket_category_id": 0,
    "ticket_access_role_id": 0,
    "automod": {
        "enabled": True,
        "blocked_words": [],
        "block_invites": True,
        "max_mentions": 8,
        "timeout_minutes": 10,
    },
    "anti_raid": {
        "enabled": True,
        "join_threshold": 6,
        "join_window_seconds": 20,
        "minimum_account_age_hours": 24,
        "lockdown_on_trigger": True,
        "timeout_minutes": 30,
    },
    "daily_reminders": {
        "enabled": True,
        "time_utc": "09:00",
        "channel_id": 0,
        "role_ids": [],
    },
    "emojis": {
        "success": "✅",
        "error": "❌",
        "warning": "⚠️",
        "medical": "🩺",
        "ticket": "🎫",
        "shield": "🛡️",
        "reminder": "⏰",
        "lock": "🔒",
        "unlock": "🔓",
        "mail": "✉️",
    },
    "templates": {
        "generic_error": "{error_emoji} Something went wrong. Please try again.",
        "no_permission": "{error_emoji} You do not have permission to use this command.",
        "dm_sent": "{success_emoji} Your message was sent to {user}.",
        "dm_failed": "{error_emoji} I could not send a message to that user.",
        "raid_lockdown": "{lock_emoji} Anti-raid lockdown activated in {guild}.",
        "raid_unlock": "{unlock_emoji} The server lockdown has been lifted.",
        "automod_warning": "{warning_emoji} {user}, your message was removed by automoderation.",
        "ticket_created": "{ticket_emoji} Your ticket has been created: {channel}.",
        "ticket_exists": "{warning_emoji} You already have an open ticket: {channel}.",
        "ticket_closed": "{success_emoji} This ticket is being closed.",
        "medical_added": "{medical_emoji} Medical record saved for {patient}.",
        "medical_deleted": "{success_emoji} Medical record deleted for {patient}.",
        "medical_empty": "{warning_emoji} No medical record exists for {patient}.",
        "template_updated": "{success_emoji} Template `{key}` has been updated.",
        "config_updated": "{success_emoji} Configuration updated.",
        "panel_title": "{ticket_emoji} Lifeline Support",
        "panel_description": "Press the button below to open a private support ticket.",
        "reminder": "{reminder_emoji} Daily reminder for {role}: {message}",
        "raid_status": "{shield_emoji} Raid protection: **{enabled}**\nLockdown: **{lockdown}**\nRecent joins: **{joins}**",
        "invalid_template": "{error_emoji} That template key does not exist.",
    },
}


def load_config():
    if not CONFIG_PATH.exists():
        CONFIG_PATH.write_text(
            json.dumps(DEFAULT_CONFIG, indent=4),
            encoding="utf-8",
        )
        return DEFAULT_CONFIG.copy()

    try:
        with CONFIG_PATH.open("r", encoding="utf-8") as file:
            config = json.load(file)
    except json.JSONDecodeError:
        logger.exception("config.json is invalid")
        return DEFAULT_CONFIG.copy()

    merged = DEFAULT_CONFIG.copy()
    for key, value in config.items():
        if isinstance(value, dict) and isinstance(merged.get(key), dict):
            merged[key] = {**merged[key], **value}
        else:
            merged[key] = value
    return merged


def save_config(config):
    with CONFIG_PATH.open("w", encoding="utf-8") as file:
        json.dump(config, file, indent=4)


class SafeTemplate(dict):
    def __missing__(self, key):
        return "{" + key + "}"


def render_template(config, key, **values):
    template = config.get("templates", {}).get(key, "")
    values = SafeTemplate(values)
    try:
        return template.format_map(values)
    except (KeyError, ValueError):
        return template


def emoji(config, key):
    return config.get("emojis", {}).get(key, "")


def get_role(guild, role_id):
    if not role_id:
        return None
    return guild.get_role(int(role_id))


def get_channel(guild, channel_id):
    if not channel_id:
        return None
    return guild.get_channel(int(channel_id))


class TicketView(discord.ui.View):
    def __init__(self, bot):
        super().__init__(timeout=None)
        self.bot = bot

    @discord.ui.button(
        label="Open Ticket",
        style=discord.ButtonStyle.primary,
        emoji="🎫",
        custom_id="lifeline:ticket_open",
    )
    async def open_ticket(
        self,
        interaction: discord.Interaction,
        button: discord.ui.Button,
    ):
        if interaction.guild is None:
            await interaction.response.send_message(
                "Tickets can only be opened inside a server.",
                ephemeral=True,
            )
            return

        guild = interaction.guild
        existing = next(
            (
                channel
                for channel in guild.text_channels
                if channel.topic
                and channel.topic == f"ticket_owner:{interaction.user.id}"
            ),
            None,
        )

        if existing:
            await interaction.response.send_message(
                render_template(
                    self.bot.config,
                    "ticket_exists",
                    warning_emoji=emoji(self.bot.config, "warning"),
                    channel=existing.mention,
                ),
                ephemeral=True,
            )
            return

        access_role = get_role(
            guild,
            self.bot.config.get("ticket_access_role_id", 0),
        )
        category = get_channel(