2021-06-30 04:56:56 +02:00
|
|
|
import { MessagePayload, User } from "discord.js";
|
2020-08-21 03:44:38 +03:00
|
|
|
import { logger } from "../logger";
|
2021-06-30 23:06:02 +02:00
|
|
|
import { createChunkedMessage, HOURS, isDiscordAPIError } from "../utils";
|
2020-11-09 20:03:57 +02:00
|
|
|
import Timeout = NodeJS.Timeout;
|
2020-08-21 03:44:38 +03:00
|
|
|
|
|
|
|
let dmsDisabled = false;
|
2020-11-09 20:03:57 +02:00
|
|
|
let dmsDisabledTimeout: Timeout;
|
2020-08-21 03:44:38 +03:00
|
|
|
|
|
|
|
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";
|
|
|
|
|
2021-06-30 04:56:56 +02:00
|
|
|
export async function sendDM(user: User, content: string | MessagePayload, source: string) {
|
2020-08-21 03:44:38 +03:00
|
|
|
if (dmsDisabled) {
|
|
|
|
throw new DMError(error20026);
|
|
|
|
}
|
|
|
|
|
|
|
|
logger.debug(`Sending ${source} DM to ${user.id}`);
|
|
|
|
|
|
|
|
try {
|
|
|
|
if (typeof content === "string") {
|
2021-05-31 03:30:55 +02:00
|
|
|
await createChunkedMessage(user, content);
|
2020-08-21 03:44:38 +03:00
|
|
|
} else {
|
2021-05-31 03:30:55 +02:00
|
|
|
await user.send(content);
|
2020-08-21 03:44:38 +03:00
|
|
|
}
|
|
|
|
} catch (e) {
|
2021-06-30 23:06:02 +02:00
|
|
|
if (isDiscordAPIError(e) && e.code === 20026) {
|
2020-08-21 03:44:38 +03:00
|
|
|
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;
|
|
|
|
}
|
|
|
|
}
|