Files
.gitignore
bot.py
README.md
requirements.txt
Code
4 116
bot.py
import asyncio
import logging
import os
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("jackson-state-bot")
intents = discord.Intents.default()
intents.members = True
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents, help_command=None)
@bot.event
async def on_ready() -> None:
activity = discord.Activity(type=discord.ActivityType.watching, name="Jackson State")
await bot.change_presence(status=discord.Status.online, activity=activity)
logger.info("Logged in as %s", bot.user)
@bot.command(name="messagealll")
@commands.guild_only()
@commands.cooldown(1, 60, commands.BucketType.guild)
@commands.has_guild_permissions(administrator=True)
async def message_all(ctx: commands.Context, *, message: str) -> None:
"""DM a plain-text message to every non-bot member of this server."""
sent = 0
failed = 0
await ctx.send("Starting the plain-text message delivery...")
async for member in ctx.guild.fetch_members(limit=None):
if member.bot:
continue
try:
await member.send(message)
sent += 1
except (discord.Forbidden, discord.HTTPException, discord.NotFound):
failed += 1
await asyncio.sleep(1)
await ctx.send(f"Finished. Sent: {sent}; unavailable or failed: {failed}.")
@message_all.error
async def message_all_error(ctx: commands.Context, error: commands.CommandError) -> None:
if isinstance(error, commands.MissingRequiredArgument):
await ctx.send("Usage: `!messagealll <message>`")
elif isinstance(error, commands.MissingPermissions):
await ctx.send("You need Administrator permission to use this command.")
elif isinstance(error, commands.CommandOnCooldown):
await ctx.send(f"Try again in {error.retry_after:.0f} seconds.")
elif isinstance(error, commands.NoPrivateMessage):
await ctx.send("This command can only be used in a server.")
else:
logger.exception("Error while running !messagealll", exc_info=error)
await ctx.send("The message could not be delivered.")
token = os.getenv("DISCORD_TOKEN")
if not token:
raise RuntimeError("DISCORD_TOKEN is missing from the environment.")
bot.run(token)