Recipe: a link filter that cleans up

Removes messages that link to domains you did not allow, in the channels you choose, and tells the author why. About 40 lines with the TypeScript SDK.

What it needs

  • Intents: GUILD_MESSAGES (to read new messages).
  • Permissions in the channels it watches: View channels, Send messages and Manage messages (to delete others' messages).
  • The built-in automod already handles mention spam, raids and links from brand-new accounts. This bot is for your own rule: an allow-list of domains.

The code

import { Client, Intents } from '@mnema-xyz/bot-sdk'

const ALLOWED = new Set(['example.org', 'wiki.example.org'])
const WATCHED = new Set((process.env.WATCHED_CHANNELS ?? '').split(',').filter(Boolean))

const client = new Client({
  baseUrl: process.env.MNEMA_URL ?? 'https://talk.example.org',
  token: process.env.MNEMA_TOKEN ?? '',
  intents: Intents.GuildMessages,
})

function forbiddenLink(text: string): string | null {
  for (const match of text.matchAll(/https?:\/\/([^/\s]+)/gi)) {
    const host = (match[1] ?? '').toLowerCase()
    if (![...ALLOWED].some((d) => host === d || host.endsWith(`.${d}`))) return host
  }
  return null
}

client.on('messageCreate', async (m) => {
  if (m.is_bot || !WATCHED.has(m.channel_id)) return
  const host = forbiddenLink(m.content)
  if (!host) return
  await client.rest.deleteMessage(m.channel_id, m.id)
  await client.rest.createMessage(m.channel_id, {
    content: `@${m.username} links to ${host} are not allowed here. Ask a moderator if it should be.`,
    allowed_mentions: { users: [m.user_id] },
  })
})

client.on('error', (err) => console.error(err))
await client.connect()

Notes

  • allowed_mentions.users limits the notification to the author, whatever else the text contains. See allowed_mentions.
  • Deleting another member's message needs Manage messages in that channel; without it the call answers 403 with code 50013.
  • Bots cannot time out, kick or ban members: no bot endpoint manages members, by design. Leave sanctions to your moderators and the built-in commands.

Something wrong on this page? Tell us.