Skip to content

Commit

Permalink
fix(bot): handling of disallowed intents
Browse files Browse the repository at this point in the history
Discord.js throws an unhandlable rejection when the bot does not have a
required privileged intent.
This hacky changes listens to the unhandledRejection and tries to handle
it gracefully.

Related issue:
discordjs/discord.js#9621
  • Loading branch information
tabarra committed Jun 24, 2023
1 parent a6ebcc5 commit 416f3d0
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 5 deletions.
36 changes: 31 additions & 5 deletions core/components/DiscordBot/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,19 +54,29 @@ export default class DiscordBot {
guild: Discord.Guild | undefined;
guildName: string | undefined;
announceChannel: Discord.TextBasedChannel | undefined;
lastDisallowedIntentsError: number = 0;


constructor(txAdmin: TxAdmin, public config: DiscordBotConfigType) {
this.#txAdmin = txAdmin;

if (this.config.enabled) {
this.startBot().catch();
this.startBot().catch((e) => {});
}

// FIXME: Hacky solution to fix the issue with disallowed intents
// Remove this when issue below is fixed
// https://github.com/discordjs/discord.js/issues/9621
process.on('unhandledRejection', (error: Error) => {
if (error.message === 'Used disallowed intents') {
this.lastDisallowedIntentsError = Date.now();
}
});

//Cron
setInterval(() => {
if (this.config.enabled) {
this.updateStatus().catch();
this.updateStatus().catch((e) => {});
}
}, 60_000)
}
Expand Down Expand Up @@ -219,8 +229,22 @@ export default class DiscordBot {
//Setting up client object
this.#client = new Client(this.#clientOptions);

//Setup disallowed intents unhandled rejection watcher
const lastKnownDisallowedIntentsError = this.lastDisallowedIntentsError;
const disallowedIntentsWatcherId = setInterval(() => {
if (this.lastDisallowedIntentsError !== lastKnownDisallowedIntentsError) {
clearInterval(disallowedIntentsWatcherId);
return sendError(
`This bot does not have a required privileged intent.`,
{ code: 'DisallowedIntents' }
);
}
}, 250);


//Setup Ready listener
this.#client.on('ready', async () => {
clearInterval(disallowedIntentsWatcherId);
if (!this.#client?.isReady() || !this.#client.user) throw new Error(`ready event while not being ready`);

//Fetching guild
Expand Down Expand Up @@ -283,31 +307,33 @@ export default class DiscordBot {
}
}


// if previously registered by tx before v6 or other bot
this.guild.commands.set(slashCommands).catch(console.error);
this.#client.application?.commands.set([]).catch(console.error);

this.updateStatus().catch();
this.updateStatus().catch((e) => {});

console.ok(`Started and logged in as '${this.#client.user.tag}'`);
return resolve();
});

//Setup remaining event listeners
this.#client.on('error', (error) => {
clearInterval(disallowedIntentsWatcherId);
console.error(`Error from Discord.js client: ${error.message}`);
return reject(error);
});
this.#client.on('resume', () => {
console.verbose.ok('Connection with Discord API server resumed');
this.updateStatus().catch();
this.updateStatus().catch((e) => {});
});
this.#client.on('interactionCreate', interactionCreateHandler.bind(null, this.#txAdmin));
// this.#client.on('debug', console.verbose.debug);

//Start bot
this.#client.login(this.config.token).catch((error) => {
clearInterval(disallowedIntentsWatcherId);
console.error(`Discord login failed with error: ${(error as Error).message}`);
return reject(error);
});
Expand Down
3 changes: 3 additions & 0 deletions core/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,9 @@ process.stderr.on('error', (data) => { });

//Handle "the unexpected"
process.on('unhandledRejection', (err: Error) => {
//We are handling this inside the DiscordBot component
if(err.message === 'Used disallowed intents') return;

console.error('Ohh nooooo - unhandledRejection');
console.dir(err);
});
Expand Down
1 change: 1 addition & 0 deletions docs/dev_notes.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# TODO:
- [x] improve timeout handling of discord bot save
- [x] fix handling of disallowed intents
- [ ] attempt to update mysql2 and got
- [ ] improve the bot with dangerous permissions message
- [ ] merge PRs
Expand Down

0 comments on commit 416f3d0

Please sign in to comment.