max Facts

Can you create me a discord bot that is called AWA and it will ping a random person in the server at random times with the message: There are tickets currently aging in the queue. Please check to make sure you are set to available in AWA.

Kodari AI
KodariSep 1 at 1:09 am 1
AWATicketPinger
A Discord bot named AWA that randomly pings a server member at random intervals with a reminder message about aging tickets in the queue. It selects a random user from the server, sends the predefined text, and schedules the next ping with randomized timing. Built with discord.py, it includes startup readiness, error handling, and configurable ping frequency.
  1. Create the AWA bot with a cancellable random-notification loop and safe user-only mentions.

  2. Add environment-based token and timing configuration without hardcoding secrets.

  3. Add dependency, setup, and required Discord intent documentation.

Created the AWA Discord bot with:

  • Random notification timing configurable via .env

  • Random selection of a non-bot member across available servers

  • Safe user-only mentions

  • Channel permission checks

  • !awa_status command

  • Logging and command error handling

  • .env.example, requirements.txt, .gitignore, and setup instructions

Set the bot’s Discord username to AWA in the Developer Portal, enable the Server Members and Message Content intents, then run:

Shell
python -m pip install -r requirements.txt
python bot.py
Kodari can make mistakes. Review important code before using.
Files
.gitignore
bot.py
README.md
requirements.txt
Code
4 198
bot.py
import asyncio
import logging
import os
import random
from contextlib import suppress

import discord
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("awa")

TOKEN = os.getenv("DISCORD_TOKEN")
NOTIFICATION_MESSAGE = (
    "There are tickets currently aging in the queue. Please check to make sure "
    "you are set to available in AWA."
)


def read_delay_setting(name: str, default: int) -> int:
    value = os.getenv(name)
    if value is None:
        return default

    try:
        delay = int(value)
    except ValueError:
        logger.warning("%s must be a whole number; using %s", name, default)
        return default

    if delay < 1:
        logger.warning("%s must be at least 1 second; using %s", name, default)
        return default
    return delay


MIN_DELAY_SECONDS = read_delay_setting("MIN_DELAY_SECONDS", 1800)
MAX_DELAY_SECONDS = read_delay_setting("MAX_DELAY_SECONDS", 7200)
if MAX_DELAY_SECONDS < MIN_DELAY_SECONDS:
    logger.warning("MAX_DELAY_SECONDS is below MIN_DELAY_SECONDS; using the minimum")
    MAX_DELAY_SECONDS = MIN_DELAY_SECONDS


intents = discord.Intents.default()
intents.members = True
intents.message_content = True


class AwaBot(commands.Bot):
    def __init__(self) -> None:
        super().__init__(command_prefix="!", intents=intents)
        self.notification_task: asyncio.Task[None] | None = None

    async def setup_hook(self) -> None:
        self.notification_task = asyncio.create_task(self.notification_loop())

    async def close(self) -> None:
        if self.notification_task is not None:
            self.notification_task.cancel()
            with suppress(asyncio.CancelledError):
                await self.notification_task
        await super().close()

    @staticmethod
    def can_send_in(channel: discord.TextChannel, guild: discord.Guild) -> bool:
        member = guild.me
        if member is None:
            return False

        permissions = channel.permissions_for(member)
        return permissions.view_channel and permissions.send_messages

    async def send_random_notification(self) -> None:
        available_guilds: list[
            tuple[discord.Guild, list[discord.Member], list[discord.TextChannel]]
        ] = []

        for guild in self.guilds:
            members = [member for member in guild.members if not member.bot]
            channels = [
                channel
                for channel in guild.text_channels
                if self.can_send_in(channel, guild)
            ]
            if members and channels:
                available_guilds.append((guild, members, channels))

        if not available_guilds:
            logger.warning("No guild has both an eligible member and writable channel")
            return

        guild, members, channels = random.choice(available_guilds)
        member = random.choice(members)
        channel = random.choice(channels)
        content = f"{member.mention} {NOTIFICATION_MESSAGE}"
        allowed_mentions = discord.AllowedMentions(
            users=[member], everyone=False, roles=False, replied_user=False
        )

        try:
            await channel.send(content, allowed_mentions=allowed_mentions)
            logger.info(
                "Sent notification in %s (%s) mentioning %s",
                guild.name,
                channel.name,
                member,
            )
        except discord.HTTPException:
            logger.exception("Discord rejected the notification for guild %s", guild.id)

    async def notification_loop(self) -> None:
        await self.wait_until_ready()
        while not self.is_closed():
            delay = random.randint(MIN_DELAY_SECONDS, MAX_DELAY_SECONDS)
            logger.info("Next notification scheduled in %s seconds", delay)
            await asyncio.sleep(delay)

            if self.is_ready():
                await self.send_random_notification()


bot = AwaBot()


@bot.event
async def on_ready() -> None:
    if bot.user is not None:
        logger.info("AWA is online as %s in %s server(s)", bot.user, len(bot.guilds))


@bot.command(name="awa_status")
@commands.guild_only()
@commands.cooldown(1, 10, commands.BucketType.user)
async def awa_status(ctx: commands.Context[commands.Bot]) -> None:
    await ctx.send(
        f"AWA is online. Random notifications occur every "
        f"{MIN_DELAY_SECONDS}-{MAX_DELAY_SECONDS} seconds."
    )


@bot.event
async def on_command_error(
    ctx: commands.Context[commands.Bot], error: commands.CommandError
) -> None:
    if isinstance(error, commands.CommandNotFound):
        return
    if isinstance(error, commands.CommandOnCooldown):
        await ctx.send(f"Please wait {error.retry_after:.1f} more seconds before using that.")
        return
    if isinstance(error, commands.NoPrivateMessage):
        await ctx.send("That command can only be used in a server.")
        return

    logger.exception("Command error", exc_info=error)


if not TOKEN:
    raise RuntimeError("DISCORD_TOKEN is not set. Add it to a .env file.")

bot.run(TOKEN)