discordx-ts / discordx

🤖 Create a discord bot with TypeScript and Decorators!
https://discordx.js.org
Apache License 2.0
584 stars 50 forks source link

[Feature]: Owner guard #992

Closed ravener closed 3 months ago

ravener commented 3 months ago

Feature?

It'd be nice to have some guard for easily restricting commands/modules to only be usable for bot owners, something that perhaps makes use of client.application.owner (taking into account Teams) or even some generic @Guard(IsUser(id)) to limit it to some specific user(s).

Package

@discordx/utilities

samarmeena commented 3 months ago

@ravener could you make PR instead?

ravener commented 3 months ago

@samarmeena I could try but I've only been playing with discordx for like 2 days, and which approach would you prefer?

VictoriqueMoe commented 3 months ago

you want a guard to only allow bot owners/user ids? ok, i can do this

samarmeena commented 3 months ago

@ravener use @PermissionGuard guard, allow only administrator to access the commaand.

samarmeena commented 3 months ago

See permissions at https://discord.com/developers/docs/topics/permissions#permissions-bitwise-permission-flags there are permissions like manage guild and administrator useful.

samarmeena commented 3 months ago

you could do

@Guard(
  IsGuildUser(({ guild, user }) => {
    if (!guild || !user) {
      return false;
    }

    const member = guild.members.cache.get(user.id);
    if (!member) {
      return false;
    }

    return member.permissions.has(PermissionsBitField.Flags.Administrator);
  }),
)

or

@Guard(
  IsGuildUser(({ user }) => {
    if (!user) {
      return false;
    }

    return user.id === "ADMIN_USER_ID";
  }),
)
samarmeena commented 3 months ago

As you wanted to check client application owner, this will be useful.

@Guard(
  IsGuildUser(({ client, user }) => {
    if (!user) {
      return false;
    }

    return client.application?.owner?.id === user.id;
  }),
)
samarmeena commented 3 months ago

Even better this way,

import { IsGuardUserCallback, IsGuildUser } from "@discordx/utilities";
import { Events } from "discord.js";
import {
  ArgsOf,
  Discord,
  Guard,
  On,
  SimpleCommand,
  SimpleCommandMessage,
} from "discordx";

const OwnerOnly: IsGuardUserCallback = ({ client, user }) => {
  if (!user) {
    return false;
  }

  return client.application?.owner?.id === user.id;
};

@Discord()
@Guard(IsGuildUser(OwnerOnly))
class Example {
  @On({ event: Events.MessageCreate })
  message([message]: ArgsOf<"messageCreate">) {
    //...
  }

  @SimpleCommand({ name: "hello" })
  hello(command: SimpleCommandMessage) {
    //...
  }
}