Skip to content

Instantly share code, notes, and snippets.

@Amgelo563
Last active December 3, 2025 01:08
Show Gist options
  • Select an option

  • Save Amgelo563/55c68b14aaf5724a9c0977374e38a76b to your computer and use it in GitHub Desktop.

Select an option

Save Amgelo563/55c68b14aaf5724a9c0977374e38a76b to your computer and use it in GitHub Desktop.
Simple Discord bot script to add roles to a joining member, depending on account age.

Usage

  1. Add a config.json file:
{
  "token": "Discord token",
  "roles": {
    "1234": 20,
    "5678": 80
  },
  "reason": "Automatically added due to account age"
}

This will add the 1234 role to accounts that are at least 20 days old, and the 5678 role to accounts that are at least 80 days old (would also add the 1234 role).

  1. Run npm install.
  2. Run npm start.
import {
Client,
GatewayDispatchEvents,
GatewayIntentBits,
} from "@discordjs/core";
import { REST } from "@discordjs/rest";
import { WebSocketManager } from "@discordjs/ws";
import { DiscordSnowflake } from "@sapphire/snowflake";
import z from "zod";
import { readFileSync } from "fs";
const configSchema = z.object({
token: z.string(),
roles: z.record(z.string(), z.number()),
reason: z.string(),
});
let config;
try {
const rawConfig = readFileSync("./config.json", "utf8");
config = configSchema.parse(JSON.parse(rawConfig));
} catch (error) {
console.log("Error loading config:", error);
process.exit(1);
}
const rest = new REST({ version: "10" }).setToken(config.token);
const gateway = new WebSocketManager({
token: config.token,
intents: GatewayIntentBits.Guilds | GatewayIntentBits.GuildMembers,
rest,
});
const client = new Client({ rest, gateway });
client.on(
GatewayDispatchEvents.GuildMemberAdd,
async ({ data: member, api }) => {
if (member.user.bot) return;
const createdTimestamp = DiscordSnowflake.timestampFrom(member.user.id);
const daysSinceCreation = Math.floor(
(Date.now() - createdTimestamp) / (1000 * 60 * 60 * 24)
);
const roles = [];
for (const [role, days] of Object.entries(config.roles)) {
if (daysSinceCreation >= days) {
roles.push(role);
}
}
if (roles.length === 0) return;
// Use the idempotent PUT route to avoid overriding roles
for (const role of roles) {
await api.guilds.addRoleToMember(member.guild_id, member.user.id, role, {
reason: config.reason,
});
}
}
);
client.once(GatewayDispatchEvents.Ready, () => console.log("Ready!"));
gateway.connect();
{
"name": "roles-bot",
"version": "1.0.0",
"description": "Simple bot script to add a role to a member.",
"main": "index.js",
"scripts": {
"start": "node index.js"
},
"author": "Amgelo563",
"license": "MIT",
"dependencies": {
"@discordjs/core": "^2.4.0",
"@discordjs/rest": "^2.6.0",
"@discordjs/ws": "^2.0.4",
"@sapphire/snowflake": "^3.5.5",
"zod": "^4.1.12"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment