mirror of
https://github.com/nx-bat/discordbot-ng.git
synced 2026-09-22 10:29:10 -04:00
Initial commit.
This commit is contained in:
@@ -0,0 +1,94 @@
|
||||
import { APIEmbedField, APIRole, AuditLogChange, AuditLogEvent, EmbedBuilder, EmbedField, Guild, GuildAuditLogsEntry, PermissionsBitField, Role, RoleFlags, SlashCommandSubcommandGroupBuilder, SnowflakeUtil } from 'discord.js';
|
||||
import { formatChanges, formatExtras, formatSnowflake, getTargetType } from '../utils';
|
||||
import { Database } from '../shared/Database';
|
||||
|
||||
const IGNORED_ACTIONS = [
|
||||
AuditLogEvent.MemberMove,
|
||||
// Handled by automod.
|
||||
AuditLogEvent.AutoModerationFlagToChannel
|
||||
];
|
||||
|
||||
export async function handleAuditLogCreate(entry: GuildAuditLogsEntry, guild: Guild) {
|
||||
if (!await shouldLog(entry, guild)) return;
|
||||
const settings = await Database.getGuildSettings(guild.id);
|
||||
|
||||
if (!settings || !settings.audit_logs_channel_id) return;
|
||||
|
||||
const channel = await guild.channels.fetch(settings.audit_logs_channel_id);
|
||||
|
||||
if (!channel || !channel.isSendable()) return;
|
||||
|
||||
const fields: APIEmbedField[] = [
|
||||
{
|
||||
name: 'Actor',
|
||||
value: `<@${entry.executorId}>`,
|
||||
inline: true
|
||||
}
|
||||
];
|
||||
|
||||
if (entry.targetId) {
|
||||
const targetType = getTargetType(entry.action);
|
||||
fields.push({
|
||||
name: 'Target',
|
||||
value: formatSnowflake(entry.targetId, targetType),
|
||||
inline: true
|
||||
});
|
||||
}
|
||||
|
||||
if (entry.reason) {
|
||||
fields.push({
|
||||
name: 'Reason',
|
||||
value: entry.reason,
|
||||
inline: true
|
||||
});
|
||||
}
|
||||
|
||||
if (entry.changes && entry.changes.length > 0) {
|
||||
fields.push({
|
||||
name: 'Changes',
|
||||
value: formatChanges(entry),
|
||||
inline: false
|
||||
});
|
||||
}
|
||||
|
||||
if (entry.extra) {
|
||||
fields.push({
|
||||
name: 'Options',
|
||||
value: formatExtras(entry, guild),
|
||||
inline: false
|
||||
});
|
||||
}
|
||||
|
||||
const embed = new EmbedBuilder()
|
||||
.setTitle(Object.keys(AuditLogEvent)[Object.values(AuditLogEvent).indexOf(entry.action)])
|
||||
.setTimestamp(Number(SnowflakeUtil.decode(entry.id).timestamp))
|
||||
.addFields(...fields);
|
||||
|
||||
channel.send({ embeds: [embed] });
|
||||
}
|
||||
|
||||
async function shouldLog(entry: GuildAuditLogsEntry, guild: Guild): Promise<boolean> {
|
||||
if (!entry.executorId) return true;
|
||||
|
||||
if (IGNORED_ACTIONS.some(a => entry.action == a)) return false;
|
||||
|
||||
if (entry.action == AuditLogEvent.MemberRoleUpdate) {
|
||||
return await shouldLogRoleChanges(entry as GuildAuditLogsEntry<AuditLogEvent.MemberRoleUpdate>, guild);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
async function shouldLogRoleChanges(entry: GuildAuditLogsEntry<AuditLogEvent.MemberRoleUpdate>, guild: Guild): Promise<boolean> {
|
||||
for (const change of entry.changes) {
|
||||
// Get role changes from the log.
|
||||
const roles = (await Promise.all((change.new! as Pick<APIRole, 'id' | 'name'>[]).map(c => guild.roles.fetch(c.id))));
|
||||
|
||||
// Check if role is part of onboarding.
|
||||
for (const role of roles) {
|
||||
if (role && !role.flags.has(RoleFlags.InPrompt)) return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { Database } from '../shared/Database';
|
||||
|
||||
export async function handleGuildCreate(guild) {
|
||||
try {
|
||||
if (!await Database.getGuildSettings(guild.id)) await Database.addGuild(guild.id);
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { GuildMember, GuildTextBasedChannel } from 'discord.js';
|
||||
import { Database } from '../shared/Database';
|
||||
import { config } from '../config';
|
||||
|
||||
export async function handleMemberJoin(member: GuildMember) {
|
||||
const guildSettings = await Database.getGuildSettings(member.guild.id);
|
||||
|
||||
if (guildSettings?.new_member_channel_id) {
|
||||
const e621UserIds = await Database.getE621Ids(member.id);
|
||||
const channel = await member.guild.channels.fetch(guildSettings.new_member_channel_id) as GuildTextBasedChannel;
|
||||
|
||||
if (channel) {
|
||||
let content = `${member.toString()}'s e621 and discord account(s):\n`;
|
||||
|
||||
for (const e621Id of e621UserIds) {
|
||||
content += `- ${config.E621_BASE_URL}/users/${e621Id}\n`;
|
||||
|
||||
const discordIds = await Database.getDiscordIds(e621Id);
|
||||
|
||||
for (const discordId of discordIds) {
|
||||
content += `- - <@${discordId}>\n`;
|
||||
}
|
||||
}
|
||||
|
||||
channel.send(content).catch(console.error);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,244 @@
|
||||
import { AllowedMentionsTypes, Message as DiscordMessage, GuildTextBasedChannel, OmitPartialGroupDMChannel, PartialMessage, ReadonlyCollection } from 'discord.js';
|
||||
import { config } from '../config';
|
||||
import { E621Post } from '../types';
|
||||
import { getE621Post, getE621PostByMd5, getPostUrl, hasBlacklistedTags } from '../utils/e621-utils';
|
||||
import { Database } from '../shared/Database';
|
||||
import { logDeletion, logEdit } from '../utils/message-logger';
|
||||
import { isEdited } from '../utils/message-utils';
|
||||
|
||||
export type Message<InGuild extends boolean = boolean> = OmitPartialGroupDMChannel<DiscordMessage<InGuild>>;
|
||||
export type Partial = OmitPartialGroupDMChannel<PartialMessage>;
|
||||
|
||||
// TODO: I don't know of any good way to not hardcode this regex for e621 links. So I've provided two that may need to have the port altered.
|
||||
const postRegex = new RegExp('!?https?://(?:.*@)?(?:e621|e926)\\.net/+posts/+([0-9]+)', 'gi');
|
||||
const imageRegex = new RegExp('!?https?://(?:.*@)?static[0-9]*\\.(?:e621|e926)\\.net/+data/+(?:sample/+|preview/+|)[\\da-f]{2}/+[\\da-f]{2}/+([\\da-f]{32})\\.[\\da-z]+', 'gi');
|
||||
|
||||
const postRegex_DEV = new RegExp('!?https?://(?:.*@)?localhost:3000/+posts/+([0-9]+)', 'gi');
|
||||
const imageRegex_DEV = new RegExp('!?https?://(?:.*@)?localhost:3000/+data/+(?:sample/+|preview/+|)[\\da-f]{2}/+[\\da-f]{2}/+([\\da-f]{32})\\.[\\da-z]+', 'gi');
|
||||
|
||||
const postIDRegex = new RegExp('post #([0-9]+)', 'gi');
|
||||
const tagSearchRegex = '(?:[\\S]| )+?';
|
||||
const wikiLinkRegex = new RegExp(`\\[\\[(${tagSearchRegex})]]`, 'gi');
|
||||
const searchLinkRegex = new RegExp(`{{(${tagSearchRegex})}}`, 'gi');
|
||||
|
||||
const regexTesters = [
|
||||
{ runInDev: false, regex: postRegex, handler: postHandler },
|
||||
{ runInDev: false, regex: imageRegex, handler: imageHandler },
|
||||
{ runInDev: true, regex: postRegex_DEV, handler: postHandler },
|
||||
{ runInDev: true, regex: imageRegex_DEV, handler: imageHandler },
|
||||
{ runInDev: true, regex: postIDRegex, handler: postIdHandler },
|
||||
{ runInDev: true, regex: wikiLinkRegex, handler: wikiPageHandler },
|
||||
{ runInDev: true, regex: searchLinkRegex, handler: searchHandler }
|
||||
];
|
||||
|
||||
const uniqueRegexMatches = (g, i, a) => a.findIndex(v => v[1] == g[1]) == i;
|
||||
|
||||
export async function handleMessageCreate(message: Message) {
|
||||
if (message.author.bot) return;
|
||||
if (message.inGuild()) await Database.putMessage(message);
|
||||
|
||||
for (const test of regexTesters) {
|
||||
if (config.DEV_MODE && !test.runInDev) continue;
|
||||
|
||||
const hasMatches = test.regex.test(message.content);
|
||||
test.regex.lastIndex = 0;
|
||||
|
||||
if (hasMatches) {
|
||||
const matches: RegExpExecArray[] = [];
|
||||
let match: RegExpExecArray | null;
|
||||
|
||||
while ((match = test.regex.exec(message.content)) != null) {
|
||||
matches.push(match);
|
||||
}
|
||||
test.regex.lastIndex = 0;
|
||||
|
||||
if (!await test.handler(message, matches.filter(uniqueRegexMatches))) return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function handleMessageUpdate(oldMessage: Message | PartialMessage, newMessage: Message) {
|
||||
if (newMessage.author.bot) return;
|
||||
|
||||
const loggedMessage = await Database.getMessageWithRetry(newMessage.id);
|
||||
|
||||
if (!loggedMessage) return;
|
||||
|
||||
if (newMessage.inGuild() && isEdited(loggedMessage, newMessage)) {
|
||||
await Database.putMessage(newMessage);
|
||||
await logEdit(loggedMessage, newMessage);
|
||||
}
|
||||
|
||||
if (loggedMessage.content == newMessage.content) return;
|
||||
|
||||
for (const test of regexTesters) {
|
||||
if (config.DEV_MODE && !test.runInDev) continue;
|
||||
|
||||
const hasMatches = test.regex.test(newMessage.content);
|
||||
test.regex.lastIndex = 0;
|
||||
|
||||
if (hasMatches) {
|
||||
const oldMatches: RegExpExecArray[] = [];
|
||||
const newMatches: RegExpExecArray[] = [];
|
||||
let match: RegExpExecArray | null;
|
||||
|
||||
while ((match = test.regex.exec(newMessage.content)) != null) {
|
||||
newMatches.push(match);
|
||||
}
|
||||
test.regex.lastIndex = 0;
|
||||
|
||||
while ((match = test.regex.exec(loggedMessage.content)) != null) {
|
||||
oldMatches.push(match);
|
||||
}
|
||||
test.regex.lastIndex = 0;
|
||||
|
||||
const properMatches: RegExpExecArray[] = [];
|
||||
|
||||
for (const newMatch of newMatches) {
|
||||
if (!oldMatches.find(m => m[1] == newMatch[1])) properMatches.push(newMatch);
|
||||
}
|
||||
|
||||
if (properMatches.length > 0 && !await test.handler(newMessage, properMatches.filter(uniqueRegexMatches))) return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function handleMessageDelete(message: Message | PartialMessage) {
|
||||
const loggedMessage = await Database.getMessageWithRetry(message.id);
|
||||
|
||||
if (!loggedMessage) return;
|
||||
|
||||
if (message.inGuild()) await logDeletion(loggedMessage, message);
|
||||
}
|
||||
|
||||
export async function handleBulkMessageDelete(messages: ReadonlyCollection<string, Message | Partial>, channel: GuildTextBasedChannel) {
|
||||
for (const message of messages.values()) {
|
||||
await handleMessageDelete(message);
|
||||
}
|
||||
}
|
||||
|
||||
async function searchHandler(message: Message, matchedGroups: RegExpExecArray[]): Promise<boolean> {
|
||||
let content = '';
|
||||
|
||||
for (const group of matchedGroups) {
|
||||
content += `<${config.E621_BASE_URL}/posts?tags=${encodeURIComponent(group[1])}>\n`;
|
||||
}
|
||||
|
||||
await message.reply(content.trim());
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
async function wikiPageHandler(message: Message, matchedGroups: RegExpExecArray[]): Promise<boolean> {
|
||||
let content = '';
|
||||
|
||||
for (const group of matchedGroups) {
|
||||
content += `<${config.E621_BASE_URL}/wiki_pages/${encodeURIComponent(group[1])}>\n`;
|
||||
}
|
||||
|
||||
await message.reply(content.trim());
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
async function blacklistIfNecessary(message: Message, posts: E621Post[]): Promise<boolean> {
|
||||
const staffCategories = await Database.getGuildStaffCategories(message.guildId!);
|
||||
|
||||
const blacklistedIds: number[] = [];
|
||||
|
||||
const channel = await message.channel.fetch() as GuildTextBasedChannel;
|
||||
|
||||
|
||||
for (const post of posts) {
|
||||
if (hasBlacklistedTags(post)) {
|
||||
blacklistedIds.push(post.id);
|
||||
}
|
||||
}
|
||||
|
||||
if (blacklistedIds.length == 0) return false;
|
||||
|
||||
await message.delete();
|
||||
|
||||
if (channel.parentId && staffCategories.includes(channel.parentId)) {
|
||||
await message.channel.send({
|
||||
content: `_sucks message into the void._ ${message.author.toString()} nono, don't post links to ${blacklistedIds.length == 1 ? `post ${blacklistedIds[0]}` : `posts \`${blacklistedIds.join('`, `')}\``}. See rule #5.b for more details.`,
|
||||
allowedMentions: {
|
||||
users: [message.author.id]
|
||||
}
|
||||
});
|
||||
} else {
|
||||
await message.channel.send({
|
||||
content: `_sucks message into the void._ ${message.author.toString()} nono, don't post links to young/cub content. See rule #5.b for more details.`,
|
||||
allowedMentions: {
|
||||
users: [message.author.id]
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
async function postIdHandler(message: Message, matchedGroups: RegExpExecArray[]): Promise<boolean> {
|
||||
if (!message.guildId) return true;
|
||||
|
||||
const posts: E621Post[] = [];
|
||||
|
||||
for (const match of matchedGroups) {
|
||||
try {
|
||||
const post = await getE621Post(match[1]);
|
||||
if (post) posts.push(post);
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
}
|
||||
|
||||
if (await blacklistIfNecessary(message, posts)) return false;
|
||||
|
||||
const content = posts.map(post => getPostUrl(post)).join('\n');
|
||||
|
||||
if (content.length > 0) await message.reply(content);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
async function postHandler(message: Message, matchedGroups: RegExpExecArray[]): Promise<boolean> {
|
||||
if (!message.guildId) return true;
|
||||
|
||||
const posts: E621Post[] = [];
|
||||
|
||||
for (const match of matchedGroups) {
|
||||
try {
|
||||
const post = await getE621Post(match[1]);
|
||||
if (post) posts.push(post);
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
}
|
||||
|
||||
if (await blacklistIfNecessary(message, posts)) return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
async function imageHandler(message: Message, matchedGroups: RegExpExecArray[]): Promise<boolean> {
|
||||
if (!message.guildId) return true;
|
||||
|
||||
const posts: E621Post[] = [];
|
||||
|
||||
for (const match of matchedGroups) {
|
||||
try {
|
||||
const post = await getE621PostByMd5(match[1]);
|
||||
if (post) posts.push(post);
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
}
|
||||
|
||||
if (await blacklistIfNecessary(message, posts)) return false;
|
||||
|
||||
const content = posts.map(post => getPostUrl(post)).join('\n');
|
||||
|
||||
if (content.length > 0) await message.reply(content);
|
||||
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { AnyThreadChannel } from 'discord.js';
|
||||
|
||||
export async function handleThreadCreate(thread: AnyThreadChannel, newlyCreated: boolean) {
|
||||
try {
|
||||
await thread.join();
|
||||
} catch (e) {
|
||||
console.error('Failed to join thread:');
|
||||
console.error(e);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import { Guild, GuildMember, GuildTextBasedChannel, time, TimestampStyles, VoiceBasedChannel, VoiceState } from 'discord.js';
|
||||
import { Database } from '../shared/Database';
|
||||
|
||||
export async function handleVoiceStateUpdate(oldState: VoiceState, newState: VoiceState) {
|
||||
// The logChannel declaration being inside is purposeful, as this event is fired a lot for users talking.
|
||||
if (newState.channelId != null && oldState.channelId != null && newState.channelId != oldState.channelId) {
|
||||
const logChannel = await getVoiceLogsChannel(newState.guild);
|
||||
if (!logChannel) return;
|
||||
|
||||
await sendMovedMessage(logChannel, newState.member!, oldState.channel!, newState.channel!);
|
||||
} else if (oldState.channelId == null && newState.channelId != null) {
|
||||
const logChannel = await getVoiceLogsChannel(newState.guild);
|
||||
if (!logChannel) return;
|
||||
|
||||
await sendJoinMessage(logChannel, newState.member!, newState.channel!);
|
||||
} else if (newState.channelId == null && oldState.channelId != null) {
|
||||
const logChannel = await getVoiceLogsChannel(newState.guild);
|
||||
if (!logChannel) return;
|
||||
|
||||
await sendLeftMessage(logChannel, newState.member!, oldState.channel!);
|
||||
}
|
||||
}
|
||||
|
||||
async function sendJoinMessage(channel: GuildTextBasedChannel, member: GuildMember, voiceChannel: VoiceBasedChannel) {
|
||||
await channel.send(`${member} joined ${voiceChannel} at ${time()}`);
|
||||
}
|
||||
|
||||
async function sendLeftMessage(channel: GuildTextBasedChannel, member: GuildMember, voiceChannel: VoiceBasedChannel) {
|
||||
await channel.send(`${member} left ${voiceChannel} at ${time()}`);
|
||||
}
|
||||
|
||||
async function sendMovedMessage(channel: GuildTextBasedChannel, member: GuildMember, oldVoiceChannel: VoiceBasedChannel, newVoiceChannel: VoiceBasedChannel) {
|
||||
await channel.send(`${member} moved from ${oldVoiceChannel} to ${newVoiceChannel} at ${time()}`);
|
||||
}
|
||||
|
||||
async function getVoiceLogsChannel(guild: Guild): Promise<GuildTextBasedChannel | undefined> {
|
||||
const settings = await Database.getGuildSettings(guild.id);
|
||||
|
||||
if (!settings || !settings.event_logs_channel_id) return;
|
||||
|
||||
const channel = await guild.channels.fetch(settings.event_logs_channel_id);
|
||||
|
||||
if (!channel || !channel.isSendable()) return;
|
||||
|
||||
return channel as GuildTextBasedChannel;
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
export * from './handle-audit-log-create';
|
||||
export * from './handle-guild-create';
|
||||
export * from './handle-member-join';
|
||||
export * from './handle-message';
|
||||
export * from './handle-thread-create';
|
||||
export * from './handle-voice-state-update';
|
||||
Reference in New Issue
Block a user