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)