Skip to content

Commit 763174f

Browse files
committed
ChatGPT, flags, testing
1 parent 3a654d7 commit 763174f

18 files changed

Lines changed: 455 additions & 18 deletions

File tree

ChatGPT/gpt.js

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
require("dotenv").config();
2+
require("colors");
3+
const { Configuration, OpenAIApi } = require("openai");
4+
5+
module.exports = async (client) => {
6+
console.log("Initializing ChatGPT", process.env.ChatGPT)
7+
8+
const setupGPTconnection = new Promise((resolve, reject) => {
9+
const chatGPTconfig = new Configuration({
10+
apiKey: process.env.chatGPT
11+
});
12+
const openai = new OpenAIApi(chatGPTconfig);
13+
if (openai) resolve(openai)
14+
else reject("Could not initialize connection to openAI server")
15+
})
16+
17+
setupGPTconnection.then((openAI) => {
18+
client.openai = openAI;
19+
console.log("GPT Initialized".rainbow)
20+
}).catch((err) => {
21+
console.error(err);
22+
})
23+
//==================================================================
24+
// const completion = await openai.createCompletion({
25+
// model: "text-davinci-003",
26+
// prompt: message,
27+
// max_tokens: 200,
28+
// });
29+
// return completion.data.choices[0].text;
30+
}

Slash/commands/ping.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
const { SlashCommandBuilder } = require('discord.js');
2+
3+
module.exports = {
4+
data: new SlashCommandBuilder()
5+
.setName('ping')
6+
.setDescription('Replies with Pong!'),
7+
async execute(interaction) {
8+
await interaction.reply('Pong!');
9+
},
10+
};

Slash/commands/relative.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
const { SlashCommandBuilder } = require('discord.js');
2+
3+
module.exports = {
4+
data: new SlashCommandBuilder()
5+
.setName('relative')
6+
.setDescription('Provides an example of a dynamic timestamp.'),
7+
async execute(interaction) {
8+
await interaction.reply(`It has been <t:${parseInt((+ new Date())/1000)}:R> since this message has been received`);
9+
},
10+
};

Slash/commands/server.js

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
const { SlashCommandBuilder } = require('discord.js');
2+
3+
module.exports = {
4+
data: new SlashCommandBuilder()
5+
.setName('server')
6+
.setDescription('Provides information about the server.'),
7+
async execute(interaction) {
8+
// interaction.guild is the object representing the Guild in which the command was run
9+
await interaction.reply(`This server is ${interaction.guild.name} and has ${interaction.guild.memberCount} members.`);
10+
},
11+
};

Slash/commands/user.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
const { SlashCommandBuilder } = require('discord.js');
2+
3+
module.exports = {
4+
data: new SlashCommandBuilder()
5+
.setName('user')
6+
.setDescription('Provides information about the user.'),
7+
async execute(interaction) {
8+
// interaction.user is the object representing the User who ran the command
9+
// interaction.member is the GuildMember object, which represents the user in the specific guild
10+
await interaction.reply(`This command was run by ${interaction.user.username}, who joined on ${interaction.member.joinedAt}.`);
11+
},
12+
};

Slash/deployGlobal.js

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
require("dotenv").config()
2+
const { REST, Routes } = require('discord.js');
3+
const fs = require('node:fs');
4+
5+
const clientId = process.env.clientID
6+
const guildId = process.env.guildID
7+
const token = process.env.TOKEN
8+
9+
const commands = [];
10+
// Grab all the command files from the commands directory you created earlier
11+
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
12+
13+
// Grab the SlashCommandBuilder#toJSON() output of each command's data for deployment
14+
for (const file of commandFiles) {
15+
const command = require(`./commands/${file}`);
16+
commands.push(command.data.toJSON());
17+
}
18+
19+
// Construct and prepare an instance of the REST module
20+
const rest = new REST({ version: '10' }).setToken(token);
21+
22+
// and deploy your commands!
23+
(async () => {
24+
try {
25+
console.log(`Started refreshing ${commands.length} application (/) commands.`);
26+
27+
// The put method is used to fully refresh all commands in the guild with the current set
28+
const data = await rest.put(
29+
Routes.applicationCommands(clientId),
30+
{ body: commands },
31+
);
32+
console.log(`Successfully reloaded ${data.length} application (/) commands.`);
33+
} catch (error) {
34+
// And of course, make sure you catch and log any errors!
35+
console.error(error);
36+
}
37+
})();

Slash/deployLocal.js

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
require("dotenv").config()
2+
const { REST, Routes } = require('discord.js');
3+
const fs = require('node:fs');
4+
5+
const clientId = process.env.clientID
6+
const guildId = process.env.guildID
7+
const token = process.env.TOKEN
8+
9+
const commands = [];
10+
// Grab all the command files from the commands directory you created earlier
11+
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
12+
13+
// Grab the SlashCommandBuilder#toJSON() output of each command's data for deployment
14+
for (const file of commandFiles) {
15+
const command = require(`./commands/${file}`);
16+
commands.push(command.data.toJSON());
17+
}
18+
19+
// Construct and prepare an instance of the REST module
20+
const rest = new REST({ version: '10' }).setToken(token);
21+
22+
// and deploy your commands!
23+
(async () => {
24+
try {
25+
console.log(`Started refreshing ${commands.length} application (/) commands.`);
26+
27+
// The put method is used to fully refresh all commands in the guild with the current set
28+
const data = await rest.put(
29+
Routes.applicationGuildCommands(clientId, guildId),
30+
{ body: commands },
31+
);
32+
33+
console.log(`Successfully reloaded ${data.length} application (/) commands.`);
34+
} catch (error) {
35+
// And of course, make sure you catch and log any errors!
36+
console.error(error);
37+
}
38+
})();

