mirror of
https://github.com/ZeppelinBot/Zeppelin.git
synced 2025-05-21 16:55:03 +00:00
parent
517ce4f52f
commit
7e8ffb9ee3
161 changed files with 659 additions and 534 deletions
|
@ -14,7 +14,7 @@ export class Queue {
|
|||
}
|
||||
|
||||
public add(fn) {
|
||||
const promise = new Promise((resolve) => {
|
||||
const promise = new Promise(resolve => {
|
||||
this.queue.push(async () => {
|
||||
await fn();
|
||||
resolve(undefined);
|
||||
|
@ -35,7 +35,7 @@ export class Queue {
|
|||
}
|
||||
|
||||
const fn = this.queue.shift()!;
|
||||
new Promise((resolve) => {
|
||||
new Promise(resolve => {
|
||||
// Either fn() completes or the timeout is reached
|
||||
fn().then(resolve);
|
||||
setTimeout(resolve, this.timeout);
|
||||
|
|
|
@ -42,7 +42,7 @@ export class QueuedEventEmitter {
|
|||
const listeners = [...(this.listeners.get(eventName) || []), ...(this.listeners.get("*") || [])];
|
||||
|
||||
let promise: Promise<any> = Promise.resolve();
|
||||
listeners.forEach((listener) => {
|
||||
listeners.forEach(listener => {
|
||||
promise = this.queue.add(listener.bind(null, ...args));
|
||||
});
|
||||
|
||||
|
|
|
@ -27,7 +27,7 @@ const INITIAL_REGEX_TIMEOUT = 1000; // ms
|
|||
const INITIAL_REGEX_TIMEOUT_DURATION = 30 * SECONDS;
|
||||
const FINAL_REGEX_TIMEOUT = 750; // ms
|
||||
|
||||
const regexTimeoutUpgradePromise = new Promise((resolve) => setTimeout(resolve, INITIAL_REGEX_TIMEOUT_DURATION));
|
||||
const regexTimeoutUpgradePromise = new Promise(resolve => setTimeout(resolve, INITIAL_REGEX_TIMEOUT_DURATION));
|
||||
|
||||
let newWorkerTimeout = INITIAL_REGEX_TIMEOUT;
|
||||
regexTimeoutUpgradePromise.then(() => (newWorkerTimeout = FINAL_REGEX_TIMEOUT));
|
||||
|
|
|
@ -33,17 +33,17 @@ function simpleDiscordAPIRequest(bearerToken, path): Promise<any> {
|
|||
Authorization: `Bearer ${bearerToken}`,
|
||||
},
|
||||
},
|
||||
(res) => {
|
||||
res => {
|
||||
if (res.statusCode !== 200) {
|
||||
reject(new Error(`Discord API error ${res.statusCode}`));
|
||||
return;
|
||||
}
|
||||
|
||||
res.on("data", (data) => resolve(JSON.parse(data)));
|
||||
res.on("data", data => resolve(JSON.parse(data)));
|
||||
},
|
||||
);
|
||||
|
||||
request.on("error", (err) => reject(err));
|
||||
request.on("error", err => reject(err));
|
||||
});
|
||||
}
|
||||
|
||||
|
|
|
@ -20,21 +20,21 @@ function formatConfigSchema(schema) {
|
|||
if (schema.name.startsWith("Nullable<")) {
|
||||
return `Nullable<${formatConfigSchema(schema.types[0])}>`;
|
||||
} else {
|
||||
return schema.types.map((t) => formatConfigSchema(t)).join(" | ");
|
||||
return schema.types.map(t => formatConfigSchema(t)).join(" | ");
|
||||
}
|
||||
} else if (schema._tag === "IntersectionType") {
|
||||
return schema.types.map((t) => formatConfigSchema(t)).join(" & ");
|
||||
return schema.types.map(t => formatConfigSchema(t)).join(" & ");
|
||||
} else {
|
||||
return schema.name;
|
||||
}
|
||||
}
|
||||
|
||||
export function initDocs(app: express.Express) {
|
||||
const docsPlugins = guildPlugins.filter((plugin) => plugin.showInDocs);
|
||||
const docsPlugins = guildPlugins.filter(plugin => plugin.showInDocs);
|
||||
|
||||
app.get("/docs/plugins", (req: express.Request, res: express.Response) => {
|
||||
res.json(
|
||||
docsPlugins.map((plugin) => {
|
||||
docsPlugins.map(plugin => {
|
||||
const thinInfo = plugin.info ? { prettyName: plugin.info.prettyName } : {};
|
||||
return {
|
||||
name: plugin.name,
|
||||
|
@ -54,7 +54,7 @@ export function initDocs(app: express.Express) {
|
|||
const name = plugin.name;
|
||||
const info = plugin.info || {};
|
||||
|
||||
const commands = (plugin.commands || []).map((cmd) => ({
|
||||
const commands = (plugin.commands || []).map(cmd => ({
|
||||
trigger: cmd.trigger,
|
||||
permission: cmd.permission,
|
||||
signature: cmd.signature,
|
||||
|
|
|
@ -66,7 +66,10 @@ export class ApiLogins extends BaseRepository {
|
|||
token: hashedToken,
|
||||
user_id: userId,
|
||||
logged_in_at: moment.utc().format(DBDateFormat),
|
||||
expires_at: moment.utc().add(1, "day").format(DBDateFormat),
|
||||
expires_at: moment
|
||||
.utc()
|
||||
.add(1, "day")
|
||||
.format(DBDateFormat),
|
||||
});
|
||||
|
||||
return `${loginId}.${token}`;
|
||||
|
|
|
@ -22,7 +22,7 @@ export class ApiUserInfo extends BaseRepository {
|
|||
}
|
||||
|
||||
update(id, data: ApiUserInfoData) {
|
||||
return connection.transaction(async (entityManager) => {
|
||||
return connection.transaction(async entityManager => {
|
||||
const repo = entityManager.getRepository(ApiUserInfoEntity);
|
||||
|
||||
const existingInfo = await repo.findOne({ where: { id } });
|
||||
|
|
|
@ -41,7 +41,11 @@ export class Configs extends BaseRepository {
|
|||
}
|
||||
|
||||
getActiveLargerThanId(id) {
|
||||
return this.configs.createQueryBuilder().where("id > :id", { id }).andWhere("is_active = 1").getMany();
|
||||
return this.configs
|
||||
.createQueryBuilder()
|
||||
.where("id > :id", { id })
|
||||
.andWhere("is_active = 1")
|
||||
.getMany();
|
||||
}
|
||||
|
||||
async hasConfig(key) {
|
||||
|
@ -61,7 +65,7 @@ export class Configs extends BaseRepository {
|
|||
}
|
||||
|
||||
async saveNewRevision(key, config, editedBy) {
|
||||
return connection.transaction(async (entityManager) => {
|
||||
return connection.transaction(async entityManager => {
|
||||
const repo = entityManager.getRepository(Config);
|
||||
// Mark all old revisions inactive
|
||||
await repo.update({ key }, { is_active: false });
|
||||
|
|
|
@ -132,7 +132,7 @@ export class GuildCases extends BaseGuildRepository {
|
|||
}
|
||||
|
||||
async softDelete(id: number, deletedById: string, deletedByName: string, deletedByText: string) {
|
||||
return connection.transaction(async (entityManager) => {
|
||||
return connection.transaction(async entityManager => {
|
||||
const cases = entityManager.getRepository(Case);
|
||||
const caseNotes = entityManager.getRepository(CaseNote);
|
||||
|
||||
|
|
|
@ -45,11 +45,19 @@ const DELETE_UNUSED_COUNTER_TRIGGERS_AFTER = 1 * DAYS;
|
|||
const MAX_COUNTER_VALUE = 2147483647; // 2^31-1, for MySQL INT
|
||||
|
||||
async function deleteCountersMarkedToBeDeleted(): Promise<void> {
|
||||
await getRepository(Counter).createQueryBuilder().where("delete_at <= NOW()").delete().execute();
|
||||
await getRepository(Counter)
|
||||
.createQueryBuilder()
|
||||
.where("delete_at <= NOW()")
|
||||
.delete()
|
||||
.execute();
|
||||
}
|
||||
|
||||
async function deleteTriggersMarkedToBeDeleted(): Promise<void> {
|
||||
await getRepository(CounterTrigger).createQueryBuilder().where("delete_at <= NOW()").delete().execute();
|
||||
await getRepository(CounterTrigger)
|
||||
.createQueryBuilder()
|
||||
.where("delete_at <= NOW()")
|
||||
.delete()
|
||||
.execute();
|
||||
}
|
||||
|
||||
setInterval(deleteCountersMarkedToBeDeleted, 1 * HOURS);
|
||||
|
@ -110,7 +118,10 @@ export class GuildCounters extends BaseGuildRepository {
|
|||
return;
|
||||
}
|
||||
|
||||
const deleteAt = moment.utc().add(DELETE_UNUSED_COUNTERS_AFTER, "ms").format(DBDateFormat);
|
||||
const deleteAt = moment
|
||||
.utc()
|
||||
.add(DELETE_UNUSED_COUNTERS_AFTER, "ms")
|
||||
.format(DBDateFormat);
|
||||
await this.counters.update(
|
||||
{
|
||||
guild_id: this.guildId,
|
||||
|
@ -124,7 +135,11 @@ export class GuildCounters extends BaseGuildRepository {
|
|||
}
|
||||
|
||||
async deleteCountersMarkedToBeDeleted(): Promise<void> {
|
||||
await this.counters.createQueryBuilder().where("delete_at <= NOW()").delete().execute();
|
||||
await this.counters
|
||||
.createQueryBuilder()
|
||||
.where("delete_at <= NOW()")
|
||||
.delete()
|
||||
.execute();
|
||||
}
|
||||
|
||||
async changeCounterValue(id: number, channelId: string | null, userId: string | null, change: number): Promise<void> {
|
||||
|
@ -216,7 +231,10 @@ export class GuildCounters extends BaseGuildRepository {
|
|||
}
|
||||
|
||||
async markAllTriggersTobeDeleted() {
|
||||
const deleteAt = moment.utc().add(DELETE_UNUSED_COUNTER_TRIGGERS_AFTER, "ms").format(DBDateFormat);
|
||||
const deleteAt = moment
|
||||
.utc()
|
||||
.add(DELETE_UNUSED_COUNTER_TRIGGERS_AFTER, "ms")
|
||||
.format(DBDateFormat);
|
||||
await this.counterTriggers.update(
|
||||
{},
|
||||
{
|
||||
|
@ -226,7 +244,11 @@ export class GuildCounters extends BaseGuildRepository {
|
|||
}
|
||||
|
||||
async deleteTriggersMarkedToBeDeleted(): Promise<void> {
|
||||
await this.counterTriggers.createQueryBuilder().where("delete_at <= NOW()").delete().execute();
|
||||
await this.counterTriggers
|
||||
.createQueryBuilder()
|
||||
.where("delete_at <= NOW()")
|
||||
.delete()
|
||||
.execute();
|
||||
}
|
||||
|
||||
async initCounterTrigger(
|
||||
|
@ -242,7 +264,7 @@ export class GuildCounters extends BaseGuildRepository {
|
|||
throw new Error(`Invalid comparison value: ${comparisonValue}`);
|
||||
}
|
||||
|
||||
return connection.transaction(async (entityManager) => {
|
||||
return connection.transaction(async entityManager => {
|
||||
const existing = await entityManager.findOne(CounterTrigger, {
|
||||
counter_id: counterId,
|
||||
comparison_op: comparisonOp,
|
||||
|
@ -286,7 +308,7 @@ export class GuildCounters extends BaseGuildRepository {
|
|||
channelId = channelId || "0";
|
||||
userId = userId || "0";
|
||||
|
||||
return connection.transaction(async (entityManager) => {
|
||||
return connection.transaction(async entityManager => {
|
||||
const previouslyTriggered = await entityManager.findOne(CounterTriggerState, {
|
||||
trigger_id: counterTrigger.id,
|
||||
user_id: userId!,
|
||||
|
@ -334,7 +356,7 @@ export class GuildCounters extends BaseGuildRepository {
|
|||
async checkAllValuesForTrigger(
|
||||
counterTrigger: CounterTrigger,
|
||||
): Promise<Array<{ channelId: string; userId: string }>> {
|
||||
return connection.transaction(async (entityManager) => {
|
||||
return connection.transaction(async entityManager => {
|
||||
const matchingValues = await entityManager
|
||||
.createQueryBuilder(CounterValue, "cv")
|
||||
.leftJoin(
|
||||
|
@ -351,7 +373,7 @@ export class GuildCounters extends BaseGuildRepository {
|
|||
if (matchingValues.length) {
|
||||
await entityManager.insert(
|
||||
CounterTriggerState,
|
||||
matchingValues.map((row) => ({
|
||||
matchingValues.map(row => ({
|
||||
trigger_id: counterTrigger.id,
|
||||
channelId: row.channel_id,
|
||||
userId: row.user_id,
|
||||
|
@ -359,7 +381,7 @@ export class GuildCounters extends BaseGuildRepository {
|
|||
);
|
||||
}
|
||||
|
||||
return matchingValues.map((row) => ({
|
||||
return matchingValues.map(row => ({
|
||||
channelId: row.channel_id,
|
||||
userId: row.user_id,
|
||||
}));
|
||||
|
@ -385,7 +407,7 @@ export class GuildCounters extends BaseGuildRepository {
|
|||
channelId = channelId || "0";
|
||||
userId = userId || "0";
|
||||
|
||||
return connection.transaction(async (entityManager) => {
|
||||
return connection.transaction(async entityManager => {
|
||||
const reverseOp = getReverseComparisonOp(counterTrigger.comparison_op);
|
||||
const matchingValue = await entityManager
|
||||
.createQueryBuilder(CounterValue, "cv")
|
||||
|
@ -423,7 +445,7 @@ export class GuildCounters extends BaseGuildRepository {
|
|||
async checkAllValuesForReverseTrigger(
|
||||
counterTrigger: CounterTrigger,
|
||||
): Promise<Array<{ channelId: string; userId: string }>> {
|
||||
return connection.transaction(async (entityManager) => {
|
||||
return connection.transaction(async entityManager => {
|
||||
const reverseOp = getReverseComparisonOp(counterTrigger.comparison_op);
|
||||
const matchingValues: Array<{
|
||||
id: string;
|
||||
|
@ -450,11 +472,11 @@ export class GuildCounters extends BaseGuildRepository {
|
|||
|
||||
if (matchingValues.length) {
|
||||
await entityManager.delete(CounterTriggerState, {
|
||||
id: In(matchingValues.map((v) => v.triggerStateId)),
|
||||
id: In(matchingValues.map(v => v.triggerStateId)),
|
||||
});
|
||||
}
|
||||
|
||||
return matchingValues.map((row) => ({
|
||||
return matchingValues.map(row => ({
|
||||
channelId: row.channel_id,
|
||||
userId: row.user_id,
|
||||
}));
|
||||
|
|
|
@ -46,12 +46,12 @@ export class GuildLogs extends events.EventEmitter {
|
|||
}
|
||||
|
||||
isLogIgnored(type: LogType, ignoreId: any) {
|
||||
return this.ignoredLogs.some((info) => type === info.type && ignoreId === info.ignoreId);
|
||||
return this.ignoredLogs.some(info => type === info.type && ignoreId === info.ignoreId);
|
||||
}
|
||||
|
||||
clearIgnoredLog(type: LogType, ignoreId: any) {
|
||||
this.ignoredLogs.splice(
|
||||
this.ignoredLogs.findIndex((info) => type === info.type && ignoreId === info.ignoreId),
|
||||
this.ignoredLogs.findIndex(info => type === info.type && ignoreId === info.ignoreId),
|
||||
1,
|
||||
);
|
||||
}
|
||||
|
|
|
@ -19,7 +19,7 @@ export class GuildMemberTimezones extends BaseGuildRepository {
|
|||
}
|
||||
|
||||
async set(memberId, timezone: string) {
|
||||
await connection.transaction(async (entityManager) => {
|
||||
await connection.transaction(async entityManager => {
|
||||
const repo = entityManager.getRepository(MemberTimezone);
|
||||
const existingRow = await repo.findOne({
|
||||
guild_id: this.guildId,
|
||||
|
|
|
@ -35,7 +35,12 @@ export class GuildMutes extends BaseGuildRepository {
|
|||
}
|
||||
|
||||
async addMute(userId, expiryTime, rolesToRestore?: string[]): Promise<Mute> {
|
||||
const expiresAt = expiryTime ? moment.utc().add(expiryTime, "ms").format("YYYY-MM-DD HH:mm:ss") : null;
|
||||
const expiresAt = expiryTime
|
||||
? moment
|
||||
.utc()
|
||||
.add(expiryTime, "ms")
|
||||
.format("YYYY-MM-DD HH:mm:ss")
|
||||
: null;
|
||||
|
||||
const result = await this.mutes.insert({
|
||||
guild_id: this.guildId,
|
||||
|
@ -48,7 +53,12 @@ export class GuildMutes extends BaseGuildRepository {
|
|||
}
|
||||
|
||||
async updateExpiryTime(userId, newExpiryTime, rolesToRestore?: string[]) {
|
||||
const expiresAt = newExpiryTime ? moment.utc().add(newExpiryTime, "ms").format("YYYY-MM-DD HH:mm:ss") : null;
|
||||
const expiresAt = newExpiryTime
|
||||
? moment
|
||||
.utc()
|
||||
.add(newExpiryTime, "ms")
|
||||
.format("YYYY-MM-DD HH:mm:ss")
|
||||
: null;
|
||||
|
||||
if (rolesToRestore && rolesToRestore.length) {
|
||||
return this.mutes.update(
|
||||
|
@ -79,7 +89,7 @@ export class GuildMutes extends BaseGuildRepository {
|
|||
.createQueryBuilder("mutes")
|
||||
.where("guild_id = :guild_id", { guild_id: this.guildId })
|
||||
.andWhere(
|
||||
new Brackets((qb) => {
|
||||
new Brackets(qb => {
|
||||
qb.where("expires_at > NOW()").orWhere("expires_at IS NULL");
|
||||
}),
|
||||
)
|
||||
|
|
|
@ -70,7 +70,7 @@ export class GuildNicknameHistory extends BaseGuildRepository {
|
|||
|
||||
if (toDelete.length > 0) {
|
||||
await this.nicknameHistory.delete({
|
||||
id: In(toDelete.map((v) => v.id)),
|
||||
id: In(toDelete.map(v => v.id)),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
|
@ -11,7 +11,10 @@ export class GuildScheduledPosts extends BaseGuildRepository {
|
|||
}
|
||||
|
||||
all(): Promise<ScheduledPost[]> {
|
||||
return this.scheduledPosts.createQueryBuilder().where("guild_id = :guildId", { guildId: this.guildId }).getMany();
|
||||
return this.scheduledPosts
|
||||
.createQueryBuilder()
|
||||
.where("guild_id = :guildId", { guildId: this.guildId })
|
||||
.getMany();
|
||||
}
|
||||
|
||||
getDueScheduledPosts(): Promise<ScheduledPost[]> {
|
||||
|
|
|
@ -67,7 +67,10 @@ export class GuildSlowmodes extends BaseGuildRepository {
|
|||
const slowmode = await this.getChannelSlowmode(channelId);
|
||||
if (!slowmode) return;
|
||||
|
||||
const expiresAt = moment.utc().add(slowmode.slowmode_seconds, "seconds").format("YYYY-MM-DD HH:mm:ss");
|
||||
const expiresAt = moment
|
||||
.utc()
|
||||
.add(slowmode.slowmode_seconds, "seconds")
|
||||
.format("YYYY-MM-DD HH:mm:ss");
|
||||
|
||||
if (await this.userHasSlowmode(channelId, userId)) {
|
||||
// Update existing
|
||||
|
|
|
@ -31,7 +31,10 @@ export class GuildTempbans extends BaseGuildRepository {
|
|||
}
|
||||
|
||||
async addTempban(userId, expiryTime, modId): Promise<Tempban> {
|
||||
const expiresAt = moment.utc().add(expiryTime, "ms").format("YYYY-MM-DD HH:mm:ss");
|
||||
const expiresAt = moment
|
||||
.utc()
|
||||
.add(expiryTime, "ms")
|
||||
.format("YYYY-MM-DD HH:mm:ss");
|
||||
|
||||
const result = await this.tempbans.insert({
|
||||
guild_id: this.guildId,
|
||||
|
@ -45,7 +48,10 @@ export class GuildTempbans extends BaseGuildRepository {
|
|||
}
|
||||
|
||||
async updateExpiryTime(userId, newExpiryTime, modId) {
|
||||
const expiresAt = moment.utc().add(newExpiryTime, "ms").format("YYYY-MM-DD HH:mm:ss");
|
||||
const expiresAt = moment
|
||||
.utc()
|
||||
.add(newExpiryTime, "ms")
|
||||
.format("YYYY-MM-DD HH:mm:ss");
|
||||
|
||||
return this.tempbans.update(
|
||||
{
|
||||
|
|
|
@ -19,7 +19,10 @@ export class GuildVCAlerts extends BaseGuildRepository {
|
|||
}
|
||||
|
||||
async getAllGuildAlerts(): Promise<VCAlert[]> {
|
||||
return this.allAlerts.createQueryBuilder().where("guild_id = :guildId", { guildId: this.guildId }).getMany();
|
||||
return this.allAlerts
|
||||
.createQueryBuilder()
|
||||
.where("guild_id = :guildId", { guildId: this.guildId })
|
||||
.getMany();
|
||||
}
|
||||
|
||||
async getAlertsByUserId(userId: string): Promise<VCAlert[]> {
|
||||
|
|
|
@ -67,7 +67,7 @@ export class UsernameHistory extends BaseRepository {
|
|||
|
||||
if (toDelete.length > 0) {
|
||||
await this.usernameHistory.delete({
|
||||
id: In(toDelete.map((v) => v.id)),
|
||||
id: In(toDelete.map(v => v.id)),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
|
@ -13,7 +13,10 @@ export async function cleanupConfigs() {
|
|||
let rows;
|
||||
|
||||
// >1 month old: 1 config retained per month
|
||||
const oneMonthCutoff = moment.utc().subtract(30, "days").format(DBDateFormat);
|
||||
const oneMonthCutoff = moment
|
||||
.utc()
|
||||
.subtract(30, "days")
|
||||
.format(DBDateFormat);
|
||||
do {
|
||||
rows = await connection.query(
|
||||
`
|
||||
|
@ -43,7 +46,7 @@ export async function cleanupConfigs() {
|
|||
|
||||
if (rows.length > 0) {
|
||||
await configRepository.delete({
|
||||
id: In(rows.map((r) => r.id)),
|
||||
id: In(rows.map(r => r.id)),
|
||||
});
|
||||
}
|
||||
|
||||
|
@ -51,7 +54,10 @@ export async function cleanupConfigs() {
|
|||
} while (rows.length === CLEAN_PER_LOOP);
|
||||
|
||||
// >2 weeks old: 1 config retained per day
|
||||
const twoWeekCutoff = moment.utc().subtract(2, "weeks").format(DBDateFormat);
|
||||
const twoWeekCutoff = moment
|
||||
.utc()
|
||||
.subtract(2, "weeks")
|
||||
.format(DBDateFormat);
|
||||
do {
|
||||
rows = await connection.query(
|
||||
`
|
||||
|
@ -81,7 +87,7 @@ export async function cleanupConfigs() {
|
|||
|
||||
if (rows.length > 0) {
|
||||
await configRepository.delete({
|
||||
id: In(rows.map((r) => r.id)),
|
||||
id: In(rows.map(r => r.id)),
|
||||
});
|
||||
}
|
||||
|
||||
|
|
|
@ -18,9 +18,18 @@ export async function cleanupMessages(): Promise<number> {
|
|||
|
||||
const messagesRepository = getRepository(SavedMessage);
|
||||
|
||||
const deletedAtThreshold = moment.utc().subtract(DELETED_MESSAGE_RETENTION_PERIOD, "ms").format(DBDateFormat);
|
||||
const postedAtThreshold = moment.utc().subtract(RETENTION_PERIOD, "ms").format(DBDateFormat);
|
||||
const botPostedAtThreshold = moment.utc().subtract(BOT_MESSAGE_RETENTION_PERIOD, "ms").format(DBDateFormat);
|
||||
const deletedAtThreshold = moment
|
||||
.utc()
|
||||
.subtract(DELETED_MESSAGE_RETENTION_PERIOD, "ms")
|
||||
.format(DBDateFormat);
|
||||
const postedAtThreshold = moment
|
||||
.utc()
|
||||
.subtract(RETENTION_PERIOD, "ms")
|
||||
.format(DBDateFormat);
|
||||
const botPostedAtThreshold = moment
|
||||
.utc()
|
||||
.subtract(BOT_MESSAGE_RETENTION_PERIOD, "ms")
|
||||
.format(DBDateFormat);
|
||||
|
||||
// SELECT + DELETE messages in batches
|
||||
// This is to avoid deadlocks that happened frequently when deleting with the same criteria as the select below
|
||||
|
@ -51,7 +60,7 @@ export async function cleanupMessages(): Promise<number> {
|
|||
|
||||
if (rows.length > 0) {
|
||||
await messagesRepository.delete({
|
||||
id: In(rows.map((r) => r.id)),
|
||||
id: In(rows.map(r => r.id)),
|
||||
});
|
||||
}
|
||||
|
||||
|
|
|
@ -11,7 +11,10 @@ export async function cleanupNicknames(): Promise<number> {
|
|||
let cleaned = 0;
|
||||
|
||||
const nicknameHistoryRepository = getRepository(NicknameHistoryEntry);
|
||||
const dateThreshold = moment.utc().subtract(NICKNAME_RETENTION_PERIOD, "ms").format(DBDateFormat);
|
||||
const dateThreshold = moment
|
||||
.utc()
|
||||
.subtract(NICKNAME_RETENTION_PERIOD, "ms")
|
||||
.format(DBDateFormat);
|
||||
|
||||
// Clean old nicknames (NICKNAME_RETENTION_PERIOD)
|
||||
let rows;
|
||||
|
@ -28,7 +31,7 @@ export async function cleanupNicknames(): Promise<number> {
|
|||
|
||||
if (rows.length > 0) {
|
||||
await nicknameHistoryRepository.delete({
|
||||
id: In(rows.map((r) => r.id)),
|
||||
id: In(rows.map(r => r.id)),
|
||||
});
|
||||
}
|
||||
|
||||
|
|
|
@ -11,7 +11,10 @@ export async function cleanupUsernames(): Promise<number> {
|
|||
let cleaned = 0;
|
||||
|
||||
const usernameHistoryRepository = getRepository(UsernameHistoryEntry);
|
||||
const dateThreshold = moment.utc().subtract(USERNAME_RETENTION_PERIOD, "ms").format(DBDateFormat);
|
||||
const dateThreshold = moment
|
||||
.utc()
|
||||
.subtract(USERNAME_RETENTION_PERIOD, "ms")
|
||||
.format(DBDateFormat);
|
||||
|
||||
// Clean old usernames (USERNAME_RETENTION_PERIOD)
|
||||
let rows;
|
||||
|
@ -28,7 +31,7 @@ export async function cleanupUsernames(): Promise<number> {
|
|||
|
||||
if (rows.length > 0) {
|
||||
await usernameHistoryRepository.delete({
|
||||
id: In(rows.map((r) => r.id)),
|
||||
id: In(rows.map(r => r.id)),
|
||||
});
|
||||
}
|
||||
|
||||
|
|
|
@ -7,9 +7,9 @@ export let connection: Connection;
|
|||
|
||||
export function connect() {
|
||||
if (!connectionPromise) {
|
||||
connectionPromise = createConnection().then((newConnection) => {
|
||||
connectionPromise = createConnection().then(newConnection => {
|
||||
// Verify the DB timezone is set to UTC
|
||||
return newConnection.query("SELECT TIMEDIFF(NOW(), UTC_TIMESTAMP) AS tz").then((r) => {
|
||||
return newConnection.query("SELECT TIMEDIFF(NOW(), UTC_TIMESTAMP) AS tz").then(r => {
|
||||
if (r[0].tz !== "00:00:00") {
|
||||
throw new SimpleError(`Database timezone must be UTC (detected ${r[0].tz})`);
|
||||
}
|
||||
|
|
|
@ -19,7 +19,10 @@ export class ApiLogin {
|
|||
@Column()
|
||||
expires_at: string;
|
||||
|
||||
@ManyToOne((type) => ApiUserInfo, (userInfo) => userInfo.logins)
|
||||
@ManyToOne(
|
||||
type => ApiUserInfo,
|
||||
userInfo => userInfo.logins,
|
||||
)
|
||||
@JoinColumn({ name: "user_id" })
|
||||
userInfo: ApiUserInfo;
|
||||
}
|
||||
|
|
|
@ -18,7 +18,10 @@ export class ApiPermissionAssignment {
|
|||
@Column("simple-array")
|
||||
permissions: string[];
|
||||
|
||||
@ManyToOne((type) => ApiUserInfo, (userInfo) => userInfo.permissionAssignments)
|
||||
@ManyToOne(
|
||||
type => ApiUserInfo,
|
||||
userInfo => userInfo.permissionAssignments,
|
||||
)
|
||||
@JoinColumn({ name: "target_id" })
|
||||
userInfo: ApiUserInfo;
|
||||
}
|
||||
|
|
|
@ -20,9 +20,15 @@ export class ApiUserInfo {
|
|||
@Column()
|
||||
updated_at: string;
|
||||
|
||||
@OneToMany((type) => ApiLogin, (login) => login.userInfo)
|
||||
@OneToMany(
|
||||
type => ApiLogin,
|
||||
login => login.userInfo,
|
||||
)
|
||||
logins: ApiLogin[];
|
||||
|
||||
@OneToMany((type) => ApiPermissionAssignment, (p) => p.userInfo)
|
||||
@OneToMany(
|
||||
type => ApiPermissionAssignment,
|
||||
p => p.userInfo,
|
||||
)
|
||||
permissionAssignments: ApiPermissionAssignment[];
|
||||
}
|
||||
|
|
|
@ -35,6 +35,9 @@ export class Case {
|
|||
*/
|
||||
@Column({ type: String, nullable: true }) log_message_id: string | null;
|
||||
|
||||
@OneToMany((type) => CaseNote, (note) => note.case)
|
||||
@OneToMany(
|
||||
type => CaseNote,
|
||||
note => note.case,
|
||||
)
|
||||
notes: CaseNote[];
|
||||
}
|
||||
|
|
|
@ -15,7 +15,10 @@ export class CaseNote {
|
|||
|
||||
@Column() created_at: string;
|
||||
|
||||
@ManyToOne((type) => Case, (theCase) => theCase.notes)
|
||||
@ManyToOne(
|
||||
type => Case,
|
||||
theCase => theCase.notes,
|
||||
)
|
||||
@JoinColumn({ name: "case_id" })
|
||||
case: Case;
|
||||
}
|
||||
|
|
|
@ -22,7 +22,7 @@ export class Config {
|
|||
@Column()
|
||||
edited_at: string;
|
||||
|
||||
@ManyToOne((type) => ApiUserInfo)
|
||||
@ManyToOne(type => ApiUserInfo)
|
||||
@JoinColumn({ name: "edited_by" })
|
||||
userInfo: ApiUserInfo;
|
||||
}
|
||||
|
|
|
@ -16,7 +16,7 @@ export class StarboardMessage {
|
|||
@Column()
|
||||
guild_id: string;
|
||||
|
||||
@OneToOne((type) => SavedMessage)
|
||||
@OneToOne(type => SavedMessage)
|
||||
@JoinColumn({ name: "message_id" })
|
||||
message: SavedMessage;
|
||||
}
|
||||
|
|
|
@ -16,7 +16,7 @@ export class StarboardReaction {
|
|||
@Column()
|
||||
reactor_id: string;
|
||||
|
||||
@OneToOne((type) => SavedMessage)
|
||||
@OneToOne(type => SavedMessage)
|
||||
@JoinColumn({ name: "message_id" })
|
||||
message: SavedMessage;
|
||||
}
|
||||
|
|
|
@ -139,8 +139,8 @@ if (process.env.NODE_ENV === "production") {
|
|||
|
||||
// Verify required Node.js version
|
||||
const REQUIRED_NODE_VERSION = "14.0.0";
|
||||
const requiredParts = REQUIRED_NODE_VERSION.split(".").map((v) => parseInt(v, 10));
|
||||
const actualVersionParts = process.versions.node.split(".").map((v) => parseInt(v, 10));
|
||||
const requiredParts = REQUIRED_NODE_VERSION.split(".").map(v => parseInt(v, 10));
|
||||
const actualVersionParts = process.versions.node.split(".").map(v => parseInt(v, 10));
|
||||
for (const [i, part] of actualVersionParts.entries()) {
|
||||
if (part > requiredParts[i]) break;
|
||||
if (part === requiredParts[i]) continue;
|
||||
|
@ -175,7 +175,7 @@ connect().then(async () => {
|
|||
});
|
||||
client.setMaxListeners(200);
|
||||
|
||||
client.on("debug", (message) => {
|
||||
client.on("debug", message => {
|
||||
if (message.includes(" 429 ")) {
|
||||
logger.info(`[429] ${message}`);
|
||||
}
|
||||
|
@ -209,9 +209,9 @@ connect().then(async () => {
|
|||
}
|
||||
|
||||
const configuredPlugins = ctx.config.plugins;
|
||||
const basePluginNames = baseGuildPlugins.map((p) => p.name);
|
||||
const basePluginNames = baseGuildPlugins.map(p => p.name);
|
||||
|
||||
return Array.from(plugins.keys()).filter((pluginName) => {
|
||||
return Array.from(plugins.keys()).filter(pluginName => {
|
||||
if (basePluginNames.includes(pluginName)) return true;
|
||||
return configuredPlugins[pluginName] && configuredPlugins[pluginName].enabled !== false;
|
||||
});
|
||||
|
|
|
@ -9,23 +9,23 @@ export class MigrateUsernamesToNewHistoryTable1556909512501 implements Migration
|
|||
|
||||
const migratedUsernames = new Set();
|
||||
|
||||
await new Promise(async (resolve) => {
|
||||
await new Promise(async resolve => {
|
||||
const stream = await queryRunner.stream("SELECT CONCAT(user_id, '-', username) AS `key` FROM username_history");
|
||||
stream.on("result", (row) => {
|
||||
stream.on("result", row => {
|
||||
migratedUsernames.add(row.key);
|
||||
});
|
||||
stream.on("end", resolve);
|
||||
});
|
||||
|
||||
const migrateNextBatch = (): Promise<{ finished: boolean; migrated?: number }> => {
|
||||
return new Promise(async (resolve) => {
|
||||
return new Promise(async resolve => {
|
||||
const toInsert: any[][] = [];
|
||||
const toDelete: number[] = [];
|
||||
|
||||
const stream = await queryRunner.stream(
|
||||
`SELECT * FROM name_history WHERE type=1 ORDER BY timestamp ASC LIMIT ${BATCH_SIZE}`,
|
||||
);
|
||||
stream.on("result", (row) => {
|
||||
stream.on("result", row => {
|
||||
const key = `${row.user_id}-${row.value}`;
|
||||
|
||||
if (!migratedUsernames.has(key)) {
|
||||
|
|
|
@ -1,33 +1,34 @@
|
|||
import { MigrationInterface, QueryRunner, Table } from "typeorm";
|
||||
|
||||
export class AFKStatus1617410382003 implements MigrationInterface {
|
||||
public async up(queryRunner: QueryRunner): Promise<void> {
|
||||
await queryRunner.createTable(
|
||||
new Table({
|
||||
name: "afk",
|
||||
columns: [
|
||||
{
|
||||
name: "id",
|
||||
type: "int",
|
||||
isPrimary: true,
|
||||
isGenerated: true,
|
||||
generationStrategy: "increment",
|
||||
},
|
||||
{
|
||||
name: "user_id",
|
||||
type: "bigint",
|
||||
},
|
||||
{
|
||||
name: "status",
|
||||
type: "varchar",
|
||||
length: "255",
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
public async down(queryRunner: QueryRunner): Promise<void> {
|
||||
return queryRunner.dropTable("afk");
|
||||
}
|
||||
public async up(queryRunner: QueryRunner): Promise<void> {
|
||||
await queryRunner.createTable(
|
||||
new Table({
|
||||
name: "afk",
|
||||
columns: [
|
||||
{
|
||||
name: "id",
|
||||
type: "int",
|
||||
isPrimary: true,
|
||||
isGenerated: true,
|
||||
generationStrategy: "increment",
|
||||
},
|
||||
{
|
||||
name: "user_id",
|
||||
type: "bigint",
|
||||
},
|
||||
{
|
||||
name: "status",
|
||||
type: "varchar",
|
||||
length: "255",
|
||||
}
|
||||
]
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
public async down(queryRunner: QueryRunner): Promise<void> {
|
||||
return queryRunner.dropTable("afk");
|
||||
}
|
||||
}
|
||||
|
|
|
@ -61,7 +61,7 @@ export function strictValidationErrorToConfigValidationError(err: StrictValidati
|
|||
return new ConfigValidationError(
|
||||
err
|
||||
.getErrors()
|
||||
.map((e) => e.toString())
|
||||
.map(e => e.toString())
|
||||
.join("\n"),
|
||||
);
|
||||
}
|
||||
|
@ -150,7 +150,7 @@ export function sendSuccessMessage(
|
|||
: { content: formattedBody };
|
||||
return channel
|
||||
.createMessage(content) // Force line break
|
||||
.catch((err) => {
|
||||
.catch(err => {
|
||||
const channelInfo = (channel as GuildTextableChannel).guild
|
||||
? `${channel.id} (${(channel as GuildTextableChannel).guild.id})`
|
||||
: `${channel.id}`;
|
||||
|
@ -172,7 +172,7 @@ export function sendErrorMessage(
|
|||
: { content: formattedBody };
|
||||
return channel
|
||||
.createMessage(content) // Force line break
|
||||
.catch((err) => {
|
||||
.catch(err => {
|
||||
const channelInfo = (channel as GuildTextableChannel).guild
|
||||
? `${channel.id} (${(channel as GuildTextableChannel).guild.id})`
|
||||
: `${channel.id}`;
|
||||
|
@ -206,7 +206,7 @@ type AnyFn = (...args: any[]) => any;
|
|||
* Creates a public plugin function out of a function with pluginData as the first parameter
|
||||
*/
|
||||
export function mapToPublicFn<T extends AnyFn>(inputFn: T) {
|
||||
return (pluginData) => {
|
||||
return pluginData => {
|
||||
return (...args: Tail<Parameters<typeof inputFn>>): ReturnType<typeof inputFn> => {
|
||||
return inputFn(pluginData, ...args);
|
||||
};
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
import { PluginOptions } from "knub";
|
||||
import { AFKPluginType, ConfigSchema } from "./types";
|
||||
import { AFKPluginType, ConfigSchema } from './types';
|
||||
import { zeppelinGuildPlugin } from "../ZeppelinPluginBlueprint";
|
||||
import { AFK } from "src/data/AFK";
|
||||
|
||||
|
@ -7,39 +7,40 @@ import { AfkSetCmd } from "./commands/AFKCmd";
|
|||
import { AFKNotificationEvt } from "./events/AFKNotificationEvt";
|
||||
|
||||
const defaultOptions: PluginOptions<AFKPluginType> = {
|
||||
config: {
|
||||
can_afk: false,
|
||||
allow_links: false,
|
||||
allow_invites: false,
|
||||
},
|
||||
overrides: [
|
||||
{
|
||||
level: ">=50",
|
||||
config: {
|
||||
can_afk: true,
|
||||
allow_links: true,
|
||||
allow_invites: true,
|
||||
},
|
||||
config: {
|
||||
can_afk: false,
|
||||
allow_links: false,
|
||||
allow_invites: false,
|
||||
},
|
||||
],
|
||||
};
|
||||
overrides: [
|
||||
{
|
||||
level: '>=50',
|
||||
config: {
|
||||
can_afk: true,
|
||||
allow_links: true,
|
||||
allow_invites: true,
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
export const AFKPlugin = zeppelinGuildPlugin<AFKPluginType>()("afk", {
|
||||
showInDocs: true,
|
||||
info: {
|
||||
prettyName: "AFK",
|
||||
description: "Allows you to set your AFK Status.",
|
||||
},
|
||||
showInDocs: true,
|
||||
info: {
|
||||
prettyName: "AFK",
|
||||
description: "Allows you to set your AFK Status.",
|
||||
},
|
||||
|
||||
configSchema: ConfigSchema,
|
||||
defaultOptions,
|
||||
configSchema: ConfigSchema,
|
||||
defaultOptions,
|
||||
|
||||
commands: [AfkSetCmd],
|
||||
events: [AFKNotificationEvt],
|
||||
commands: [AfkSetCmd],
|
||||
events: [AFKNotificationEvt],
|
||||
|
||||
onLoad(pluginData) {
|
||||
const { state } = pluginData;
|
||||
onLoad(pluginData) {
|
||||
const { state } = pluginData;
|
||||
|
||||
state.afkUsers = new AFK();
|
||||
}
|
||||
})
|
||||
|
||||
state.afkUsers = new AFK();
|
||||
},
|
||||
});
|
||||
|
|
|
@ -4,40 +4,43 @@ import { sendErrorMessage, sendSuccessMessage } from "../../../pluginUtils";
|
|||
import { parseStatusMessage } from "../functions/parseStatusMessage";
|
||||
|
||||
export const AfkSetCmd = afkCmd({
|
||||
trigger: ["afk", "afk set"],
|
||||
permission: "can_afk",
|
||||
trigger: ['afk', 'afk set'],
|
||||
permission: 'can_afk',
|
||||
|
||||
signature: {
|
||||
status: ct.string({ rest: true, required: true }),
|
||||
},
|
||||
signature: {
|
||||
status: ct.string({ rest: true, required: true }),
|
||||
},
|
||||
|
||||
async run({ message: msg, args, pluginData }) {
|
||||
// Checks if the user is AFK, if so, return.
|
||||
const isAfk = await pluginData.state.afkUsers.getUserAFKStatus(msg.author.id);
|
||||
if (isAfk) return;
|
||||
async run({ message: msg, args, pluginData }) {
|
||||
// Checks if the user is AFK, if so, return.
|
||||
const isAfk = await pluginData.state.afkUsers.getUserAFKStatus(msg.author.id);
|
||||
if (isAfk) return;
|
||||
|
||||
const status = args.status.join(" ");
|
||||
|
||||
const status = args.status.join(" ");
|
||||
// Check status length
|
||||
if (status.length > 124) {
|
||||
sendErrorMessage(pluginData, msg.channel, "Status length is above **124** characters.");
|
||||
return;
|
||||
}
|
||||
|
||||
// Check status length
|
||||
if (status.length > 124) {
|
||||
sendErrorMessage(pluginData, msg.channel, "Status length is above **124** characters.");
|
||||
return;
|
||||
// Checks status based on configuration options
|
||||
const parsed = parseStatusMessage(pluginData, msg.member, status);
|
||||
if (typeof parsed === 'string') {
|
||||
sendErrorMessage(pluginData, msg.channel, parsed);
|
||||
return;
|
||||
}
|
||||
|
||||
// Set user status
|
||||
const afk = await pluginData.state.afkUsers.setAfkStatus(
|
||||
msg.author.id,
|
||||
status,
|
||||
);
|
||||
|
||||
sendSuccessMessage(pluginData, msg.channel, `AFK Status set to: **${afk.status}**`, {
|
||||
roles: false,
|
||||
everyone: false,
|
||||
users: false,
|
||||
});
|
||||
}
|
||||
|
||||
// Checks status based on configuration options
|
||||
const parsed = parseStatusMessage(pluginData, msg.member, status);
|
||||
if (typeof parsed === "string") {
|
||||
sendErrorMessage(pluginData, msg.channel, parsed);
|
||||
return;
|
||||
}
|
||||
|
||||
// Set user status
|
||||
const afk = await pluginData.state.afkUsers.setAfkStatus(msg.author.id, status);
|
||||
|
||||
sendSuccessMessage(pluginData, msg.channel, `AFK Status set to: **${afk.status}**`, {
|
||||
roles: false,
|
||||
everyone: false,
|
||||
users: false,
|
||||
});
|
||||
},
|
||||
});
|
||||
})
|
|
@ -2,27 +2,27 @@ import { sendUserMentionMessage, sendWelcomeBackMessage } from "../functions/bui
|
|||
import { afkEvt } from "../types";
|
||||
|
||||
export const AFKNotificationEvt = afkEvt({
|
||||
event: "messageCreate",
|
||||
event: 'messageCreate',
|
||||
|
||||
listener: async ({ pluginData, args: { message } }) => {
|
||||
// Mention Check (if someone mentions the AFK user)
|
||||
if (message.mentions.length) {
|
||||
const afk = await pluginData.state.afkUsers.getUserAFKStatus(message.mentions[0].id);
|
||||
if (!afk) return;
|
||||
listener: async ({ pluginData, args: { message } }) => {
|
||||
// Mention Check (if someone mentions the AFK user)
|
||||
if (message.mentions.length) {
|
||||
const afk = await pluginData.state.afkUsers.getUserAFKStatus(message.mentions[0].id);
|
||||
if (!afk) return;
|
||||
|
||||
sendUserMentionMessage(message, afk.status);
|
||||
|
||||
sendUserMentionMessage(message, afk.status);
|
||||
return;
|
||||
}
|
||||
|
||||
return;
|
||||
// Self AFK Check (if user is the one that's AFK)
|
||||
const afk = await pluginData.state.afkUsers.getUserAFKStatus(message.author.id);
|
||||
if (!afk) return;
|
||||
|
||||
try {
|
||||
await pluginData.state.afkUsers.clearAFKStatus(message.author.id);
|
||||
} catch (err) {}
|
||||
|
||||
sendWelcomeBackMessage(message);
|
||||
}
|
||||
|
||||
// Self AFK Check (if user is the one that's AFK)
|
||||
const afk = await pluginData.state.afkUsers.getUserAFKStatus(message.author.id);
|
||||
if (!afk) return;
|
||||
|
||||
try {
|
||||
await pluginData.state.afkUsers.clearAFKStatus(message.author.id);
|
||||
} catch (err) {}
|
||||
|
||||
sendWelcomeBackMessage(message);
|
||||
},
|
||||
});
|
||||
});
|
|
@ -1,23 +1,23 @@
|
|||
import { Message } from "eris";
|
||||
|
||||
export function sendUserMentionMessage(message: Message, status: string) {
|
||||
return message.channel.createMessage({
|
||||
allowedMentions: {
|
||||
users: [message.author.id],
|
||||
everyone: false,
|
||||
roles: false,
|
||||
},
|
||||
content: `<@!${message.author.id}>, the user mentioned is currently AFK: **${status}**`,
|
||||
});
|
||||
return message.channel.createMessage({
|
||||
allowedMentions: {
|
||||
users: [message.author.id],
|
||||
everyone: false,
|
||||
roles: false,
|
||||
},
|
||||
content: `<@!${message.author.id}>, the user mentioned is currently AFK: **${status}**`,
|
||||
});
|
||||
}
|
||||
|
||||
export function sendWelcomeBackMessage(message: Message) {
|
||||
return message.channel.createMessage({
|
||||
allowedMentions: {
|
||||
users: [message.author.id],
|
||||
everyone: false,
|
||||
roles: false,
|
||||
},
|
||||
content: `<@!${message.author.id}>, welcome back!`,
|
||||
});
|
||||
}
|
||||
return message.channel.createMessage({
|
||||
allowedMentions: {
|
||||
users: [message.author.id],
|
||||
everyone: false,
|
||||
roles: false,
|
||||
},
|
||||
content: `<@!${message.author.id}>, welcome back!`,
|
||||
});
|
||||
}
|
|
@ -10,9 +10,9 @@ const HttpUrlRegex = /^(https?):\/\/[^\s$.?#].[^\s]*$/;
|
|||
const DiscordInviteLinkRegex = /^(?:https?:\/\/)?(?:www\.)?(?:discord\.gg\/|discord(?:app)?\.com\/invite\/)?(?<code>[\w\d-]{2,})$/i;
|
||||
|
||||
export function parseStatusMessage(pluginData: GuildPluginData<AFKPluginType>, member: Member, status: string) {
|
||||
const allow_links = hasPermission(pluginData, "allow_links", { member });
|
||||
const allow_invites = hasPermission(pluginData, "allow_invites", { member });
|
||||
const allow_links = hasPermission(pluginData, "allow_links", { member });
|
||||
const allow_invites = hasPermission(pluginData, "allow_invites", { member });
|
||||
|
||||
if (!allow_links && HttpUrlRegex.test(status)) return "Links are not allowed in an AFK status!";
|
||||
if (!allow_invites && DiscordInviteLinkRegex.test(status)) return "Invites are not allowed in an AFK status!";
|
||||
}
|
||||
if (!allow_links && HttpUrlRegex.test(status)) return "Links are not allowed in an AFK status!";
|
||||
if (!allow_invites && DiscordInviteLinkRegex.test(status)) return "Invites are not allowed in an AFK status!";
|
||||
}
|
|
@ -1,20 +1,20 @@
|
|||
import * as t from "io-ts";
|
||||
import { BasePluginType, guildCommand, guildEventListener } from "knub";
|
||||
import { AFK } from "../../data/AFK";
|
||||
import * as t from 'io-ts';
|
||||
import { BasePluginType, guildCommand, guildEventListener } from 'knub';
|
||||
import { AFK } from '../../data/AFK';
|
||||
|
||||
export const ConfigSchema = t.type({
|
||||
can_afk: t.boolean,
|
||||
allow_links: t.boolean,
|
||||
allow_invites: t.boolean,
|
||||
can_afk: t.boolean,
|
||||
allow_links: t.boolean,
|
||||
allow_invites: t.boolean,
|
||||
});
|
||||
export type TConfigSchema = t.TypeOf<typeof ConfigSchema>;
|
||||
|
||||
export interface AFKPluginType extends BasePluginType {
|
||||
config: TConfigSchema;
|
||||
state: {
|
||||
afkUsers: AFK;
|
||||
};
|
||||
config: TConfigSchema;
|
||||
state: {
|
||||
afkUsers: AFK;
|
||||
}
|
||||
}
|
||||
|
||||
export const afkCmd = guildCommand<AFKPluginType>();
|
||||
export const afkEvt = guildEventListener<AFKPluginType>();
|
||||
export const afkEvt = guildEventListener<AFKPluginType>();
|
|
@ -39,13 +39,13 @@ export const AutoDeletePlugin = zeppelinGuildPlugin<AutoDeletePluginType>()("aut
|
|||
|
||||
state.maxDelayWarningSent = false;
|
||||
|
||||
state.onMessageCreateFn = (msg) => onMessageCreate(pluginData, msg);
|
||||
state.onMessageCreateFn = msg => onMessageCreate(pluginData, msg);
|
||||
state.guildSavedMessages.events.on("create", state.onMessageCreateFn);
|
||||
|
||||
state.onMessageDeleteFn = (msg) => onMessageDelete(pluginData, msg);
|
||||
state.onMessageDeleteFn = msg => onMessageDelete(pluginData, msg);
|
||||
state.guildSavedMessages.events.on("delete", state.onMessageDeleteFn);
|
||||
|
||||
state.onMessageDeleteBulkFn = (msgs) => onMessageDeleteBulk(pluginData, msgs);
|
||||
state.onMessageDeleteBulkFn = msgs => onMessageDeleteBulk(pluginData, msgs);
|
||||
state.guildSavedMessages.events.on("deleteBulk", state.onMessageDeleteBulkFn);
|
||||
},
|
||||
|
||||
|
|
|
@ -4,7 +4,7 @@ import { SavedMessage } from "../../../data/entities/SavedMessage";
|
|||
import { scheduleNextDeletion } from "./scheduleNextDeletion";
|
||||
|
||||
export function onMessageDelete(pluginData: GuildPluginData<AutoDeletePluginType>, msg: SavedMessage) {
|
||||
const indexToDelete = pluginData.state.deletionQueue.findIndex((item) => item.message.id === msg.id);
|
||||
const indexToDelete = pluginData.state.deletionQueue.findIndex(item => item.message.id === msg.id);
|
||||
if (indexToDelete > -1) {
|
||||
pluginData.state.deletionQueue.splice(indexToDelete, 1);
|
||||
scheduleNextDeletion(pluginData);
|
||||
|
|
|
@ -61,7 +61,7 @@ const defaultOptions = {
|
|||
/**
|
||||
* Config preprocessor to set default values for triggers and perform extra validation
|
||||
*/
|
||||
const configPreprocessor: ConfigPreprocessorFn<AutomodPluginType> = (options) => {
|
||||
const configPreprocessor: ConfigPreprocessorFn<AutomodPluginType> = options => {
|
||||
if (options.config?.rules) {
|
||||
// Loop through each rule
|
||||
for (const [name, rule] of Object.entries(options.config.rules)) {
|
||||
|
@ -217,10 +217,10 @@ export const AutomodPlugin = zeppelinGuildPlugin<AutomodPluginType>()("automod",
|
|||
pluginData.state.antiraidLevels = GuildAntiraidLevels.getGuildInstance(pluginData.guild.id);
|
||||
pluginData.state.archives = GuildArchives.getGuildInstance(pluginData.guild.id);
|
||||
|
||||
pluginData.state.onMessageCreateFn = (message) => runAutomodOnMessage(pluginData, message, false);
|
||||
pluginData.state.onMessageCreateFn = message => runAutomodOnMessage(pluginData, message, false);
|
||||
pluginData.state.savedMessages.events.on("create", pluginData.state.onMessageCreateFn);
|
||||
|
||||
pluginData.state.onMessageUpdateFn = (message) => runAutomodOnMessage(pluginData, message, true);
|
||||
pluginData.state.onMessageUpdateFn = message => runAutomodOnMessage(pluginData, message, true);
|
||||
pluginData.state.savedMessages.events.on("update", pluginData.state.onMessageUpdateFn);
|
||||
|
||||
pluginData.state.cachedAntiraidLevel = await pluginData.state.antiraidLevels.get();
|
||||
|
|
|
@ -17,7 +17,7 @@ export const AddRolesAction = automodAction({
|
|||
defaultConfig: [],
|
||||
|
||||
async apply({ pluginData, contexts, actionConfig, ruleName }) {
|
||||
const members = unique(contexts.map((c) => c.member).filter(nonNullish));
|
||||
const members = unique(contexts.map(c => c.member).filter(nonNullish));
|
||||
const me = pluginData.guild.members.get(pluginData.client.user.id)!;
|
||||
|
||||
const missingPermissions = getMissingPermissions(me.permission, p.manageRoles);
|
||||
|
@ -41,7 +41,7 @@ export const AddRolesAction = automodAction({
|
|||
|
||||
if (rolesWeCannotAssign.length) {
|
||||
const roleNamesWeCannotAssign = rolesWeCannotAssign.map(
|
||||
(roleId) => pluginData.guild.roles.get(roleId)?.name || roleId,
|
||||
roleId => pluginData.guild.roles.get(roleId)?.name || roleId,
|
||||
);
|
||||
const logs = pluginData.getPlugin(LogsPlugin);
|
||||
logs.log(LogType.BOT_ALERT, {
|
||||
|
@ -52,7 +52,7 @@ export const AddRolesAction = automodAction({
|
|||
}
|
||||
|
||||
await Promise.all(
|
||||
members.map(async (member) => {
|
||||
members.map(async member => {
|
||||
const memberRoles = new Set(member.roles);
|
||||
for (const roleId of rolesToAssign) {
|
||||
memberRoles.add(roleId);
|
||||
|
|
|
@ -33,7 +33,7 @@ export const AlertAction = automodAction({
|
|||
const theMessageLink =
|
||||
contexts[0].message && messageLink(pluginData.guild.id, contexts[0].message.channel_id, contexts[0].message.id);
|
||||
|
||||
const safeUsers = contexts.map((c) => c.user && stripObjectToScalars(c.user)).filter(Boolean);
|
||||
const safeUsers = contexts.map(c => c.user && stripObjectToScalars(c.user)).filter(Boolean);
|
||||
const safeUser = safeUsers[0];
|
||||
const actionsTaken = Object.keys(pluginData.config.get().rules[ruleName].actions).join(", ");
|
||||
|
||||
|
|
|
@ -27,7 +27,7 @@ export const BanAction = automodAction({
|
|||
extraNotes: matchResult.fullSummary ? [matchResult.fullSummary] : [],
|
||||
};
|
||||
|
||||
const userIdsToBan = unique(contexts.map((c) => c.user?.id).filter(nonNullish));
|
||||
const userIdsToBan = unique(contexts.map(c => c.user?.id).filter(nonNullish));
|
||||
|
||||
const modActions = pluginData.getPlugin(ModActionsPlugin);
|
||||
for (const userId of userIdsToBan) {
|
||||
|
|
|
@ -15,13 +15,13 @@ export const ChangeNicknameAction = automodAction({
|
|||
defaultConfig: {},
|
||||
|
||||
async apply({ pluginData, contexts, actionConfig }) {
|
||||
const members = unique(contexts.map((c) => c.member).filter(nonNullish));
|
||||
const members = unique(contexts.map(c => c.member).filter(nonNullish));
|
||||
|
||||
for (const member of members) {
|
||||
if (pluginData.state.recentNicknameChanges.has(member.id)) continue;
|
||||
const newName = typeof actionConfig === "string" ? actionConfig : actionConfig.name;
|
||||
|
||||
member.edit({ nick: newName }).catch((err) => {
|
||||
member.edit({ nick: newName }).catch(err => {
|
||||
pluginData.getPlugin(LogsPlugin).log(LogType.BOT_ALERT, {
|
||||
body: `Failed to change the nickname of \`${member.id}\``,
|
||||
});
|
||||
|
|
|
@ -25,8 +25,8 @@ export const KickAction = automodAction({
|
|||
extraNotes: matchResult.fullSummary ? [matchResult.fullSummary] : [],
|
||||
};
|
||||
|
||||
const userIdsToKick = unique(contexts.map((c) => c.user?.id).filter(nonNullish));
|
||||
const membersToKick = await asyncMap(userIdsToKick, (id) => resolveMember(pluginData.client, pluginData.guild, id));
|
||||
const userIdsToKick = unique(contexts.map(c => c.user?.id).filter(nonNullish));
|
||||
const membersToKick = await asyncMap(userIdsToKick, id => resolveMember(pluginData.client, pluginData.guild, id));
|
||||
|
||||
const modActions = pluginData.getPlugin(ModActionsPlugin);
|
||||
for (const member of membersToKick) {
|
||||
|
|
|
@ -9,9 +9,9 @@ export const LogAction = automodAction({
|
|||
defaultConfig: true,
|
||||
|
||||
async apply({ pluginData, contexts, ruleName, matchResult }) {
|
||||
const safeUsers = unique(contexts.map((c) => c.user))
|
||||
const safeUsers = unique(contexts.map(c => c.user))
|
||||
.filter(Boolean)
|
||||
.map((user) => stripObjectToScalars(user));
|
||||
.map(user => stripObjectToScalars(user));
|
||||
const safeUser = safeUsers[0];
|
||||
const actionsTaken = Object.keys(pluginData.config.get().rules[ruleName].actions).join(", ");
|
||||
|
||||
|
|
|
@ -42,7 +42,7 @@ export const MuteAction = automodAction({
|
|||
extraNotes: matchResult.fullSummary ? [matchResult.fullSummary] : [],
|
||||
};
|
||||
|
||||
const userIdsToMute = unique(contexts.map((c) => c.user?.id).filter(nonNullish));
|
||||
const userIdsToMute = unique(contexts.map(c => c.user?.id).filter(nonNullish));
|
||||
|
||||
const mutes = pluginData.getPlugin(MutesPlugin);
|
||||
for (const userId of userIdsToMute) {
|
||||
|
|
|
@ -19,7 +19,7 @@ export const RemoveRolesAction = automodAction({
|
|||
defaultConfig: [],
|
||||
|
||||
async apply({ pluginData, contexts, actionConfig, ruleName }) {
|
||||
const members = unique(contexts.map((c) => c.member).filter(nonNullish));
|
||||
const members = unique(contexts.map(c => c.member).filter(nonNullish));
|
||||
const me = pluginData.guild.members.get(pluginData.client.user.id)!;
|
||||
|
||||
const missingPermissions = getMissingPermissions(me.permission, p.manageRoles);
|
||||
|
@ -43,7 +43,7 @@ export const RemoveRolesAction = automodAction({
|
|||
|
||||
if (rolesWeCannotRemove.length) {
|
||||
const roleNamesWeCannotRemove = rolesWeCannotRemove.map(
|
||||
(roleId) => pluginData.guild.roles.get(roleId)?.name || roleId,
|
||||
roleId => pluginData.guild.roles.get(roleId)?.name || roleId,
|
||||
);
|
||||
const logs = pluginData.getPlugin(LogsPlugin);
|
||||
logs.log(LogType.BOT_ALERT, {
|
||||
|
@ -54,7 +54,7 @@ export const RemoveRolesAction = automodAction({
|
|||
}
|
||||
|
||||
await Promise.all(
|
||||
members.map(async (member) => {
|
||||
members.map(async member => {
|
||||
const memberRoles = new Set(member.roles);
|
||||
for (const roleId of rolesToRemove) {
|
||||
memberRoles.delete(roleId);
|
||||
|
|
|
@ -27,8 +27,8 @@ export const ReplyAction = automodAction({
|
|||
|
||||
async apply({ pluginData, contexts, actionConfig }) {
|
||||
const contextsWithTextChannels = contexts
|
||||
.filter((c) => c.message?.channel_id)
|
||||
.filter((c) => pluginData.guild.channels.get(c.message!.channel_id) instanceof TextChannel);
|
||||
.filter(c => c.message?.channel_id)
|
||||
.filter(c => pluginData.guild.channels.get(c.message!.channel_id) instanceof TextChannel);
|
||||
|
||||
const contextsByChannelId = contextsWithTextChannels.reduce((map: Map<string, AutomodContext[]>, context) => {
|
||||
if (!map.has(context.message!.channel_id)) {
|
||||
|
@ -40,10 +40,10 @@ export const ReplyAction = automodAction({
|
|||
}, new Map());
|
||||
|
||||
for (const [channelId, _contexts] of contextsByChannelId.entries()) {
|
||||
const users = unique(Array.from(new Set(_contexts.map((c) => c.user).filter(Boolean))));
|
||||
const users = unique(Array.from(new Set(_contexts.map(c => c.user).filter(Boolean))));
|
||||
const user = users[0];
|
||||
|
||||
const renderReplyText = async (str) =>
|
||||
const renderReplyText = async str =>
|
||||
renderTemplate(str, {
|
||||
user: stripObjectToScalars(user),
|
||||
});
|
||||
|
|
|
@ -25,8 +25,8 @@ export const WarnAction = automodAction({
|
|||
extraNotes: matchResult.fullSummary ? [matchResult.fullSummary] : [],
|
||||
};
|
||||
|
||||
const userIdsToWarn = unique(contexts.map((c) => c.user?.id).filter(nonNullish));
|
||||
const membersToWarn = await asyncMap(userIdsToWarn, (id) => resolveMember(pluginData.client, pluginData.guild, id));
|
||||
const userIdsToWarn = unique(contexts.map(c => c.user?.id).filter(nonNullish));
|
||||
const membersToWarn = await asyncMap(userIdsToWarn, id => resolveMember(pluginData.client, pluginData.guild, id));
|
||||
|
||||
const modActions = pluginData.getPlugin(ModActionsPlugin);
|
||||
for (const member of membersToWarn) {
|
||||
|
|
|
@ -4,7 +4,7 @@ import { RECENT_ACTION_EXPIRY_TIME } from "../constants";
|
|||
|
||||
export function clearOldRecentActions(pluginData: GuildPluginData<AutomodPluginType>) {
|
||||
const now = Date.now();
|
||||
pluginData.state.recentActions = pluginData.state.recentActions.filter((info) => {
|
||||
pluginData.state.recentActions = pluginData.state.recentActions.filter(info => {
|
||||
return info.context.timestamp + RECENT_ACTION_EXPIRY_TIME > now;
|
||||
});
|
||||
}
|
||||
|
|
|
@ -4,7 +4,7 @@ import { RECENT_SPAM_EXPIRY_TIME } from "../constants";
|
|||
|
||||
export function clearOldRecentSpam(pluginData: GuildPluginData<AutomodPluginType>) {
|
||||
const now = Date.now();
|
||||
pluginData.state.recentSpam = pluginData.state.recentSpam.filter((spam) => {
|
||||
pluginData.state.recentSpam = pluginData.state.recentSpam.filter(spam => {
|
||||
return spam.timestamp + RECENT_SPAM_EXPIRY_TIME > now;
|
||||
});
|
||||
}
|
||||
|
|
|
@ -8,7 +8,7 @@ export function clearRecentActionsForMessage(pluginData: GuildPluginData<Automod
|
|||
const globalIdentifier = message.user_id;
|
||||
const perChannelIdentifier = `${message.channel_id}-${message.user_id}`;
|
||||
|
||||
pluginData.state.recentActions = pluginData.state.recentActions.filter((act) => {
|
||||
pluginData.state.recentActions = pluginData.state.recentActions.filter(act => {
|
||||
return act.identifier !== globalIdentifier && act.identifier !== perChannelIdentifier;
|
||||
});
|
||||
}
|
||||
|
|
|
@ -60,7 +60,7 @@ export function createMessageSpamTrigger(spamType: RecentActionType, prettyName:
|
|||
|
||||
if (matchedSpam) {
|
||||
const messages = matchedSpam.recentActions
|
||||
.map((action) => action.context.message)
|
||||
.map(action => action.context.message)
|
||||
.filter(Boolean)
|
||||
.sort(sorter("posted_at")) as SavedMessage[];
|
||||
|
||||
|
@ -75,8 +75,8 @@ export function createMessageSpamTrigger(spamType: RecentActionType, prettyName:
|
|||
|
||||
return {
|
||||
extraContexts: matchedSpam.recentActions
|
||||
.map((action) => action.context)
|
||||
.filter((_context) => _context !== context),
|
||||
.map(action => action.context)
|
||||
.filter(_context => _context !== context),
|
||||
|
||||
extra: {
|
||||
archiveId,
|
||||
|
|
|
@ -7,7 +7,7 @@ export function findRecentSpam(
|
|||
type: RecentActionType,
|
||||
identifier?: string,
|
||||
) {
|
||||
return pluginData.state.recentSpam.find((spam) => {
|
||||
return pluginData.state.recentSpam.find(spam => {
|
||||
return spam.type === type && (!identifier || spam.identifiers.includes(identifier));
|
||||
});
|
||||
}
|
||||
|
|
|
@ -11,7 +11,7 @@ export function getMatchingRecentActions(
|
|||
) {
|
||||
to = to || Date.now();
|
||||
|
||||
return pluginData.state.recentActions.filter((action) => {
|
||||
return pluginData.state.recentActions.filter(action => {
|
||||
return (
|
||||
action.type === type &&
|
||||
(!identifier || action.identifier === identifier) &&
|
||||
|
|
|
@ -15,7 +15,7 @@ export const ExampleTrigger = automodTrigger<ExampleMatchResultType>()({
|
|||
},
|
||||
|
||||
async match({ triggerConfig, context }) {
|
||||
const foundFruit = triggerConfig.allowedFruits.find((fruit) => context.message?.data.content === fruit);
|
||||
const foundFruit = triggerConfig.allowedFruits.find(fruit => context.message?.data.content === fruit);
|
||||
if (foundFruit) {
|
||||
return {
|
||||
extra: {
|
||||
|
|
|
@ -37,10 +37,13 @@ export const MatchAttachmentTypeTrigger = automodTrigger<MatchResultType>()({
|
|||
const attachments: any[] = context.message.data.attachments;
|
||||
|
||||
for (const attachment of attachments) {
|
||||
const attachmentType = attachment.filename.split(".").pop().toLowerCase();
|
||||
const attachmentType = attachment.filename
|
||||
.split(".")
|
||||
.pop()
|
||||
.toLowerCase();
|
||||
|
||||
const blacklist = trigger.blacklist_enabled
|
||||
? (trigger.filetype_blacklist || []).map((_t) => _t.toLowerCase())
|
||||
? (trigger.filetype_blacklist || []).map(_t => _t.toLowerCase())
|
||||
: null;
|
||||
|
||||
if (blacklist && blacklist.includes(attachmentType)) {
|
||||
|
@ -53,7 +56,7 @@ export const MatchAttachmentTypeTrigger = automodTrigger<MatchResultType>()({
|
|||
}
|
||||
|
||||
const whitelist = trigger.whitelist_enabled
|
||||
? (trigger.filetype_whitelist || []).map((_t) => _t.toLowerCase())
|
||||
? (trigger.filetype_whitelist || []).map(_t => _t.toLowerCase())
|
||||
: null;
|
||||
|
||||
if (whitelist && !whitelist.includes(attachmentType)) {
|
||||
|
|
|
@ -64,7 +64,7 @@ export const MatchWordsTrigger = automodTrigger<MatchResultType>()({
|
|||
// When performing loose matching, allow any amount of whitespace or up to looseMatchingThreshold number of other
|
||||
// characters between the matched characters. E.g. if we're matching banana, a loose match could also match b a n a n a
|
||||
let pattern = trigger.loose_matching
|
||||
? [...word].map((c) => escapeStringRegexp(c)).join(`(?:\\s*|.{0,${looseMatchingThreshold})`)
|
||||
? [...word].map(c => escapeStringRegexp(c)).join(`(?:\\s*|.{0,${looseMatchingThreshold})`)
|
||||
: escapeStringRegexp(word);
|
||||
|
||||
if (trigger.only_full_words) {
|
||||
|
|
|
@ -30,7 +30,7 @@ export const MemberJoinSpamTrigger = automodTrigger<unknown>()({
|
|||
const totalCount = sumRecentActionCounts(matchingActions);
|
||||
|
||||
if (totalCount >= triggerConfig.amount) {
|
||||
const extraContexts = matchingActions.map((a) => a.context).filter((c) => c !== context);
|
||||
const extraContexts = matchingActions.map(a => a.context).filter(c => c !== context);
|
||||
|
||||
pluginData.state.recentSpam.push({
|
||||
type: RecentActionType.MemberJoin,
|
||||
|
|
|
@ -35,7 +35,7 @@ export const AddDashboardUserCmd = botControlCmd({
|
|||
}
|
||||
|
||||
const userNameList = args.users.map(
|
||||
(user) => `<@!${user.id}> (**${user.username}#${user.discriminator}**, \`${user.id}\`)`,
|
||||
user => `<@!${user.id}> (**${user.username}#${user.discriminator}**, \`${user.id}\`)`,
|
||||
);
|
||||
sendSuccessMessage(
|
||||
pluginData,
|
||||
|
|
|
@ -23,9 +23,9 @@ export const ListDashboardUsersCmd = botControlCmd({
|
|||
}
|
||||
|
||||
const dashboardUsers = await pluginData.state.apiPermissionAssignments.getByGuildId(guild.id);
|
||||
const users = await Promise.all(dashboardUsers.map((perm) => resolveUser(pluginData.client, perm.target_id)));
|
||||
const users = await Promise.all(dashboardUsers.map(perm => resolveUser(pluginData.client, perm.target_id)));
|
||||
const userNameList = users.map(
|
||||
(user) => `<@!${user.id}> (**${user.username}#${user.discriminator}**, \`${user.id}\`)`,
|
||||
user => `<@!${user.id}> (**${user.username}#${user.discriminator}**, \`${user.id}\`)`,
|
||||
);
|
||||
|
||||
sendSuccessMessage(
|
||||
|
|
|
@ -35,7 +35,7 @@ export const RemoveDashboardUserCmd = botControlCmd({
|
|||
}
|
||||
|
||||
const userNameList = args.users.map(
|
||||
(user) => `<@!${user.id}> (**${user.username}#${user.discriminator}**, \`${user.id}\`)`,
|
||||
user => `<@!${user.id}> (**${user.username}#${user.discriminator}**, \`${user.id}\`)`,
|
||||
);
|
||||
sendSuccessMessage(
|
||||
pluginData,
|
||||
|
|
|
@ -21,7 +21,7 @@ export const ServersCmd = botControlCmd({
|
|||
|
||||
async run({ pluginData, message: msg, args }) {
|
||||
const showList = Boolean(args.all || args.initialized || args.uninitialized || args.search);
|
||||
const search = args.search ? new RegExp([...args.search].map((s) => escapeStringRegexp(s)).join(".*"), "i") : null;
|
||||
const search = args.search ? new RegExp([...args.search].map(s => escapeStringRegexp(s)).join(".*"), "i") : null;
|
||||
|
||||
const joinedGuilds = Array.from(pluginData.client.guilds.values());
|
||||
const loadedGuilds = pluginData.getKnubInstance().getLoadedGuilds();
|
||||
|
@ -31,21 +31,21 @@ export const ServersCmd = botControlCmd({
|
|||
let filteredGuilds = Array.from(joinedGuilds);
|
||||
|
||||
if (args.initialized) {
|
||||
filteredGuilds = filteredGuilds.filter((g) => loadedGuildsMap.has(g.id));
|
||||
filteredGuilds = filteredGuilds.filter(g => loadedGuildsMap.has(g.id));
|
||||
}
|
||||
|
||||
if (args.uninitialized) {
|
||||
filteredGuilds = filteredGuilds.filter((g) => !loadedGuildsMap.has(g.id));
|
||||
filteredGuilds = filteredGuilds.filter(g => !loadedGuildsMap.has(g.id));
|
||||
}
|
||||
|
||||
if (args.search) {
|
||||
filteredGuilds = filteredGuilds.filter((g) => search!.test(`${g.id} ${g.name}`));
|
||||
filteredGuilds = filteredGuilds.filter(g => search!.test(`${g.id} ${g.name}`));
|
||||
}
|
||||
|
||||
if (filteredGuilds.length) {
|
||||
filteredGuilds.sort(sorter((g) => g.name.toLowerCase()));
|
||||
filteredGuilds.sort(sorter(g => g.name.toLowerCase()));
|
||||
const longestId = filteredGuilds.reduce((longest, guild) => Math.max(longest, guild.id.length), 0);
|
||||
const lines = filteredGuilds.map((g) => {
|
||||
const lines = filteredGuilds.map(g => {
|
||||
const paddedId = g.id.padEnd(longestId, " ");
|
||||
const owner = getUser(pluginData.client, g.ownerID);
|
||||
return `\`${paddedId}\` **${g.name}** (${g.memberCount} members) (owner **${owner.username}#${owner.discriminator}** \`${owner.id}\`)`;
|
||||
|
@ -56,7 +56,7 @@ export const ServersCmd = botControlCmd({
|
|||
}
|
||||
} else {
|
||||
const total = joinedGuilds.length;
|
||||
const initialized = joinedGuilds.filter((g) => loadedGuildsMap.has(g.id)).length;
|
||||
const initialized = joinedGuilds.filter(g => loadedGuildsMap.has(g.id)).length;
|
||||
const unInitialized = total - initialized;
|
||||
|
||||
msg.channel.createMessage(
|
||||
|
|
|
@ -22,7 +22,7 @@ export async function createCaseNote(pluginData: GuildPluginData<CasesPluginType
|
|||
|
||||
// Add note details to the beginning of the note
|
||||
if (args.noteDetails && args.noteDetails.length) {
|
||||
body = args.noteDetails.map((d) => `__[${d}]__`).join(" ") + " " + body;
|
||||
body = args.noteDetails.map(d => `__[${d}]__`).join(" ") + " " + body;
|
||||
}
|
||||
|
||||
await pluginData.state.cases.createNote(theCase.id, {
|
||||
|
|
|
@ -7,11 +7,11 @@ export async function getCaseTypeAmountForUserId(
|
|||
userID: string,
|
||||
type: CaseTypes,
|
||||
): Promise<number> {
|
||||
const cases = (await pluginData.state.cases.getByUserId(userID)).filter((c) => !c.is_hidden);
|
||||
const cases = (await pluginData.state.cases.getByUserId(userID)).filter(c => !c.is_hidden);
|
||||
let typeAmount = 0;
|
||||
|
||||
if (cases.length > 0) {
|
||||
cases.forEach((singleCase) => {
|
||||
cases.forEach(singleCase => {
|
||||
if (singleCase.type === type.valueOf()) {
|
||||
typeAmount++;
|
||||
}
|
||||
|
|
|
@ -65,10 +65,10 @@ export const CensorPlugin = zeppelinGuildPlugin<CensorPluginType>()("censor", {
|
|||
|
||||
state.regexRunner = getRegExpRunner(`guild-${pluginData.guild.id}`);
|
||||
|
||||
state.onMessageCreateFn = (msg) => onMessageCreate(pluginData, msg);
|
||||
state.onMessageCreateFn = msg => onMessageCreate(pluginData, msg);
|
||||
state.savedMessages.events.on("create", state.onMessageCreateFn);
|
||||
|
||||
state.onMessageUpdateFn = (msg) => onMessageUpdate(pluginData, msg);
|
||||
state.onMessageUpdateFn = msg => onMessageUpdate(pluginData, msg);
|
||||
state.savedMessages.events.on("update", state.onMessageUpdateFn);
|
||||
},
|
||||
|
||||
|
|
|
@ -20,7 +20,7 @@ export async function applyFiltersToMsg(
|
|||
let messageContent = savedMessage.data.content || "";
|
||||
if (savedMessage.data.attachments) messageContent += " " + JSON.stringify(savedMessage.data.attachments);
|
||||
if (savedMessage.data.embeds) {
|
||||
const embeds = (savedMessage.data.embeds as Embed[]).map((e) => cloneDeep(e));
|
||||
const embeds = (savedMessage.data.embeds as Embed[]).map(e => cloneDeep(e));
|
||||
for (const embed of embeds) {
|
||||
if (embed.type === "video") {
|
||||
// Ignore video descriptions as they're not actually shown on the embed
|
||||
|
@ -53,7 +53,7 @@ export async function applyFiltersToMsg(
|
|||
const inviteCodes = getInviteCodesInString(messageContent);
|
||||
|
||||
const invites: Array<Invite | null> = await Promise.all(
|
||||
inviteCodes.map((code) => resolveInvite(pluginData.client, code)),
|
||||
inviteCodes.map(code => resolveInvite(pluginData.client, code)),
|
||||
);
|
||||
|
||||
for (const invite of invites) {
|
||||
|
|
|
@ -66,9 +66,9 @@ export const ArchiveChannelCmd = channelArchiverCmd({
|
|||
|
||||
for (const message of messages) {
|
||||
const ts = moment.utc(message.timestamp).format("YYYY-MM-DD HH:mm:ss");
|
||||
let content = `[${ts}] [${message.author.id}] [${message.author.username}#${message.author.discriminator}]: ${
|
||||
message.content || "<no text content>"
|
||||
}`;
|
||||
let content = `[${ts}] [${message.author.id}] [${message.author.username}#${
|
||||
message.author.discriminator
|
||||
}]: ${message.content || "<no text content>"}`;
|
||||
|
||||
if (message.attachments.length) {
|
||||
if (args["attachment-channel"]) {
|
||||
|
|
|
@ -14,9 +14,9 @@ export function getCompanionChannelOptsForVoiceChannelId(
|
|||
const config = pluginData.config.getMatchingConfig({ userId, channelId: voiceChannel.id });
|
||||
return Object.values(config.entries)
|
||||
.filter(
|
||||
(opts) =>
|
||||
opts =>
|
||||
opts.voice_channel_ids.includes(voiceChannel.id) ||
|
||||
(voiceChannel.parentID && opts.voice_channel_ids.includes(voiceChannel.parentID)),
|
||||
)
|
||||
.map((opts) => Object.assign({}, defaultCompanionChannelOpts, opts));
|
||||
.map(opts => Object.assign({}, defaultCompanionChannelOpts, opts));
|
||||
}
|
||||
|
|
|
@ -44,7 +44,7 @@ const defaultOptions: PluginOptions<CountersPluginType> = {
|
|||
],
|
||||
};
|
||||
|
||||
const configPreprocessor: ConfigPreprocessorFn<CountersPluginType> = (options) => {
|
||||
const configPreprocessor: ConfigPreprocessorFn<CountersPluginType> = options => {
|
||||
for (const counter of Object.values(options.config?.counters || {})) {
|
||||
counter.per_user = counter.per_user ?? false;
|
||||
counter.per_channel = counter.per_channel ?? false;
|
||||
|
|
|
@ -37,10 +37,10 @@ export async function changeCounterValue(
|
|||
if (triggers) {
|
||||
const triggersArr = Array.from(triggers.values());
|
||||
await Promise.all(
|
||||
triggersArr.map((trigger) => checkCounterTrigger(pluginData, counterName, trigger, channelId, userId)),
|
||||
triggersArr.map(trigger => checkCounterTrigger(pluginData, counterName, trigger, channelId, userId)),
|
||||
);
|
||||
await Promise.all(
|
||||
triggersArr.map((trigger) => checkReverseCounterTrigger(pluginData, counterName, trigger, channelId, userId)),
|
||||
triggersArr.map(trigger => checkReverseCounterTrigger(pluginData, counterName, trigger, channelId, userId)),
|
||||
);
|
||||
}
|
||||
|
||||
|
|
|
@ -24,8 +24,8 @@ export async function decayCounter(
|
|||
const triggers = pluginData.state.counterTriggersByCounterId.get(counterId);
|
||||
if (triggers) {
|
||||
const triggersArr = Array.from(triggers.values());
|
||||
await Promise.all(triggersArr.map((trigger) => checkAllValuesForTrigger(pluginData, counterName, trigger)));
|
||||
await Promise.all(triggersArr.map((trigger) => checkAllValuesForReverseTrigger(pluginData, counterName, trigger)));
|
||||
await Promise.all(triggersArr.map(trigger => checkAllValuesForTrigger(pluginData, counterName, trigger)));
|
||||
await Promise.all(triggersArr.map(trigger => checkAllValuesForReverseTrigger(pluginData, counterName, trigger)));
|
||||
}
|
||||
|
||||
lock.unlock();
|
||||
|
|
|
@ -34,10 +34,10 @@ export async function setCounterValue(
|
|||
if (triggers) {
|
||||
const triggersArr = Array.from(triggers.values());
|
||||
await Promise.all(
|
||||
triggersArr.map((trigger) => checkCounterTrigger(pluginData, counterName, trigger, channelId, userId)),
|
||||
triggersArr.map(trigger => checkCounterTrigger(pluginData, counterName, trigger, channelId, userId)),
|
||||
);
|
||||
await Promise.all(
|
||||
triggersArr.map((trigger) => checkReverseCounterTrigger(pluginData, counterName, trigger, channelId, userId)),
|
||||
triggersArr.map(trigger => checkReverseCounterTrigger(pluginData, counterName, trigger, channelId, userId)),
|
||||
);
|
||||
}
|
||||
|
||||
|
|
|
@ -5,7 +5,7 @@ export const GuildBanRemoveAlertsEvt = locateUserEvt({
|
|||
|
||||
async listener(meta) {
|
||||
const alerts = await meta.pluginData.state.alerts.getAlertsByUserId(meta.args.user.id);
|
||||
alerts.forEach((alert) => {
|
||||
alerts.forEach(alert => {
|
||||
meta.pluginData.state.alerts.delete(alert.id);
|
||||
});
|
||||
},
|
||||
|
|
|
@ -29,7 +29,7 @@ export const ChannelLeaveAlertsEvt = locateUserEvt({
|
|||
const triggeredAlerts = await meta.pluginData.state.alerts.getAlertsByUserId(meta.args.member.id);
|
||||
const voiceChannel = meta.args.oldChannel as VoiceChannel;
|
||||
|
||||
triggeredAlerts.forEach((alert) => {
|
||||
triggeredAlerts.forEach(alert => {
|
||||
const txtChannel = meta.pluginData.client.getChannel(alert.channel_id) as TextableChannel;
|
||||
txtChannel.createMessage(
|
||||
`🔴 <@!${alert.requestor_id}> the user <@!${alert.user_id}> disconnected out of \`${voiceChannel.name}\``,
|
||||
|
|
|
@ -4,7 +4,7 @@ import { LocateUserPluginType } from "../types";
|
|||
export async function fillActiveAlertsList(pluginData: GuildPluginData<LocateUserPluginType>) {
|
||||
const allAlerts = await pluginData.state.alerts.getAllGuildAlerts();
|
||||
|
||||
allAlerts.forEach((alert) => {
|
||||
allAlerts.forEach(alert => {
|
||||
if (!pluginData.state.usersWithAlerts.includes(alert.user_id)) {
|
||||
pluginData.state.usersWithAlerts.push(alert.user_id);
|
||||
}
|
||||
|
|
|
@ -10,7 +10,7 @@ export async function sendAlerts(pluginData: GuildPluginData<LocateUserPluginTyp
|
|||
const member = await resolveMember(pluginData.client, pluginData.guild, userId);
|
||||
if (!member) return;
|
||||
|
||||
triggeredAlerts.forEach((alert) => {
|
||||
triggeredAlerts.forEach(alert => {
|
||||
const prepend = `<@!${alert.requestor_id}>, an alert requested by you has triggered!\nReminder: \`${alert.body}\`\n`;
|
||||
const txtChannel = pluginData.client.getChannel(alert.channel_id) as TextableChannel;
|
||||
sendWhere(pluginData, member, txtChannel, prepend);
|
||||
|
|
|
@ -97,10 +97,10 @@ export const LogsPlugin = zeppelinGuildPlugin<LogsPluginType>()("logs", {
|
|||
|
||||
state.batches = new Map();
|
||||
|
||||
state.onMessageDeleteFn = (msg) => onMessageDelete(pluginData, msg);
|
||||
state.onMessageDeleteFn = msg => onMessageDelete(pluginData, msg);
|
||||
state.savedMessages.events.on("delete", state.onMessageDeleteFn);
|
||||
|
||||
state.onMessageDeleteBulkFn = (msg) => onMessageDeleteBulk(pluginData, msg);
|
||||
state.onMessageDeleteBulkFn = msg => onMessageDeleteBulk(pluginData, msg);
|
||||
state.savedMessages.events.on("deleteBulk", state.onMessageDeleteBulkFn);
|
||||
|
||||
state.onMessageUpdateFn = (newMsg, oldMsg) => onMessageUpdate(pluginData, newMsg, oldMsg);
|
||||
|
|
|
@ -24,7 +24,7 @@ export const LogsGuildMemberAddEvt = logsEvt({
|
|||
account_age: accountAge,
|
||||
});
|
||||
|
||||
const cases = (await pluginData.state.cases.with("notes").getByUserId(member.id)).filter((c) => !c.is_hidden);
|
||||
const cases = (await pluginData.state.cases.with("notes").getByUserId(member.id)).filter(c => !c.is_hidden);
|
||||
cases.sort((a, b) => (a.created_at > b.created_at ? -1 : 1));
|
||||
|
||||
if (cases.length) {
|
||||
|
|
|
@ -61,12 +61,12 @@ export const LogsGuildMemberUpdateEvt = logsEvt({
|
|||
{
|
||||
member: logMember,
|
||||
addedRoles: addedRoles
|
||||
.map((roleId) => pluginData.guild.roles.get(roleId) || { id: roleId, name: `Unknown (${roleId})` })
|
||||
.map((r) => r.name)
|
||||
.map(roleId => pluginData.guild.roles.get(roleId) || { id: roleId, name: `Unknown (${roleId})` })
|
||||
.map(r => r.name)
|
||||
.join(", "),
|
||||
removedRoles: removedRoles
|
||||
.map((roleId) => pluginData.guild.roles.get(roleId) || { id: roleId, name: `Unknown (${roleId})` })
|
||||
.map((r) => r.name)
|
||||
.map(roleId => pluginData.guild.roles.get(roleId) || { id: roleId, name: `Unknown (${roleId})` })
|
||||
.map(r => r.name)
|
||||
.join(", "),
|
||||
mod: stripObjectToScalars(mod),
|
||||
},
|
||||
|
@ -79,8 +79,8 @@ export const LogsGuildMemberUpdateEvt = logsEvt({
|
|||
{
|
||||
member: logMember,
|
||||
roles: addedRoles
|
||||
.map((roleId) => pluginData.guild.roles.get(roleId) || { id: roleId, name: `Unknown (${roleId})` })
|
||||
.map((r) => r.name)
|
||||
.map(roleId => pluginData.guild.roles.get(roleId) || { id: roleId, name: `Unknown (${roleId})` })
|
||||
.map(r => r.name)
|
||||
.join(", "),
|
||||
mod: stripObjectToScalars(mod),
|
||||
},
|
||||
|
@ -93,8 +93,8 @@ export const LogsGuildMemberUpdateEvt = logsEvt({
|
|||
{
|
||||
member: logMember,
|
||||
roles: removedRoles
|
||||
.map((roleId) => pluginData.guild.roles.get(roleId) || { id: roleId, name: `Unknown (${roleId})` })
|
||||
.map((r) => r.name)
|
||||
.map(roleId => pluginData.guild.roles.get(roleId) || { id: roleId, name: `Unknown (${roleId})` })
|
||||
.map(r => r.name)
|
||||
.join(", "),
|
||||
mod: stripObjectToScalars(mod),
|
||||
},
|
||||
|
|
|
@ -41,7 +41,7 @@ export async function getLogMessage(
|
|||
const values = {
|
||||
...data,
|
||||
timestamp,
|
||||
userMention: async (inputUserOrMember) => {
|
||||
userMention: async inputUserOrMember => {
|
||||
if (!inputUserOrMember) return "";
|
||||
|
||||
const usersOrMembers = Array.isArray(inputUserOrMember) ? inputUserOrMember : [inputUserOrMember];
|
||||
|
@ -71,7 +71,7 @@ export async function getLogMessage(
|
|||
|
||||
return mentions.join(", ");
|
||||
},
|
||||
channelMention: (channel) => {
|
||||
channelMention: channel => {
|
||||
if (!channel) return "";
|
||||
return verboseChannelMention(channel);
|
||||
},
|
||||
|
@ -83,12 +83,12 @@ export async function getLogMessage(
|
|||
|
||||
if (type === LogType.BOT_ALERT) {
|
||||
const valuesWithoutTmplEval = { ...values };
|
||||
values.tmplEval = (str) => {
|
||||
values.tmplEval = str => {
|
||||
return renderTemplate(str, valuesWithoutTmplEval);
|
||||
};
|
||||
}
|
||||
|
||||
const renderLogString = (str) => renderTemplate(str, values);
|
||||
const renderLogString = str => renderTemplate(str, values);
|
||||
|
||||
let formatted;
|
||||
try {
|
||||
|
|
|
@ -8,7 +8,7 @@ export async function onMessageDeleteBulk(pluginData: GuildPluginData<LogsPlugin
|
|||
const channel = pluginData.guild.channels.get(savedMessages[0].channel_id);
|
||||
const archiveId = await pluginData.state.archives.createFromSavedMessages(savedMessages, pluginData.guild);
|
||||
const archiveUrl = pluginData.state.archives.getUrl(getBaseUrl(pluginData), archiveId);
|
||||
const authorIds = Array.from(new Set(savedMessages.map((item) => `\`${item.user_id}\``))).join(", ");
|
||||
const authorIds = Array.from(new Set(savedMessages.map(item => `\`${item.user_id}\``))).join(", ");
|
||||
|
||||
pluginData.state.guildLogs.log(
|
||||
LogType.MESSAGE_DELETE_BULK,
|
||||
|
|
|
@ -15,12 +15,12 @@ export async function onMessageUpdate(
|
|||
let logUpdate = false;
|
||||
|
||||
const oldEmbedsToCompare = ((oldSavedMessage.data.embeds || []) as Embed[])
|
||||
.map((e) => cloneDeep(e))
|
||||
.filter((e) => (e as Embed).type === "rich");
|
||||
.map(e => cloneDeep(e))
|
||||
.filter(e => (e as Embed).type === "rich");
|
||||
|
||||
const newEmbedsToCompare = ((savedMessage.data.embeds || []) as Embed[])
|
||||
.map((e) => cloneDeep(e))
|
||||
.filter((e) => (e as Embed).type === "rich");
|
||||
.map(e => cloneDeep(e))
|
||||
.filter(e => (e as Embed).type === "rich");
|
||||
|
||||
for (const embed of [...oldEmbedsToCompare, ...newEmbedsToCompare]) {
|
||||
if (embed.thumbnail) {
|
||||
|
|
|
@ -19,7 +19,7 @@ export const SavePinsToDBCmd = messageSaverCmd({
|
|||
const { savedCount, failed } = await saveMessagesToDB(
|
||||
pluginData,
|
||||
args.channel,
|
||||
pins.map((m) => m.id),
|
||||
pins.map(m => m.id),
|
||||
);
|
||||
|
||||
if (failed.length) {
|
||||
|
|
|
@ -51,7 +51,7 @@ export const MessageDeleteBulkEvt = messageSaverEvt({
|
|||
allowSelf: true,
|
||||
|
||||
async listener(meta) {
|
||||
const ids = meta.args.messages.map((m) => m.id);
|
||||
const ids = meta.args.messages.map(m => m.id);
|
||||
await meta.pluginData.state.savedMessages.markBulkAsDeleted(ids);
|
||||
},
|
||||
});
|
||||
|
|
|
@ -47,9 +47,9 @@ export const CasesModCmd = modActionsCmd({
|
|||
pluginData.client,
|
||||
msg.channel,
|
||||
totalPages,
|
||||
async (page) => {
|
||||
async page => {
|
||||
const cases = await casesPlugin.getRecentCasesByMod(modId, casesPerPage, (page - 1) * casesPerPage);
|
||||
const lines = await asyncMap(cases, (c) => casesPlugin.getCaseSummary(c, true, msg.author.id));
|
||||
const lines = await asyncMap(cases, c => casesPlugin.getCaseSummary(c, true, msg.author.id));
|
||||
|
||||
const firstCaseNum = (page - 1) * casesPerPage + 1;
|
||||
const lastCaseNum = page * casesPerPage;
|
||||
|
|
|
@ -42,8 +42,8 @@ export const CasesUserCmd = modActionsCmd({
|
|||
}
|
||||
|
||||
const cases = await pluginData.state.cases.with("notes").getByUserId(user.id);
|
||||
const normalCases = cases.filter((c) => !c.is_hidden);
|
||||
const hiddenCases = cases.filter((c) => c.is_hidden);
|
||||
const normalCases = cases.filter(c => !c.is_hidden);
|
||||
const hiddenCases = cases.filter(c => c.is_hidden);
|
||||
|
||||
const userName =
|
||||
user instanceof UnknownUser && cases.length
|
||||
|
@ -70,7 +70,7 @@ export const CasesUserCmd = modActionsCmd({
|
|||
} else {
|
||||
// Compact view (= regular message with a preview of each case)
|
||||
const casesPlugin = pluginData.getPlugin(CasesPlugin);
|
||||
const lines = await asyncMap(casesToDisplay, (c) => casesPlugin.getCaseSummary(c, true, msg.author.id));
|
||||
const lines = await asyncMap(casesToDisplay, c => casesPlugin.getCaseSummary(c, true, msg.author.id));
|
||||
|
||||
const prefix = getGuildPrefix(pluginData);
|
||||
const linesPerChunk = 10;
|
||||
|
|
|
@ -52,7 +52,7 @@ export const MassbanCmd = modActionsCmd({
|
|||
|
||||
// Ignore automatic ban cases and logs for these users
|
||||
// We'll create our own cases below and post a single "mass banned" log instead
|
||||
args.userIds.forEach((userId) => {
|
||||
args.userIds.forEach(userId => {
|
||||
// Use longer timeouts since this can take a while
|
||||
ignoreEvent(pluginData, IgnoredEventType.Ban, userId, 120 * 1000);
|
||||
pluginData.state.serverLogs.ignoreLog(LogType.MEMBER_BAN, userId, 120 * 1000);
|
||||
|
|
|
@ -41,7 +41,7 @@ export const MassunbanCmd = modActionsCmd({
|
|||
|
||||
// Ignore automatic unban cases and logs for these users
|
||||
// We'll create our own cases below and post a single "mass unbanned" log instead
|
||||
args.userIds.forEach((userId) => {
|
||||
args.userIds.forEach(userId => {
|
||||
// Use longer timeouts since this can take a while
|
||||
ignoreEvent(pluginData, IgnoredEventType.Unban, userId, 120 * 1000);
|
||||
pluginData.state.serverLogs.ignoreLog(LogType.MEMBER_UNBAN, userId, 120 * 1000);
|
||||
|
@ -90,19 +90,19 @@ export const MassunbanCmd = modActionsCmd({
|
|||
});
|
||||
|
||||
if (failedUnbans.length) {
|
||||
const notBanned = failedUnbans.filter((x) => x.reason === UnbanFailReasons.NOT_BANNED);
|
||||
const unbanFailed = failedUnbans.filter((x) => x.reason === UnbanFailReasons.UNBAN_FAILED);
|
||||
const notBanned = failedUnbans.filter(x => x.reason === UnbanFailReasons.NOT_BANNED);
|
||||
const unbanFailed = failedUnbans.filter(x => x.reason === UnbanFailReasons.UNBAN_FAILED);
|
||||
|
||||
let failedMsg = "";
|
||||
if (notBanned.length > 0) {
|
||||
failedMsg += `${notBanned.length}x ${UnbanFailReasons.NOT_BANNED}:`;
|
||||
notBanned.forEach((fail) => {
|
||||
notBanned.forEach(fail => {
|
||||
failedMsg += " " + fail.userId;
|
||||
});
|
||||
}
|
||||
if (unbanFailed.length > 0) {
|
||||
failedMsg += `\n${unbanFailed.length}x ${UnbanFailReasons.UNBAN_FAILED}:`;
|
||||
unbanFailed.forEach((fail) => {
|
||||
unbanFailed.forEach(fail => {
|
||||
failedMsg += " " + fail.userId;
|
||||
});
|
||||
}
|
||||
|
|
|
@ -52,7 +52,7 @@ export const MassmuteCmd = modActionsCmd({
|
|||
|
||||
// Ignore automatic mute cases and logs for these users
|
||||
// We'll create our own cases below and post a single "mass muted" log instead
|
||||
args.userIds.forEach((userId) => {
|
||||
args.userIds.forEach(userId => {
|
||||
// Use longer timeouts since this can take a while
|
||||
pluginData.state.serverLogs.ignoreLog(LogType.MEMBER_MUTE, userId, 120 * 1000);
|
||||
});
|
||||
|
|
|
@ -7,7 +7,7 @@ export function clearIgnoredEvents(
|
|||
userId: string,
|
||||
) {
|
||||
pluginData.state.ignoredEvents.splice(
|
||||
pluginData.state.ignoredEvents.findIndex((info) => type === info.type && userId === info.userId),
|
||||
pluginData.state.ignoredEvents.findIndex(info => type === info.type && userId === info.userId),
|
||||
1,
|
||||
);
|
||||
}
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
import { Attachment } from "eris";
|
||||
|
||||
export function formatReasonWithAttachments(reason: string, attachments: Attachment[]) {
|
||||
const attachmentUrls = attachments.map((a) => a.url);
|
||||
const attachmentUrls = attachments.map(a => a.url);
|
||||
return ((reason || "") + " " + attachmentUrls.join(" ")).trim();
|
||||
}
|
||||
|
|
|
@ -5,7 +5,7 @@ import { isDiscordHTTPError } from "../../../utils";
|
|||
export async function isBanned(pluginData: GuildPluginData<ModActionsPluginType>, userId: string): Promise<boolean> {
|
||||
try {
|
||||
const bans = await pluginData.guild.getBans();
|
||||
return bans.some((b) => b.user.id === userId);
|
||||
return bans.some(b => b.user.id === userId);
|
||||
} catch (e) {
|
||||
if (isDiscordHTTPError(e) && e.code === 500) {
|
||||
return false;
|
||||
|
|
|
@ -6,5 +6,5 @@ export function isEventIgnored(
|
|||
type: IgnoredEventType,
|
||||
userId: string,
|
||||
) {
|
||||
return pluginData.state.ignoredEvents.some((info) => type === info.type && userId === info.userId);
|
||||
return pluginData.state.ignoredEvents.some(info => type === info.type && userId === info.userId);
|
||||
}
|
||||
|
|
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue