owengombas / discord.ts

🤖 Create your discord bot by using TypeScript and decorators!
https://owencalvin.github.io/discord.ts/
325 stars 40 forks source link

Fetching Prefix dynamically from mongoDB #15

Closed koester closed 3 years ago

koester commented 4 years ago

Hi,

I'm saving the prefix set by a guild in a MongoDB and want to fetch that prefix and forward that to @Discord.

I followed the example in the Readme and passed an async function as the first arg that queries the db and returns the correct string for the quild, or a default when no db record was found.

When I do this tho, the bot goes wild. It will start triggering on every message (with and without prefix, or with any prefix) and execute a command mulitple times in a row, even when it was only called once. Adding something like if (message.content[0] !== myPrefix) return; would not stop the bot from triggering multiple times for every message sent in the channel and DMs.

Removing the async fn getPrefix again fixes this behavior of the bot and it stops spamming.

Example:

async function getPrefix(message: Message) {
  try {
    const prefix: string = await getGuildPrefix(message); // gets findById(message.guild.id) with mongoose and returns the prefix field
    return prefix || '$'; // '$' is the default here
  } catch (err) {
    return '$';
  }
}

@Discord(getPrefix, {
  import: [
    join(__dirname, '../commands', '*.ts'),
    join(__dirname, '../events', '*.ts'),
  ],
})
export class DiscordApp { ... }

Am I missing something? This is probably also not the best way to go about this, since I would query the DB on every command/message/event. Where should I do this instead to persist the data and only query for the prefix once on startup? Should I not set a global prefix with @Discord but rather add a Guard or Rule to check for the prefix?

Thanks for your help

SteeledSlagle13 commented 3 years ago

you can cache/store the prefix in a singleton service

and in your getPrefix function import that service and get the prefix that way.

AndyClausen commented 3 years ago

It will start triggering on every message

Assuming that by "It" you mean getPrefix - it's supposed to trigger on every message. Otherwise, how will it know if it's a command or not? Just wanted to clear that up.

SteeledSlagle13 commented 3 years ago

Closing issue

If you need more help join the discord! :D https://discord.gg/VDjwu8E