Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: list 명령어 구현 (현 서버의 모든 유저 보여주기) #39

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions src/commands/list.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import {logger} from "../logger.js";
import {MongoUtil} from "../util/mongoUtil.js";
import {ChatInputCommandInteraction, SlashCommandBuilder} from "discord.js";
import {TimeUtil} from "../util/timeUtil.js";

function formatDailyTime(dailyTime: string) {
if (dailyTime) {
return TimeUtil.formatDailyTime(dailyTime)
}
return "미등록"
}

export default {
data: new SlashCommandBuilder()
.setName('list')
.setDescription('등록된 모든 백준 아이디 목록을 보여드립니다.'),
async execute(interaction: ChatInputCommandInteraction) {
try {
const guildId = interaction.guildId
if (!guildId) {
await interaction.reply("서버 정보를 가져올 수 없습니다. 명령을 취소합니다.")
return;
}

const users = await MongoUtil.findAllUserInGuild(guildId);
if (!users || users.length === 0) {
await interaction.reply(`등록된 유저가 없습니다. \n/quit을 통해 아이디를 등록해주세요.`)
return;
}

const userInfo = users.map(user => {
return `백준 아이디: ${user.boj_id} | 매일 알림 시간: ${formatDailyTime(user.daily_time)}`;
}).join('\n')

Comment on lines +31 to +34
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

큰 문제가 될 것 같지는 않습니다만, 혹시라도 자신의 백준 정보 공개를 원치 않는 사람들이 있을까봐 조금은 걱정이 되네요. (티어 공개 원하지 않거나, private하게 사용하고 싶은 사람들 등...)

만약 이 기능을 추가한다면 등록할 시 프로필 공개 여부를 넣어야 할 것 같습니다.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

네, 저도 이 기능을 추가하고 뒤늦게 생각한건데... 사실 DB 구조를 많이 바꿔야 될 것 같습니다. 이 PR 은 일단 클로즈하고, 디자인을 조금 다시 잡으면 좋을 것 같다는 생각을 했습니다 😄

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

맞아요 사실 정말 주먹구구식으로 만들다보니 놓친 점이 한 두가지가 아니었어요😅 현재 백준봇 v2를 만들고 있는데 올려주신 pr 참고해서 반영하도록 하겠습니다 감사합니다!

await interaction.reply(userInfo)
return;
} catch (error: any) {
await interaction.reply("알 수 없는 오류가 발생했습니다.")
logger.error(error.message)
}
}
}
8 changes: 7 additions & 1 deletion src/commands/register.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,14 @@ export default {
return;
}

const guildId = interaction.guildId
if(!guildId){
await interaction.reply("서버 정보를 가져올 수 없습니다. 명령을 취소합니다.")
return;
}

await interaction.reply({embeds: [getUserInfo(realUser)]})
const response = await MongoUtil.addUser(interaction.user.id, boj_id!);
const response = await MongoUtil.addUser(interaction.user.id, boj_id!, guildId);
if (response) {
await interaction.followUp("정상적으로 등록되었습니다.")
logger.info(`${interaction.user.id} / ${boj_id} 가입 완료`)
Expand Down
1 change: 1 addition & 0 deletions src/embedMessage/guideMessage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ export const embedWelcome = new EmbedBuilder()
{ name: '/categorylist', value: '/category 사용 전, 알고리즘 분류 목록표를 보여드립니다.', inline: false },
{ name: '/quit', value: '백준 ID를 제거합니다. 봇을 제거할 시 정보 또한 동일하게 제거됩니다.', inline: false },
{ name: '/deactivate', value: '일일 문제 알림 수신을 비활성화 합니다.', inline: false },
{ name: '/list', value: '등록된 모든 백준 아이디 목록을 보여드립니다.', inline: false },
{ name: '\u200B', value: '\u200B' },
{ name: '업데이트 로그는 다음 링크에서 확인해주세요.', value: 'https://github.com/boaz-baekjoon/baekjoon-discord-bot/releases', inline: false },
)
Expand Down
4 changes: 3 additions & 1 deletion src/model/mongodb_user_schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,14 @@ interface IUser extends mongoose.Document {
discord_id: string;
boj_id: string;
daily_time: string;
guild_id: string;
}

const UserSchema = new mongoose.Schema({
discord_id: {type: String, required: true},
boj_id: {type: String, required: true},
daily_time: {type: String, required: false}
daily_time: {type: String, required: false},
guild_id: {type: String, required: false} // not required for backward compatibility
});

export const Mongodb_user_schema = mongoose.model<IUser>('Mongodb_use_schema', UserSchema, 'boj_user');
24 changes: 19 additions & 5 deletions src/util/mongoUtil.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,21 @@
import * as mongoose from 'mongoose';
import { Mongodb_user_schema } from '../model/mongodb_user_schema.js';
import {Mongodb_user_schema} from '../model/mongodb_user_schema.js';
import {logger} from "../logger.js";
import {Problem} from "../model/problem_schema.js";
import {BojProblem} from "../model/problem_class.js";
import {ClientSession} from "typeorm";
import {Report} from "../model/report_schema.js";

export class MongoUtil{
//map discordId and bojId, and save it to mongoDB
static async addUser(userDiscordId: string, userBojId: string): Promise<boolean>{
static async addUser(userDiscordId: string, userBojId: string, guildId: string): Promise<boolean>{
try{
const user = new Mongodb_user_schema({
discord_id: userDiscordId,
boj_id: userBojId,
daily_time: null,
guild_id: guildId,
});
await user.save();
logger.info(`Adding user ${userDiscordId} with boj id ${userBojId}`);
logger.info(`Adding user ${userDiscordId} with boj id ${userBojId} in guild ${guildId}`);
return true;
}catch (error: any){
logger.error(error.message);
Expand Down Expand Up @@ -127,6 +127,20 @@ export class MongoUtil{
}
}

static async findAllUserInGuild(guildId: string): Promise<any>{
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Discord에서 Guild의 경우는 일종의 워크스페이스 전체를 지칭하는 단위라, 같은 그룹 내 타 채널에서 봇을 사용하는 유저 정보까지 모조리 불러올 것 같아요.

이 부분은 어떻게 생각하시나요?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

제가 discord sdk 에 대한 이해가 조금 부족했던 것 같네요. 수정해야 될 부분으로 보입니다. (See #39 (comment) please)

try{
const users = await Mongodb_user_schema.find({guild_id: guildId});
logger.info(`Finding all users in guild ${guildId}`);
if (users){
return users;
}else {
return null;
}
}catch (error: any){
logger.error(error.message);
}
}

//find problem with problemId
static async findProblemWithProblemId(problemId: number): Promise<any>{
try {
Expand Down
12 changes: 12 additions & 0 deletions src/util/timeUtil.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
export class TimeUtil {
static formatDailyTime(dailyTime: string): string {
let [hh, mm] = dailyTime.split(' ')
if (hh.length === 1) {
hh = `0${hh}`
}
if (mm.length === 1) {
mm = `0${mm}`
}
return `${hh}:${mm}`
}
}