3
0
Fork 0
mirror of https://github.com/ZeppelinBot/Zeppelin.git synced 2025-05-10 12:25:02 +00:00

Centralize DM logic, don't attempt DMs for an hour after a 20026 error

This commit is contained in:
Dragory 2020-08-21 03:44:38 +03:00
parent 1d4c32d8f9
commit 902be16ae8
No known key found for this signature in database
GPG key ID: 5F387BA66DF8AAC1
5 changed files with 60 additions and 16 deletions

View file

@ -0,0 +1,46 @@
import { MessageContent, MessageFile, User } from "eris";
import { createChunkedMessage, HOURS, isDiscordRESTError } from "../utils";
import { logger } from "../logger";
let dmsDisabled = false;
let dmsDisabledTimeout = null;
function disableDMs(duration) {
dmsDisabled = true;
clearTimeout(dmsDisabledTimeout);
dmsDisabledTimeout = setTimeout(() => (dmsDisabled = false), duration);
}
export class DMError extends Error {}
const error20026 = "The bot cannot currently send DMs";
export async function sendDM(user: User, content: MessageContent, source: string) {
if (dmsDisabled) {
throw new DMError(error20026);
}
logger.debug(`Sending ${source} DM to ${user.id}`);
try {
const dmChannel = await user.getDMChannel();
if (!dmChannel) {
throw new DMError("Unable to open DM channel");
}
if (typeof content === "string") {
await createChunkedMessage(dmChannel, content);
} else {
await dmChannel.createMessage(content);
}
} catch (e) {
if (isDiscordRESTError(e) && e.code === 20026) {
logger.warn(`Received error code 20026: ${e.message}`);
logger.warn("Disabling attempts to send DMs for 1 hour");
disableDMs(1 * HOURS);
throw new DMError(error20026);
}
throw e;
}
}