Slash/index.js

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
require("dotenv").config()
2+
require("color");
3+
const fs = require('node:fs');
4+
const path = require('node:path');
5+
const { Client, Events, Collection, GatewayIntentBits } = require('discord.js');
6+
7+
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
8+
9+
client.commands = new Collection();
10+
11+
const commandsPath = path.join(__dirname, 'commands');
12+
const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js'));
13+
14+
for (const file of commandFiles) {
15+
const filePath = path.join(commandsPath, file);
16+
const command = require(filePath);
17+
// Set a new item in the Collection with the key as the command name and the value as the exported module
18+
if ('data' in command && 'execute' in command) {
19+
client.commands.set(command.data.name, command);
20+
} else {
21+
console.log(`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`);
22+
}
23+
}
24+
25+
client.once(Events.ClientReady, bot => {
26+
console.log(`Slash Commands Ready! Logged in as ${bot.user.tag}`.green);
27+
});
28+
29+
client.on(Events.InteractionCreate, async interaction => {
30+
if (!interaction.isChatInputCommand()) return;
31+
32+
const command = interaction.client.commands.get(interaction.commandName);
33+
34+
if (!command) {
35+
console.error(`No command matching ${interaction.commandName} was found.`);
36+
return;
37+
}
38+
39+
try {
40+
await command.execute(interaction);
41+
} catch (error) {
42+
console.error(error);
43+
await interaction.reply({ content: 'There was an error while executing this command!', ephemeral: true });
44+
}
45+
});
46+
47+
48+
49+
// Log in to Discord with your client's token
50+
client.login(process.env.TOKEN);

Slash/package.json

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
{
2+
"name": "pjs-slash",
3+
"version": "1.0.0",
4+
"description": "",
5+
"main": "index.js",
6+
"scripts": {
7+
"test": "echo \"Error: no test specified\" && exit 1"
8+
},
9+
"keywords": [],
10+
"author": "",
11+
"license": "ISC",
12+
"dependencies": {
13+
"color": "^4.2.3",
14+
"discord.js": "^14.6.0",
15+
"dotenv": "^16.0.3"
16+
}
17+
}

commands/Fun/chat.js

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
require("dotenv").config();
2+
3+
exports.run = async (client, msg, args) => {
4+
let trusted = client.trusted.find(usr => (usr == msg.author.id));
5+
if (!trusted) return msg.channel.send("Apologies, you are not allowed to talk to my friend Kyle3.5.")
6+
7+
const username = String(msg.author.username);
8+
const embedQuestion = new client.discord.MessageEmbed();
9+
const embedResult = new client.discord.MessageEmbed();
10+
embedResult.setColor("RANDOM");
11+
12+
embedQuestion.setColor("RANDOM");
13+
embedQuestion.addField("You asked ChatGPT...", args.join(" "));
14+
embedQuestion.setFooter({
15+
text: "Please wait for a response...Might take a few seconds...",
16+
iconURL: msg.author.avatarURL()
17+
});
18+
19+
msg.channel.send({
20+
embeds: [embedQuestion]
21+
}).then(async (msgEdit) => {
22+
23+
const completion = await client.openai.createChatCompletion({
24+
model: "gpt-3.5-turbo",
25+
messages: [{
26+
role: "user",
27+
content: args.join()
28+
}],
29+
max_tokens: 500,
30+
}).catch(err => {
31+
console.error("Err GPT:", err);
32+
embedResult.setDescription(`Uh oh, ${err.type}: ${err.message} ${err?.code}`);
33+
});
34+
35+
if (completion && completion?.data) {
36+
const choices = completion.data;
37+
const response = choices.choices[0].message;
38+
console.log(response);
39+
const gptResponse = segmentation(response.content)
40+
41+
// embedResult.addField("You asked DaVinci...", args.join(" "))
42+
for (let index = 0; index < gptResponse.length; index++) {
43+
if (index >= 16) embedResult.addField(`Too long`, `Apologies, have to refine code to indiacte more messages...`)
44+
else embedResult.addField(index === 0 ? `ChatGPT ${response.role}` : "\u200b", gptResponse[index])
45+
}
46+
} else {
47+
embedResult.addField(`Oopsie`, "No Result")
48+
}
49+
50+
embedResult.setFooter({
51+
text: username + ", this is an unfinished bot- it doesn't use previous answers yet.",
52+
iconURL: msg.author.avatarURL()
53+
})
54+
embedResult.setColor("RANDOM")
55+
56+
msgEdit.edit({
57+
embeds: [embedResult]
58+
})
59+
})
60+
}
61+
62+
const segmentation = (phrase) => {
63+
// return phrase.match(/[\s\S]{1,1020}/gm) || [];
64+
return phrase.trim().match(/.{1,1024}(\\s|$)/gm) || [];
65+
}
66+
67+
exports.help = {
68+
name: 'chat',
69+
desc: "chat using ChatGPT algorithm: gpt3.5-turbo",
70+
type: "Fun",
71+
usage: "chat Please tell me a short bedtime story",
72+
owner: false,
73+
locked: false,
74+
guild: false
75+
}

0 commit comments

Comments
 (0)