-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
218 lines (189 loc) · 8.05 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
import 'dotenv/config'
import { Events, REST, Routes } from 'discord.js';
import { executeTest, sendQuestion } from './commands/test-command';
import { sendSurveyQuestions, Feedbackquestions } from './functions/startSurvey';
import { google } from 'googleapis';
import { client, db } from './common';
import { executeMatch } from "./commands/match-command";
import { trackInvites } from "./inviteTracker";
import { decrypt, encrypt } from "./encryptionUtils";
client.login(process.env.TOKEN); // Log in to the bot
client.on(Events.ClientReady, async c => {
console.log(`Ready! Logged in as ${c.user.tag}`);
await db.connect();
//sendTestButton()
//add later
//client.user.setActivity("123", {ActivityType.Listening})
const rest = new REST().setToken(process.env.TOKEN!);
try {
console.log('Started refreshing application (/) commands.');
await rest.put(Routes.applicationCommands(c.user.id), {
body:
[
{
name: 'match',
description: 'Requests new match without retaking the test.'
},
{
name: 'test',
description: 'Asks the test questions!'
},
]
});
console.log('Successfully reloaded application (/) commands.');
} catch (error) {
console.error(error);
}
});
client.on('guildMemberAdd', async () => {
await trackInvites();
});
// Catch command errors
client.on(Events.InteractionCreate, async interaction => {
// Handle Slash commands
if (interaction.isChatInputCommand()) {
try {
if (interaction.commandName === 'test')
await executeTest(interaction);
else if (interaction.commandName === 'match')
await executeMatch(interaction);
} catch (error) {
console.error(error);
if (interaction.replied || interaction.deferred) {
await interaction.followUp({
content: 'There was an error while executing this command!',
ephemeral: true,
});
} else {
await interaction.reply({
content: 'There was an error while executing this command!',
ephemeral: true,
});
}
}
return;
}
// check if the interaction is a button interaction
if (interaction.isButton()) {
const buttonId = interaction.customId;
if (buttonId === 'start_survey') {
await interaction.deferUpdate();
await sendSurveyQuestions(interaction);
// Update context for this user in the database to indicate feedback process has started
await db.db('contrabot').collection("users").updateOne(
{ userId: interaction.user.id },
{
$set: {
feedbackInProgress: true,
currentFeedbackQuestionIndex: 0
}
},
{ upsert: true }
);
} else if (buttonId === 'start_test') {
await interaction.deferUpdate();
await sendQuestion(interaction);
} else {
// Fetch user's context from the database
const userContext = await db.db('contrabot').collection("users").findOne({ userId: interaction.user.id });
const userResponses = userContext?.userVector ? JSON.parse(decrypt(userContext.userVector)) : [];
// Update the userResponses based on button clicked
if (buttonId === 'agree') userResponses.push(1);
else if (buttonId === 'disagree') userResponses.push(-1);
else if (buttonId === 'neutral') userResponses.push(0);
// Update the userResponses for this user in the database
const encryptedUserVector = encrypt(JSON.stringify(userResponses));
await db.db('contrabot').collection("users").updateOne(
{ userId: interaction.user.id },
{
$set: {
userVector: encryptedUserVector
}
}
);
await interaction.deferUpdate();
await sendQuestion(interaction);
}
}
});
// API configuration for Google Sheets
const SHEET_ID = '1pKsioVutiEPkNwTUrW1v_Y8bFe5eQobCGpK9KVpsOo8';
const START_COLUMN = 'A';
const END_COLUMN = 'P';
const COLUMNS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split(''); // to allow easy access to column names
const jwtClient = new google.auth.JWT(
process.env.CLIENT_EMAIL,
undefined,
process.env.PRIVATE_KEY,
[ 'https://www.googleapis.com/auth/spreadsheets' ]
);
const sheets = google.sheets({ version: 'v4', auth: jwtClient });
// Catch feedback messages
client.on(Events.MessageCreate, async (message) => {
if (message.author.bot) return;
try {
const userContext = await db.db('contrabot').collection("users").findOne({ userId: message.author.id });
if (userContext?.feedbackInProgress) {
let currentFeedbackQuestionIndex = userContext?.currentFeedbackQuestionIndex || 0;
// Calculate the column where the answer should be placed.
const columnForAnswer = COLUMNS[ currentFeedbackQuestionIndex + 1 ]; // +1 to skip the first column which might have the userID
// Find the row number for the current user (assuming the user's ID is in the first column)
const response = await sheets.spreadsheets.values.get({
spreadsheetId: SHEET_ID,
range: `${START_COLUMN}:${START_COLUMN}` // search in the first column only
});
const rows = response.data.values || [];
let rowIndex = rows.findIndex((row: any) => row[ 0 ] === message.author.id.toString()) + 1; // +1 because index is 0-based and rows in Google Sheets are 1-based.
// If the user is not found, create a new row for them
if (rowIndex === 0) {
await sheets.spreadsheets.values.append({
spreadsheetId: SHEET_ID,
range: `${START_COLUMN}:${END_COLUMN}`,
valueInputOption: 'RAW',
insertDataOption: 'INSERT_ROWS',
resource: {
values: [
[ message.author.id ] // userID in the first column
]
}
} as any);
rowIndex = rows.length + 1; // New row index
}
// Update the particular cell with the answer
await sheets.spreadsheets.values.update({
spreadsheetId: SHEET_ID,
range: `${columnForAnswer}${rowIndex}`,
valueInputOption: 'RAW',
resource: {
values: [
[ message.content ]
]
}
} as any);
currentFeedbackQuestionIndex++;
if (currentFeedbackQuestionIndex < Feedbackquestions.length) {
message.author.send(Feedbackquestions[ currentFeedbackQuestionIndex ]);
await db.db('contrabot').collection("users").updateOne(
{ userId: message.author.id },
{
$set: {
currentFeedbackQuestionIndex: currentFeedbackQuestionIndex
}
}
);
} else {
await db.db('contrabot').collection("users").updateOne(
{ userId: message.author.id },
{
$set: {
feedbackInProgress: false
}
}
);
message.author.send("Danke für dein Feedback und dein Beitrag zur Verbesserung des Bots!");
}
}
} catch (error) {
console.error("Error in Events.MessageCreate:", error);
}
});