melonly logomelonly logo
melonly logo
Dashboard
Log in

Examples

Ready-to-use code for common bot features: logging punishments, shift buttons, on-shift lists and player lookups.

How Do These Examples Work?

Each example is a small piece of a Discord bot written with discord.js. They all share this helper, which sends a request with your token and throws if it fails:

async function melonly(method, path, body) {
  const response = await fetch(`https://api.melonly.com/api/v1${path}`, {
    method,
    headers: {
      Authorization: `Bearer ${process.env.MELONLY_TOKEN}`,
      "Content-Type": "application/json",
    },
    body: body && JSON.stringify(body),
  });
  const json = await response.json();
  if (!response.ok) throw new Error(json.error.message);
  return json;
}

Store your token in the MELONLY_TOKEN environment variable. See Authentication.

Find the Staff Member Behind a Command

Writes run as a staff member, so most commands start by turning the Discord user who ran them into a member ID. See How Writes Work.

async function memberId(user) {
  const { data } = await melonly("GET", `/server/members/discord/${user.id}`);
  return data.id;
}

If the person isn't in your Melonly server, this throws member not found. That's a good point to tell them they're not staff.

Log a Punishment From a Slash Command

A /warn command that creates a warning as the moderator who ran it. Melonly posts it to your log channel and DMs the player, just like the Mod Panel.

client.on("interactionCreate", async (interaction) => {
  if (!interaction.isChatInputCommand() || interaction.commandName !== "warn") return;
  await interaction.deferReply({ ephemeral: true });

  try {
    const { data } = await melonly("POST", "/server/logs", {
      type: 0,
      username: interaction.options.getString("username"),
      text: interaction.options.getString("reason"),
      createdBy: await memberId(interaction.user),
    });
    await interaction.editReply(`Warned ${data.username}.`);
  } catch (error) {
    await interaction.editReply(`Couldn't warn them: ${error.message}`);
  }
});

Use type: 1 for a kick and type: 2 for a ban. For your server's custom types, get the typeId from List Log Types and send it with type: 5.

Start and End Shifts With Buttons

Two buttons that start and end the clicker's shift. Discord shift roles, nickname prefixes and your shift channel all update as usual.

client.on("interactionCreate", async (interaction) => {
  if (!interaction.isButton()) return;
  const member = await memberId(interaction.user);

  if (interaction.customId === "shift-start") {
    await melonly("POST", "/server/shifts", { memberId: member });
    await interaction.reply({ content: "You're on shift.", ephemeral: true });
  }

  if (interaction.customId === "shift-end") {
    const { data: [shift] } = await melonly("GET", `/server/shifts/user/${member}?active=true`);
    if (!shift) return interaction.reply({ content: "You're not on shift.", ephemeral: true });

    await melonly("POST", `/server/shifts/${shift.id}/end`);
    await interaction.reply({ content: "Shift ended.", ephemeral: true });
  }
});

If the member is already on shift, the API returns a 409 and melonly throws, so wrap the calls in try and reply with error.message like the /warn example.

Show Who's on Shift

A /onshift command that lists everyone currently on shift.

client.on("interactionCreate", async (interaction) => {
  if (!interaction.isChatInputCommand() || interaction.commandName !== "onshift") return;

  const { data: shifts } = await melonly("GET", "/server/shifts?active=true&pageSize=100");
  if (shifts.length === 0) return interaction.reply("Nobody is on shift.");

  const lines = await Promise.all(
    shifts.map(async (shift) => {
      const { data } = await melonly("GET", `/server/members/${shift.memberId}/discord`);
      return `<@${data.discordId}>, on since <t:${Math.floor(shift.createdAt / 1000)}:R>`;
    }),
  );
  await interaction.reply(lines.join("\n"));
});

Look Up a Player's Record

A /record command that shows a player's recent logs. Looking them up by Roblox ID also finds logs from before they changed their username.

client.on("interactionCreate", async (interaction) => {
  if (!interaction.isChatInputCommand() || interaction.commandName !== "record") return;
  const robloxId = interaction.options.getString("roblox_id");
  const { data: logs, total } = await melonly("GET", `/server/logs/roblox/${robloxId}?pageSize=5`);
  if (total === 0) return interaction.reply("No logs for that player.");

  const lines = logs.map((log) => `<t:${Math.floor(log.createdAt / 1000)}:d> ${log.text}`);
  await interaction.reply(`${total} logs. Latest:\n${lines.join("\n")}`);
});

Where to Go Next

Need help?

Still have questions? Join our Discord server for support from the Melonly Team.