Skip to content

Commit ed1f660

Browse files
add filter for discord server
1 parent 98d1360 commit ed1f660

File tree

4 files changed

+73
-128
lines changed

4 files changed

+73
-128
lines changed

server/api/karma/give.post.ts

Lines changed: 0 additions & 43 deletions
This file was deleted.

server/core/discord/bot.ts

Lines changed: 32 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
1-
import { Client, GatewayIntentBits, Events, ChatInputCommandInteraction } from 'discord.js'
1+
import { Client, GatewayIntentBits, Events, ChatInputCommandInteraction, MessageFlags } from 'discord.js'
22
import { useNitroApp, useRuntimeConfig } from '#imports'
33
import { KarmaService } from './karma'
44

55
export function createDiscordBot() {
66
const logger = useNitroApp().logger
7+
const runtimeConfig = useRuntimeConfig()
8+
const allowedGuildId = runtimeConfig.public.discordGuildId
79

810
const client = new Client({
911
intents: [
@@ -13,11 +15,21 @@ export function createDiscordBot() {
1315

1416
client.once(Events.ClientReady, (readyClient) => {
1517
logger.info(`Discord bot ready! Logged in as ${readyClient.user.tag}`)
18+
logger.info(`Bot will only respond to commands from guild: ${allowedGuildId}`)
1619
})
1720

1821
client.on(Events.InteractionCreate, async (interaction) => {
1922
if (!interaction.isChatInputCommand()) return
2023

24+
if (interaction.guildId !== allowedGuildId) {
25+
logger.warn(`Ignored command from unauthorized guild: ${interaction.guildId}`)
26+
await interaction.reply({
27+
content: '❌ This bot is not configured for this server.',
28+
flags: MessageFlags.Ephemeral
29+
}).catch(() => { })
30+
return
31+
}
32+
2133
if (interaction.commandName === 'karma') {
2234
await handleKarmaCommand(interaction)
2335
}
@@ -30,47 +42,40 @@ async function handleKarmaCommand(interaction: ChatInputCommandInteraction) {
3042
const logger = useNitroApp().logger
3143

3244
try {
33-
// Get the user who invoked the command
45+
await interaction.deferReply()
46+
3447
const giver = interaction.user
3548

36-
// Get all mentioned users from the command
37-
const users = interaction.options.resolved?.users
49+
const receiverUser = interaction.options.getUser('user', true)
3850

39-
if (!users || users.size === 0) {
40-
await interaction.reply({
41-
content: '❌ Please mention at least one user to give karma!',
42-
ephemeral: true
51+
const reason = interaction.options.getString('reason', false) || undefined
52+
53+
logger.info('Karma command received:', { giver: giver.id, receiver: receiverUser.id, reason: reason || 'No reason provided' })
54+
55+
if (!receiverUser) {
56+
await interaction.editReply({
57+
content: '❌ Please mention a user to give karma!'
4358
})
4459
return
4560
}
4661

47-
// Extract user IDs
48-
const receiverIds = Array.from(users.values()).map(user => user.id)
49-
50-
// Defer reply for longer processing
51-
await interaction.deferReply()
52-
53-
// Call karma service directly
5462
const karmaService = new KarmaService()
55-
const result = await karmaService.giveKarma(giver.id, receiverIds)
63+
const result = await karmaService.giveKarma(giver.id, receiverUser.id, reason)
5664

57-
// Format success message
58-
const userMentions = Array.from(users.values())
59-
.map(user => `<@${user.id}>`)
60-
.join(', ')
65+
let message = `✅ Karma given to <@${receiverUser.id}>!\n\n<@${receiverUser.id}>: **${result.total_karma}** karma`
6166

62-
const karmaDetails = result.karma_counts
63-
.map(kc => `<@${kc.receiver_discord_id}>: **${kc.total_karma}** karma`)
64-
.join('\n')
67+
if (reason) {
68+
message += `\n\n💬 Reason: ${reason}`
69+
}
6570

6671
await interaction.editReply({
67-
content: `✅ Karma given to ${userMentions}!\n\n${karmaDetails}`
72+
content: message
6873
})
6974

70-
logger.info(`Karma given by ${giver.id} to ${receiverIds.join(', ')}`)
75+
logger.info(`Karma given by ${giver.id} to ${receiverUser.id}${reason ? ` with reason: ${reason}` : ''}`)
7176

7277
} catch (error) {
73-
logger.error('Error handling karma command:', error)
78+
logger.info('Error handling karma:', error)
7479

7580
const errorMessage = error instanceof Error ? error.message : 'An error occurred while processing your request.'
7681
const userFriendlyMessage = `❌ ${errorMessage}`
@@ -82,7 +87,7 @@ async function handleKarmaCommand(interaction: ChatInputCommandInteraction) {
8287
} else {
8388
await interaction.reply({
8489
content: userFriendlyMessage,
85-
ephemeral: true
90+
flags: MessageFlags.Ephemeral
8691
})
8792
}
8893
}

server/core/discord/karma.ts

Lines changed: 35 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,8 @@ export type KarmaCount = {
88

99
export type GiveKarmaResult = {
1010
success: boolean
11-
karma_counts: KarmaCount[]
11+
receiver_discord_id: string
12+
total_karma: number
1213
timestamp: string
1314
}
1415

@@ -22,68 +23,68 @@ export class KarmaService {
2223
}
2324

2425
/**
25-
* Give karma from one user to multiple receivers
26+
* Give karma from one user to a receiver
2627
* @param giverDiscordId - Discord ID of the user giving karma
27-
* @param receiverDiscordIds - Array of Discord IDs receiving karma
28-
* @returns Result containing karma counts for each receiver
28+
* @param receiverDiscordId - Discord ID of the user receiving karma
29+
* @param reason - Optional reason for giving karma
30+
* @returns Result containing karma count for the receiver
2931
* @throws Error if validation fails or database operation fails
3032
*/
3133
async giveKarma(
3234
giverDiscordId: string,
33-
receiverDiscordIds: string[]
35+
receiverDiscordId: string,
36+
reason?: string
3437
): Promise<GiveKarmaResult> {
35-
// Validate inputs
3638
if (!giverDiscordId) {
3739
throw new Error('giver_discord_id is required')
3840
}
3941

40-
if (!receiverDiscordIds || !Array.isArray(receiverDiscordIds) || receiverDiscordIds.length === 0) {
41-
throw new Error('receiver_discord_ids must be a non-empty array')
42+
if (!receiverDiscordId) {
43+
throw new Error('receiver_discord_id is required')
4244
}
4345

44-
if (receiverDiscordIds.includes(giverDiscordId)) {
46+
if (receiverDiscordId === giverDiscordId) {
4547
throw new Error('Хтось пробує сам собі дати карму!')
4648
}
4749

4850
try {
4951
const timestamp = new Date()
50-
const karmaCounts: KarmaCount[] = []
5152

52-
this.logger.info('Giving karma to receivers:', { giverDiscordId: giverDiscordId, receiverDiscordIds: receiverDiscordIds })
53+
this.logger.info('Giving karma to receiver:', {
54+
giverDiscordId,
55+
receiverDiscordId,
56+
reason: reason || 'No reason provided'
57+
})
5358

54-
// Check if receivers exist in discord_members collection
55-
const existingMembers = await this.db.collection('discord_members').find({
56-
discordId: { $in: receiverDiscordIds }
57-
}).project({ discordId: 1 }).toArray()
59+
const existingMember = await this.db.collection('discord_members').findOne({
60+
discordId: receiverDiscordId
61+
})
5862

59-
const existingIds = new Set(existingMembers.map((m: any) => m.discordId))
60-
const filteredDiscordIds = receiverDiscordIds.filter(id => existingIds.has(id))
63+
if (!existingMember) {
64+
throw new Error('Receiver not found in discord_members')
65+
}
6166

62-
if (filteredDiscordIds.length === 0) {
63-
throw new Error('No valid receiver_discord_ids found in discord_members')
67+
const karmaEvent: any = {
68+
giver_discord_id: giverDiscordId,
69+
receiver_discord_id: receiverDiscordId,
70+
amount: 1,
71+
timestamp: timestamp
6472
}
6573

66-
for (const receiverId of filteredDiscordIds) {
67-
await this.db.collection('karma_events').insertOne({
68-
giver_discord_id: giverDiscordId,
69-
receiver_discord_id: receiverId,
70-
amount: 1,
71-
timestamp: timestamp
72-
})
74+
if (reason) {
75+
karmaEvent.reason = reason
76+
}
7377

74-
const totalKarma = await this.getTotalKarma(receiverId)
78+
await this.db.collection('karma_events').insertOne(karmaEvent)
7579

76-
karmaCounts.push({
77-
receiver_discord_id: receiverId,
78-
total_karma: totalKarma
79-
})
80+
const totalKarma = await this.getTotalKarma(receiverDiscordId)
8081

81-
this.logger.info(`Karma given: ${giverDiscordId} -> ${receiverId}, new total: ${totalKarma}`)
82-
}
82+
this.logger.info(`Karma given: ${giverDiscordId} -> ${receiverDiscordId}, new total: ${totalKarma}${reason ? `, reason: ${reason}` : ''}`)
8383

8484
return {
8585
success: true,
86-
karma_counts: karmaCounts,
86+
receiver_discord_id: receiverDiscordId,
87+
total_karma: totalKarma,
8788
timestamp: timestamp.toISOString()
8889
}
8990
} catch (error) {

server/core/discord/register-commands.ts

Lines changed: 6 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -17,36 +17,18 @@ export async function registerDiscordCommands() {
1717
const commands = [
1818
{
1919
name: 'karma',
20-
description: 'Give karma to users',
20+
description: 'Give karma to a user',
2121
options: [
2222
{
23-
name: 'user1',
24-
description: 'First user to give karma',
23+
name: 'user',
24+
description: 'User to give karma',
2525
type: ApplicationCommandOptionType.User,
2626
required: true,
2727
},
2828
{
29-
name: 'user2',
30-
description: 'Second user to give karma',
31-
type: ApplicationCommandOptionType.User,
32-
required: false,
33-
},
34-
{
35-
name: 'user3',
36-
description: 'Third user to give karma',
37-
type: ApplicationCommandOptionType.User,
38-
required: false,
39-
},
40-
{
41-
name: 'user4',
42-
description: 'Fourth user to give karma',
43-
type: ApplicationCommandOptionType.User,
44-
required: false,
45-
},
46-
{
47-
name: 'user5',
48-
description: 'Fifth user to give karma',
49-
type: ApplicationCommandOptionType.User,
29+
name: 'reason',
30+
description: 'Reason for giving karma',
31+
type: ApplicationCommandOptionType.String,
5032
required: false,
5133
},
5234
],

0 commit comments

Comments
 (0)