Files
.gitignore
bot.py
requirements.txt
Code
3 276
bot.py
import json
import logging
import os
from datetime import timedelta
from pathlib import Path
from typing import Any, Optional
import discord
from discord import app_commands
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("honeypot")
TOKEN = os.getenv("DISCORD_TOKEN")
CONFIG_PATH = Path(os.getenv("HONEYPOT_CONFIG_FILE", "honeypot_config.json"))
ACTION_NAMES = ("ban", "kick", "timeout")
intents = discord.Intents.default()
intents.message_content = True
def load_settings() -> dict[str, dict[str, Any]]:
if not CONFIG_PATH.exists():
return {}
try:
with CONFIG_PATH.open("r", encoding="utf-8") as config_file:
data = json.load(config_file)
return data if isinstance(data, dict) else {}
except (OSError, json.JSONDecodeError):
logger.exception("Could not load honeypot settings from %s", CONFIG_PATH)
return {}
settings = load_settings()
recent_actions: dict[tuple[int, int], float] = {}
def save_settings() -> None:
CONFIG_PATH.parent.mkdir(parents=True, exist_ok=True)
temporary_path = CONFIG_PATH.with_suffix(f"{CONFIG_PATH.suffix}.tmp")
with temporary_path.open("w", encoding="utf-8") as config_file:
json.dump(settings, config_file, indent=2)
temporary_path.replace(CONFIG_PATH)
async def send_log(
guild: discord.Guild,
config: dict[str, Any],
embed: discord.Embed,
) -> None:
channel_id = config.get("log_channel_id")
if not channel_id:
return
channel = guild.get_channel(int(channel_id))
if not isinstance(channel, discord.TextChannel):
return
try:
await channel.send(embed=embed, allowed_mentions=discord.AllowedMentions.none())
except discord.HTTPException:
logger.exception("Could not send a honeypot log in guild %s", guild.id)
async def punish_member(
message: discord.Message,
action: str,
) -> None:
guild = message.guild
if guild is None:
return
reason = "Honeypot triggered"
try:
if action == "ban":
await guild.ban(message.author, reason=reason, delete_message_seconds=0)
elif action == "kick":
await guild.kick(message.author, reason=reason)
elif action == "timeout":
if not isinstance(message.author, discord.Member):
return
await message.author.timeout(timedelta(days=1), reason=reason)
except (discord.Forbidden, discord.HTTPException):
logger.exception(
"Could not apply honeypot action %s to %s in guild %s",
action,
message.author,
guild.id,
)
return
config = settings.get(str(guild.id), {})
embed = discord.Embed(
title="Honeypot triggered",
color=discord.Color.red(),
timestamp=discord.utils.utcnow(),
)
embed.add_field(
name="User",
value=f"{message.author.mention} (`{message.author.id}`)",
inline=False,
)
embed.add_field(name="Action", value=action, inline=True)
embed.add_field(name="Channel", value=message.channel.mention, inline=True)
if message.content:
content = message.content.replace("`", "ˋ")[:900]
embed.add_field(name="Message", value=content, inline=False)
await send_log(guild, config, embed)
class HoneypotBot(commands.Bot):
def __init__(self) -> None:
super().__init__(command_prefix="!", intents=intents)
self.synced = False
async def setup_hook(self) -> None:
self.tree.add_command(honeypot_group)
async def on_ready(self) -> None:
if not self.synced:
synced_commands = await self.tree.sync()
logger.info("Synced %d application commands", len(synced_commands))
self.synced = True
logger.info("Logged in as %s (%s)", self.user, self.user.id if self.user else "unknown")
async def on_message(self, message: discord.Message) -> None:
if message.guild is None or self.user is None or message.author.id == self.user.id:
return
config = settings.get(str(message.guild.id))
if not config or message.channel.id != int(config.get("channel_id", 0)):
await self.process_commands(message)
return
try:
await message.delete()
except (discord.Forbidden, discord.HTTPException):
logger.exception("Could not delete honeypot message %s", message.id)
action_key = (message.guild.id, message.author.id)
now = discord.utils.utcnow().timestamp()
last_action = recent_actions.get(action_key)
if last_action is None or now - float(last_action) >= 60:
recent_actions[action_key] = now
await punish_member(message, str(config.get("action", "ban")))
bot = HoneypotBot()
honeypot_group = app_commands.Group(
name="honeypot",
description="Configure a channel that catches unwanted users and bots.",
)
@honeypot_group.command(name="setup", description="Configure the honeypot channel and punishment.")
@app_commands.guild_only()
@app_commands.checks.has_permissions(administrator=True)
async def honeypot_setup(
interaction: discord.Interaction,
channel: discord.TextChannel,
action: str,
log_channel: Optional[discord.TextChannel] = None,
) -> None:
if action not in ACTION_NAMES:
await interaction.response.send_message(
"Action must be `ban`, `kick`, or `timeout`.", ephemeral=True
)
return
if interaction.guild is None:
return
settings[str(interaction.guild.id)] = {
"channel_id": channel.id,
"action": action,
"log_channel_id": log_channel.id if log_channel else None,
}
save_settings()
log_text = f" Logs will be sent to {log_channel.mention}." if log_channel else ""
await interaction.response.send_message(
f"Honeypot enabled in {channel.mention}. Triggered users will be **{action}d**.{log_text}\n"
"Give the bot Manage Messages and the selected moderation permission.",
ephemeral=True,
)
@honeypot_setup.autocomplete("action")
async def action_autocomplete(
interaction: discord.Interaction,
current: str,
) -> list[app_commands.Choice[str]]: