functions.ts 쪼개기

This commit is contained in:
kdh8219 2023-06-10 20:25:49 +09:00
parent b0b9476956
commit 36b5e30ce4
Signed by: kdh8219
GPG key ID: 9B901BE907D1862E
15 changed files with 212 additions and 231 deletions

View file

@ -1,7 +1,7 @@
import { SlashCommandBuilder, ChatInputCommandInteraction } from "discord.js"; import { SlashCommandBuilder, ChatInputCommandInteraction } from "discord.js";
import mojangAPI from "../../wrapper/mojang-api.js"; import mojangAPI from "../../wrapper/mojang-api.js";
import firebase from "../../wrapper/firebase.js"; import firebase from "../../wrapper/firebase.js";
import { add_user } from "../../functions.js"; import { add_user } from "../../functions/add_user.js";
export default { export default {
data: new SlashCommandBuilder() data: new SlashCommandBuilder()

View file

@ -6,7 +6,7 @@ import {
import mojangAPI from "../../wrapper/mojang-api.js"; import mojangAPI from "../../wrapper/mojang-api.js";
import firebase from "../../wrapper/firebase.js"; import firebase from "../../wrapper/firebase.js";
import { add_user } from "../../functions.js"; import { add_user } from "../../functions/add_user.js";
export default { export default {
data: new SlashCommandBuilder() data: new SlashCommandBuilder()

View file

@ -7,7 +7,7 @@ import {
import mojangAPI from "../../wrapper/mojang-api.js"; import mojangAPI from "../../wrapper/mojang-api.js";
import firebase from "../../wrapper/firebase.js"; import firebase from "../../wrapper/firebase.js";
import { embed_to_channel } from "../../functions.js"; import { send_embed } from "../../functions/send_embed.js";
export default { export default {
data: new SlashCommandBuilder() data: new SlashCommandBuilder()
@ -64,26 +64,23 @@ export default {
content: `삭제 완료:${discord_tag}(${discord_id})에게서 ${minecraft_id}(${minecraft_uuid})를 제거했습니다.`, content: `삭제 완료:${discord_tag}(${discord_id})에게서 ${minecraft_id}(${minecraft_uuid})를 제거했습니다.`,
}); });
const embed = new EmbedBuilder() await send_embed(interaction.client, process.env.LOG_CHANNEL_ID, [
.setTitle("Nick deleted") new EmbedBuilder()
.setColor(0x0099ff) .setTitle("Nick deleted")
.setFields([ .setColor(0x0099ff)
{ .setFields([
name: "Command sender", {
value: `${interaction.user.tag}(${interaction.user.id})`, name: "Command sender",
}, value: `${interaction.user.tag}(${interaction.user.id})`,
{ name: " ", value: " " }, },
{ name: "Targrt Discord Id", value: discord_id }, { name: " ", value: " " },
{ name: " ", value: " " }, { name: "Targrt Discord Id", value: discord_id },
{ name: "Minecraft Id", value: minecraft_id }, { name: " ", value: " " },
{ name: "Minecraft Uuid", value: minecraft_uuid }, { name: "Minecraft Id", value: minecraft_id },
]) { name: "Minecraft Uuid", value: minecraft_uuid },
.setTimestamp(interaction.createdAt); ])
await embed_to_channel( .setTimestamp(interaction.createdAt),
interaction.client, ]);
process.env.LOG_CHANNEL_ID,
embed
);
} else { } else {
await interaction.editReply({ await interaction.editReply({
content: `\`에러\`: 해당 계정이 없습니다.`, content: `\`에러\`: 해당 계정이 없습니다.`,

View file

@ -6,7 +6,7 @@ import {
} from "discord.js"; } from "discord.js";
import firebase from "../../wrapper/firebase.js"; import firebase from "../../wrapper/firebase.js";
import { embed_to_channel } from "../../functions.js"; import { send_embed } from "../../functions/send_embed.js";
export default { export default {
data: new SlashCommandBuilder() data: new SlashCommandBuilder()
@ -44,23 +44,21 @@ export default {
await interaction.editReply({ await interaction.editReply({
content: `삭제 완료:${discord_tag}의 계정을 모두 제거했습니다.`, content: `삭제 완료:${discord_tag}의 계정을 모두 제거했습니다.`,
}); });
const embed = new EmbedBuilder()
.setTitle("User deleted") await send_embed(interaction.client, process.env.LOG_CHANNEL_ID, [
.setColor(0x0099ff) new EmbedBuilder()
.setFields([ .setTitle("User deleted")
{ .setColor(0x0099ff)
name: "Command sender", .setFields([
value: `${interaction.user.tag}(${interaction.user.id})`, {
}, name: "Command sender",
{ name: " ", value: " " }, value: `${interaction.user.tag}(${interaction.user.id})`,
{ name: "Target Discord Id", value: discord_id }, },
]) { name: " ", value: " " },
.setTimestamp(interaction.createdAt); { name: "Target Discord Id", value: discord_id },
await embed_to_channel( ])
interaction.client, .setTimestamp(interaction.createdAt),
process.env.LOG_CHANNEL_ID, ]);
embed
);
return; return;
} else { } else {
await interaction.editReply({ await interaction.editReply({

View file

@ -1,7 +1,7 @@
import { ChatInputCommandInteraction, SlashCommandBuilder } from "discord.js"; import { ChatInputCommandInteraction, SlashCommandBuilder } from "discord.js";
import firebase from "../../wrapper/firebase.js"; import firebase from "../../wrapper/firebase.js";
import { TUser } from "../../functions.js"; import { TUser } from "../../types.js";
import mojangAPI from "../../wrapper/mojang-api.js"; import mojangAPI from "../../wrapper/mojang-api.js";
export default { export default {

View file

@ -1,7 +1,7 @@
import { SlashCommandBuilder, ChatInputCommandInteraction } from "discord.js"; import { SlashCommandBuilder, ChatInputCommandInteraction } from "discord.js";
import firebase from "../../wrapper/firebase.js"; import firebase from "../../wrapper/firebase.js";
import { TUser } from "../../functions.js"; import { TUser } from "../../types.js";
export default { export default {
data: new SlashCommandBuilder() data: new SlashCommandBuilder()

View file

@ -2,7 +2,8 @@ import { ChatInputCommandInteraction, SlashCommandBuilder } from "discord.js";
import firebase from "../../wrapper/firebase.js"; import firebase from "../../wrapper/firebase.js";
import mojangAPI from "../../wrapper/mojang-api.js"; import mojangAPI from "../../wrapper/mojang-api.js";
import { TUser } from "../../functions.js"; import { TUser } from "../../types.js";
import { dm_slice } from "../../functions/dm_slice.js";
export default { export default {
data: new SlashCommandBuilder() data: new SlashCommandBuilder()
@ -64,35 +65,10 @@ export default {
text = text.slice(0, -1); text = text.slice(0, -1);
text += "\n\n"; text += "\n\n";
} }
const sliced = dmSlice(text); const sliced = dm_slice(text);
for (const chunk of sliced) { for (const chunk of sliced) {
await interaction.user.send(chunk); await interaction.user.send(chunk);
} }
await interaction.editReply("dm을 확인해주세요."); await interaction.editReply("dm을 확인해주세요.");
}, },
}; };
function dmSlice(raw: string): string[] {
function slasher(txt: string): { front: string; end: string } {
let front = txt.slice(0, 2000);
let end = txt.slice(2000);
if (end) {
const IndexOfLastBlock = front.lastIndexOf("\n\n");
end = "" /* 공백문자 */ + front.slice(IndexOfLastBlock + 1) + end;
front = front.slice(0, IndexOfLastBlock);
}
return { front, end };
}
const output: string[] = [];
let slashed = slasher(raw);
while (true) {
output.push(slashed.front);
if (slashed.end) {
slashed = slasher(slashed.end);
} else {
return output;
}
}
}

View file

@ -5,7 +5,7 @@ import {
} from "discord.js"; } from "discord.js";
import firebase from "../../wrapper/firebase.js"; import firebase from "../../wrapper/firebase.js";
import { TUser } from "../../functions.js"; import { TUser } from "../../types.js";
export default { export default {
data: new SlashCommandBuilder() data: new SlashCommandBuilder()

View file

@ -6,7 +6,8 @@ import {
} from "discord.js"; } from "discord.js";
import firebase from "../../wrapper/firebase.js"; import firebase from "../../wrapper/firebase.js";
import { TUser, embed_to_channel } from "../../functions.js"; import { TUser } from "../../types.js";
import { send_embed } from "../../functions/send_embed.js";
export default { export default {
data: new SlashCommandBuilder() data: new SlashCommandBuilder()
@ -54,23 +55,21 @@ export default {
UUIDs += uuid; UUIDs += uuid;
UUIDs += "\n"; UUIDs += "\n";
}); });
const embed = new EmbedBuilder()
.setTitle("User blacklisted") await send_embed(interaction.client, process.env.LOG_CHANNEL_ID, [
.setColor(0x0099ff) new EmbedBuilder()
.setFields([ .setTitle("User blacklisted")
{ .setColor(0x0099ff)
name: "Command sender", .setFields([
value: `${interaction.user.tag}(${interaction.user.id})`, {
}, name: "Command sender",
{ name: " ", value: " " }, value: `${interaction.user.tag}(${interaction.user.id})`,
{ name: "Target Discord Id", value: discord_id }, },
{ name: "UUIDs", value: UUIDs }, { name: " ", value: " " },
]) { name: "Target Discord Id", value: discord_id },
.setTimestamp(interaction.createdAt); { name: "UUIDs", value: UUIDs },
await embed_to_channel( ])
interaction.client, .setTimestamp(interaction.createdAt),
process.env.LOG_CHANNEL_ID, ]);
embed
);
}, },
}; };

View file

@ -1,123 +0,0 @@
import {
ChatInputCommandInteraction,
Client,
EmbedBuilder,
Guild,
} from "discord.js";
import { Firestore } from "firebase-admin/firestore";
import { MojangAPI } from "./wrapper/mojang-api.js";
import firebase from "./wrapper/firebase.js";
export type TUser = {
discord_id: string; // id
minecraft_uuid: string; //uuid
};
export async function add_user(
interaction: ChatInputCommandInteraction,
discord_id: string,
mcid: string,
mojangAPI: MojangAPI,
firebase: Firestore
) {
let mcuuid: string;
try {
mcuuid = await mojangAPI.getUUIDFromId(mcid);
} catch {
await interaction.editReply({
content:
"`에러`: 마인크래프트 닉네임 검색을 실패했습니다. 마인크래프트 닉네임을 정확하게 입력했나요?",
});
return;
}
const members = firebase.collection("members");
const blacklist = firebase.collection("blacklist");
if (!(await blacklist.where("discord_id", "==", discord_id).get()).empty) {
await interaction.editReply({
content: "`에러`: 해당 디스코드 아이디는 블랙리스트 되었습니다.",
});
return;
}
if (!(await blacklist.where("minecraft_uuid", "==", mcuuid).get()).empty) {
await interaction.editReply({
content: "`에러`: 해당 마인크래프트 계정은 블랙리스트 되었습니다.",
});
return;
}
if (!(await members.where("minecraft_uuid", "==", mcuuid).get()).empty) {
await interaction.editReply({
content: "`에러`: 해당 마인크래프트 아이디는 이미 등록되었습니다.",
});
return;
}
if ((await members.where("discord_id", "==", discord_id).get()).empty) {
await interaction.editReply({
content: `${mcid}(${mcuuid})님 2k2r에 오신것을 환영합니다!`,
});
} else {
await interaction.editReply({
content: `${mcid}(${mcuuid})이 성공적으로 부계정으로 등록되었습니다!`,
});
}
await members.add({
discord_id,
minecraft_uuid: mcuuid,
});
const embed = new EmbedBuilder()
.setTitle("User Added")
.setColor(0x0099ff)
.addFields([
{
name: "Command sender",
value: `${interaction.user.tag}(${interaction.user.id})`,
},
{ name: " ", value: " " },
{ name: "Discord Id", value: discord_id },
{ name: " ", value: " " },
{ name: "Minecraft Id", value: mcid },
{ name: "Minecraft Uuid", value: mcuuid },
])
.setTimestamp(interaction.createdAt);
await embed_to_channel(interaction.client, process.env.LOG_CHANNEL_ID, embed);
}
export async function embed_to_channel(
client: Client<true>,
channel_id: string,
embed: EmbedBuilder
) {
const channel = await client.channels.fetch(channel_id);
if (!channel.isTextBased()) return;
channel.send({ embeds: [embed] });
}
export async function delete_members_who_left(
client: Client<true>,
guild: Guild
) {
const members_collection = firebase.collection("members");
const members = await members_collection.get();
for (const doc of members.docs) {
const data = doc.data() as TUser;
try {
await guild.members.fetch(data.discord_id);
} catch {
doc.ref.delete();
const embed = new EmbedBuilder()
.setTitle("물갈이")
.setColor(0x0099ff)
.setFields([
{ name: "Discord Id", value: data.discord_id },
{ name: "Minecraft Uuid", value: data.minecraft_uuid },
])
.setTimestamp(new Date());
await embed_to_channel(client, process.env.LOG_CHANNEL_ID, embed);
}
}
}

78
src/functions/add_user.ts Normal file
View file

@ -0,0 +1,78 @@
import { ChatInputCommandInteraction, EmbedBuilder } from "discord.js";
import { Firestore } from "firebase-admin/firestore";
import { MojangAPI } from "./../wrapper/mojang-api.js";
import { send_embed } from "./send_embed.js";
export async function add_user(
interaction: ChatInputCommandInteraction,
discord_id: string,
mcid: string,
mojangAPI: MojangAPI,
firebase: Firestore
) {
let mcuuid: string;
try {
mcuuid = await mojangAPI.getUUIDFromId(mcid);
} catch {
await interaction.editReply({
content:
"`에러`: 마인크래프트 닉네임 검색을 실패했습니다. 마인크래프트 닉네임을 정확하게 입력했나요?",
});
return;
}
const members = firebase.collection("members");
const blacklist = firebase.collection("blacklist");
if (!(await blacklist.where("discord_id", "==", discord_id).get()).empty) {
await interaction.editReply({
content: "`에러`: 해당 디스코드 아이디는 블랙리스트 되었습니다.",
});
return;
}
if (!(await blacklist.where("minecraft_uuid", "==", mcuuid).get()).empty) {
await interaction.editReply({
content: "`에러`: 해당 마인크래프트 계정은 블랙리스트 되었습니다.",
});
return;
}
if (!(await members.where("minecraft_uuid", "==", mcuuid).get()).empty) {
await interaction.editReply({
content: "`에러`: 해당 마인크래프트 아이디는 이미 등록되었습니다.",
});
return;
}
if ((await members.where("discord_id", "==", discord_id).get()).empty) {
await interaction.editReply({
content: `${mcid}(${mcuuid})님 2k2r에 오신것을 환영합니다!`,
});
} else {
await interaction.editReply({
content: `${mcid}(${mcuuid})이 성공적으로 부계정으로 등록되었습니다!`,
});
}
await members.add({
discord_id,
minecraft_uuid: mcuuid,
});
await send_embed(interaction.client, process.env.LOG_CHANNEL_ID, [
new EmbedBuilder()
.setTitle("User Added")
.setColor(0x0099ff)
.addFields([
{
name: "Command sender",
value: `${interaction.user.tag}(${interaction.user.id})`,
},
{ name: " ", value: " " },
{ name: "Discord Id", value: discord_id },
{ name: " ", value: " " },
{ name: "Minecraft Id", value: mcid },
{ name: "Minecraft Uuid", value: mcuuid },
])
.setTimestamp(interaction.createdAt),
]);
}

24
src/functions/dm_slice.ts Normal file
View file

@ -0,0 +1,24 @@
export function dm_slice(raw: string): string[] {
function slasher(txt: string): { front: string; end: string } {
let front = txt.slice(0, 2000);
let end = txt.slice(2000);
if (end) {
const IndexOfLastBlock = front.lastIndexOf("\n\n");
end = "" /* 공백문자 */ + front.slice(IndexOfLastBlock + 1) + end;
front = front.slice(0, IndexOfLastBlock);
}
return { front, end };
}
const output: string[] = [];
let slashed = slasher(raw);
while (true) {
output.push(slashed.front);
if (slashed.end) {
slashed = slasher(slashed.end);
} else {
return output;
}
}
}

View file

@ -0,0 +1,11 @@
import { Client, EmbedBuilder } from "discord.js";
export async function send_embed(
client: Client<true>,
channel_id: string,
embed: EmbedBuilder[]
) {
const channel = await client.channels.fetch(channel_id);
if (!channel.isTextBased()) return;
channel.send({ embeds: embed });
}

View file

@ -4,12 +4,9 @@ config();
import { getCommands } from "./command/commands.js"; import { getCommands } from "./command/commands.js";
import mojangAPI from "./wrapper/mojang-api.js"; import mojangAPI from "./wrapper/mojang-api.js";
import { import { TUser } from "./types.js";
TUser,
delete_members_who_left,
embed_to_channel,
} from "./functions.js";
import firebase from "./wrapper/firebase.js"; import firebase from "./wrapper/firebase.js";
import { send_embed } from "./functions/send_embed.js";
await mojangAPI.load_cache_from_firestore(); await mojangAPI.load_cache_from_firestore();
@ -22,10 +19,29 @@ client.once(Events.ClientReady, async (event) => {
console.log(`[DISCORD] Ready: discord client as ${event.user.tag}`); console.log(`[DISCORD] Ready: discord client as ${event.user.tag}`);
onTime = new Date(); onTime = new Date();
delete_members_who_left( const guild = await client.guilds.fetch(process.env.DISCORD_TARGET_GUILD_ID);
client, {
await client.guilds.fetch(process.env.DISCORD_TARGET_GUILD_ID) const members_collection = firebase.collection("members");
); const members = await members_collection.get();
for (const doc of members.docs) {
const data = doc.data() as TUser;
try {
await guild.members.fetch(data.discord_id);
} catch {
doc.ref.delete();
await send_embed(client, process.env.LOG_CHANNEL_ID, [
new EmbedBuilder()
.setTitle("Auto Removed")
.setColor(0x0099ff)
.setFields([
{ name: "Discord Id", value: data.discord_id },
{ name: "Minecraft Uuid", value: data.minecraft_uuid },
])
.setTimestamp(new Date()),
]);
}
}
}
}); });
client.on(Events.InteractionCreate, async (interaction) => { client.on(Events.InteractionCreate, async (interaction) => {
@ -63,15 +79,16 @@ client.on(Events.GuildMemberRemove, async (interaction) => {
for (const doc of exited_user.docs) { for (const doc of exited_user.docs) {
const data = doc.data() as TUser; const data = doc.data() as TUser;
doc.ref.delete(); doc.ref.delete();
const embed = new EmbedBuilder() await send_embed(client, process.env.LOG_CHANNEL_ID, [
.setTitle("물갈이") new EmbedBuilder()
.setColor(0x0099ff) .setTitle("Auto Removed")
.setFields([ .setColor(0x0099ff)
{ name: "Discord Id", value: data.discord_id }, .setFields([
{ name: "Minecraft Uuid", value: data.minecraft_uuid }, { name: "Discord Id", value: data.discord_id },
]) { name: "Minecraft Uuid", value: data.minecraft_uuid },
.setTimestamp(new Date()); ])
await embed_to_channel(client, process.env.LOG_CHANNEL_ID, embed); .setTimestamp(new Date()),
]);
} }
}); });

4
src/types.d.ts vendored Normal file
View file

@ -0,0 +1,4 @@
export type TUser = {
discord_id: string; // id
minecraft_uuid: string; //uuid
};