-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
148 lines (126 loc) · 4.07 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
require("dotenv").config();
const { Client, GatewayIntentBits, Collection } = require("discord.js");
const fs = require("fs");
const { REST } = require("@discordjs/rest");
const { Routes } = require("discord-api-types/v9");
const axios = require("axios");
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.GuildMembers,
GatewayIntentBits.DirectMessages,
GatewayIntentBits.MessageContent,
GatewayIntentBits.GuildVoiceStates,
],
});
// slash commands
client.commands = new Collection();
const commands = [];
const commandFiles = fs
.readdirSync("./commands")
.filter((file) => file.endsWith(".js"));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
client.commands.set(command.data.name, command);
commands.push(command.data.toJSON());
}
const rest = new REST({ version: "9" }).setToken(process.env.DISCORD_TOKEN);
client.once("ready", async () => {
console.log(`Logged in as ${client.user.tag}!`);
console.log("Team MPZ-Bot is ready!");
try {
console.log("Started refreshing application (/) commands.");
await rest.put(Routes.applicationCommands(client.user.id), {
body: commands,
});
console.log("Successfully reloaded application (/) commands.");
} catch (error) {
console.error(error);
}
});
client.on("interactionCreate", async (interaction) => {
if (!interaction.isCommand()) return;
const command = client.commands.get(interaction.commandName);
if (!command) return;
try {
await command.execute(interaction);
} catch (error) {
console.error(error);
await interaction.reply({
content: "There was an error while executing this command!",
ephemeral: true,
});
}
});
client.on("messageCreate", async (message) => {
// ignore messages from bots
if (message.author.bot) return;
// check if the message is DM or mentions the bot in a server
if (message.channel.type === "DM" || message.mentions.has(client.user.id)) {
let content = message.content;
// if the message is in server and mentions the bot, remove the mention from the message
if (message.channel.type !== "DM") {
content = content
.replace(new RegExp(`<@!?${client.user.id}>`, "g"), "")
.trim();
}
// generate and send a response using OpenAI API
try {
const reply = await generateOpenAIResponse(content);
await message.channel.send(reply);
} catch (error) {
console.error(
"Error in sending DM or processing OpenAI response:",
error
);
// inform the user that an error occurred (optional)
if (message.channel.type === "DM") {
await message.author.send(
"I encountered an error while processing your request."
);
}
}
}
});
// function to generate responses using OpenAI
async function generateOpenAIResponse(userMessage) {
const conversationHistory = [
{ role: "system", content: "You are a helpful assistant." },
{ role: "user", content: userMessage },
];
try {
const response = await axios.post(
"https://api.openai.com/v1/chat/completions",
{
model: "gpt-3.5-turbo",
messages: conversationHistory,
},
{
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${process.env.OPENAI_API_KEY}`,
},
}
);
console.log("OpenAI API Response:", response.data);
if (
response.data &&
response.data.choices &&
response.data.choices[0] &&
response.data.choices[0].message &&
response.data.choices[0].message.content
) {
const generatedReply = response.data.choices[0].message.content;
console.log("Generated Reply:", generatedReply);
return generatedReply;
} else {
console.error("Invalid response from OpenAI API");
return "Failed to generate a response.";
}
} catch (error) {
console.error("Error generating response:", error.message);
return "Failed to generate a response.";
}
}
client.login(process.env.DISCORD_TOKEN);