-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
247 lines (216 loc) · 8.36 KB
/
index.js
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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
// libraries
const { Client, IntentsBitField, Collection, Events, Partials } = require('discord.js');
const { OpenAI } = require('openai');
const dotenv = require('dotenv');
const fs = require('fs');
// This enables access to api keys for both open AI and the Discord bot
dotenv.config();
// intents - these enable the bot to recieve specific events, as such are required to allow the bot to perform certain actions
const botIntents = new IntentsBitField();
botIntents.add(
IntentsBitField.Flags.Guilds,
IntentsBitField.Flags.GuildMessages,
IntentsBitField.Flags.GuildMessageTyping,
IntentsBitField.Flags.GuildEmojisAndStickers,
IntentsBitField.Flags.MessageContent,
IntentsBitField.Flags.GuildMembers,
IntentsBitField.Flags.DirectMessages,
IntentsBitField.Flags.DirectMessageReactions,
IntentsBitField.Flags.DirectMessageTyping,
);
// Initializes Discord bot with defined intents
const client = new Client({ intents: botIntents, partials: [Partials.Message, Partials.Channel, Partials.Reaction] });
// Initialize OpenAI with API key
const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
// POINT 8. COMMAND PROCESSING
// Define the command prefix
const commandPrefix = '!';
// Create a collection to store commands
client.commands = new Collection();
// Read command files from the commands folder
const commandFiles = fs.readdirSync('./commands').filter((file) => file.endsWith('.js'));
// Load each command file and add it to the client.commands collection
for (const file of commandFiles) {
try {
const command = require(`./commands/${file}`);
if (command.data && command.data.name) {
// If the command has data.name, set it in the collection
client.commands.set(command.data.name, command);
} else {
console.error(`Error loading command from file ${file}: Command data or name is missing.`);
}
} catch (error) {
console.error(`Error loading command file ${file}:`, error);
}
}
// Import the button command
const buttonCommand = require('./commands/button.js');
// Check if buttonCommand and buttonCommand.data exist and if data has the name property
if (buttonCommand && buttonCommand.data && buttonCommand.data.name) {
// Set the button command in the client.commands collection using its name
client.commands.set(buttonCommand.data.name, buttonCommand);
} else {
console.error('Error loading button command:', buttonCommand);
}
// Import the meme command
const memeCommand = require('./commands/meme.js');
// Check if memeCommand and memeCommand.data exist and if data has the name property
if (memeCommand && memeCommand.data && memeCommand.data.name) {
// Set the meme command in the client.commands collection using its name
client.commands.set(memeCommand.data.name, memeCommand);
} else {
console.error('Error loading meme command:', memeCommand);
}
// Function to handle bot login
function loginBot() {
return new Promise((resolve, reject) => {
// Log in to Discord using the token from .env
client.login(process.env.DISCORD_TOKEN)
.then(() => {
console.log('Bot is logged in!');
resolve();
})
.catch((error) => {
console.error('Error logging in:', error);
reject(error); // Reject the promise with the error if login fails
});
});
}
// Login to Discord and start the bot
loginBot();
// message history handling
let history = [];
async function logMessage(message) {
if (message.author.bot && message.author.id !== client.user.id) return;
if (message.author.id === client.user.id) {
return history.push({
role: 'system',
content: message.content,
});
} else {
console.log(message.content);
history.push({
role: 'user',
content: message.content,
});
console.log('message logged');
}
}
client.once(Events.ClientReady, async (client) => {
try {
const defaultServerChannel = await client.channels.fetch('1204751557166374975');
const historyJson = await defaultServerChannel.messages.fetch({ limit: 10 });
await historyJson.forEach((message) => logMessage(message));
history.push({ 'role': 'system', 'content': 'you are a helpful assistant.' });
history = history.reverse();
console.log(history);
console.log(`${client.user.tag} history ready`);
} catch (error) {
console.error('History initialisation error', error);
}
});
// Function to handle command execution
async function handleCommand(message, commandName, args) {
if (client.commands.has(commandName)) {
const command = client.commands.get(commandName);
try {
await command.execute(message, args);
} catch (error) {
console.error('Error executing command:', error);
await message.channel.send('An error occurred while executing this command.');
}
} else {
await message.channel.send('Sorry, that command does not exist!');
}
}
// Function to handle regular message processing with OpenAI
async function handleRegularMessage(message) {
try {
const response = await openai.chat.completions.create({
model: 'gpt-3.5-turbo',
messages: history,
});
console.log(history);
await message.channel.send(response.choices[0].message.content);
} catch (error) {
console.error('There was an error while processing the OpenAI response:', error);
await message.channel.send('There was an error in processing your message.');
}
}
// Function to handle multimedia responses
const handleMultimedia = async (message) => {
try {
if (message.content.includes('cat')) {
await message.channel.send({
files: ['./multimedia-files/cat.jpg'],
});
} else if (message.content.includes('gif')) {
await message.channel.send('https://giphy.com/gifs/justin-mood-monday-mondays-1hqYk0leUMddBBkAM7');
} else if (message.content.includes('audio')) {
await message.channel.send({
files: ['./multimedia-files/magicFluteMozart.mp3'],
});
} else {
return false;
}
return true;
} catch (error) {
console.error('Error handling multimedia:', error);
await message.channel.send('An error occurred while processing multimedia content.');
}
};
// Event listener for incoming messages
client.on('messageCreate', async (message) => {
try {
// Ignore messages from bots
if (message.author.bot) return;
console.log('Message received:', message.content);
// Check if the message is a command
if (message.content.startsWith(commandPrefix)) {
const [commandName, ...args] = message.content.slice(commandPrefix.length).trim().split(/ +/);
// Handle !dm command separately
if (commandName === 'dm') {
// Handle direct message command
const username = args[0]; // Get the username from the command arguments
// Find the user by their username
const user = client.users.cache.find((user) => user.username === username);
if (user) {
await user.send('Hello! This is a direct message from me, Jelena the bot. How can I help you?');
await message.channel.send('Direct message sent!');
} else {
await message.channel.send('User not found.');
}
} else {
// Handle other commands
await handleCommand(message, commandName, args);
}
} else {
// For non-command messages
await logMessage(message);
await handleMultimedia(message);
await handleRegularMessage(message);
}
} catch (error) {
console.error('Error processing message:', error);
await message.channel.send('An error occurred while processing your message.');
}
});
// Event listener for button interactions
client.on('interactionCreate', async (interaction) => {
try {
if (!interaction.isButton()) return;
if (interaction.customId === 'deleting') {
await interaction.reply('You clicked the delete button!');
} else if (interaction.customId === 'middlebutton') {
await interaction.reply('You clicked the middle button!');
} else if (interaction.customId === 'success') {
await interaction.reply('You clicked the success button!');
} else if (interaction.customId === 'discordjs') {
// This customId should match the one set for the link button
await interaction.reply('You clicked the discord.js link button!');
}
} catch (error) {
console.error('Error handling button interaction:', error);
await interaction.reply('An error occurred while handling the button interaction.');
}
});