Skip to content

Commit

Permalink
Merge branch 'main' into fix-dms
Browse files Browse the repository at this point in the history
  • Loading branch information
Frannerz authored Dec 5, 2023
2 parents 8f5124d + 97c749d commit 93a5f07
Show file tree
Hide file tree
Showing 3 changed files with 99 additions and 55 deletions.
46 changes: 34 additions & 12 deletions src/commands.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ const commandLog = [];

const commandsList = {
ping: (message) => replyToMessage(message, "Pong!"),
greet: (message) => replyToMessage(message, `Hello ${message.author.username}!`),
greet: (message) =>
replyToMessage(message, `Hello ${message.author.username}!`),
joke: tellAJoke,
//echo:
help: help,
Expand All @@ -16,7 +17,12 @@ const commandsList = {
};

function replyToMessage(msg, answer) {
msg.reply(answer);
// Check if the answer is not undefined and not an empty string
if (answer !== undefined && answer !== "") {
msg.reply(answer);
} else {
console.warn("Tried to send an empty message. Ignoring.");
}
}

// Function to tell a joke with a delay
Expand All @@ -40,11 +46,13 @@ function help(message) {
//function echo() {}

//Function to display logged commands
function logCommands (message) {
function logCommands(message) {
if (commandLog.length > 0) {
message.channel.send(`Command Log:\n\`\`\`json\n${JSON.stringify(commandLog, null, 2)}\n\`\`\``);
message.channel.send(
`Command Log:\n\`\`\`json\n${JSON.stringify(commandLog, null, 2)}\n\`\`\``
);
} else {
message.channel.send('The command log is empty.');
message.channel.send("The command log is empty.");
}
}

Expand All @@ -54,13 +62,27 @@ function getRandomJoke() {
}

// function to access openai

function chat(message) {
return openaiResponse(message);
async function chat(message) {
const prompt = message;

if (prompt) {
try {
// Call the openaiResponse function and wait for the result
const response = await openaiResponse(prompt);

// Send the response back to the user
replyToMessage(message, response);
} catch (error) {
console.error("Error in openaiResponse:", error);
replyToMessage(
message,
"An error occurred while processing the request."
);
}
} else {
// Inform the user that they need to provide a prompt
replyToMessage(message, "Please provide a prompt after `!chat`.");
}
}

//chat("why is the sky blue?")


module.exports = { commandsList, commandLog };

36 changes: 24 additions & 12 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
require("dotenv").config();
const { Client, IntentsBitField, GatewayIntentBits, Partials } = require("discord.js");
const {
Client,
IntentsBitField,
GatewayIntentBits,
Partials,
} = require("discord.js");
const { commandsList, commandLog } = require("./commands");

const prefix = "!";
Expand All @@ -13,13 +18,11 @@ const client = new Client({
GatewayIntentBits.Guilds,
GatewayIntentBits.DirectMessages,
],
partials: [Partials.Message, Partials.Channel, Partials.Reaction]
partials: [Partials.Message, Partials.Channel, Partials.Reaction],
});


const mentionsLog = [];


client.once("ready", (c) => {
console.log(`${c.user.tag} is online!`);
});
Expand Down Expand Up @@ -53,9 +56,10 @@ client.on("messageCreate", (message) => {
if(message.content.includes('?') && !message.content.includes('!chat')) {
message.reply("That's a good question! Try starting your question with !chat");
}

const greeting = ["hi", "hello", "hey"];
for(const greet of greeting){
if(message.content.includes(greet)){
for (const greet of greeting) {
if (message.content.includes(greet)) {
message.reply(`Hi, ${message.author}, how can I help you?`);
}
}
Expand All @@ -66,13 +70,21 @@ client.on("messageCreate", (message) => {
const command = botMentioned
? message.content.split(' ')[1].slice(prefix.length).trim()
: message.content.split(' ')[0].slice(prefix.length).trim();

if (command in commandsList) {
commandLog.push(message.content);
commandsList[command](message);
//console.log(`command passed: ${command}`);

const isSpaceSeparatedCommand = command.includes(" ");
if (isSpaceSeparatedCommand) {
const [commandName, ...commandArgs] = command.split(" ");
if (commandName in commandsList) {
commandLog.push(message.content);
commandsList[commandName](message, commandArgs.join(" "));
}
} else {
if (command in commandsList) {
commandLog.push(message.content);
commandsList[command](message);
}
}
});


client.login(process.env.TOKEN);

72 changes: 41 additions & 31 deletions src/openai.js
Original file line number Diff line number Diff line change
@@ -1,39 +1,49 @@
require("dotenv").config();
const openai = require('openai');
const openai = require("openai");
const fetch = require("node-fetch");
const openaikey = process.env.OPENAI;
//const openai = new OpenAI();

//openai.ChatCompletion.create()

function openaiResponse(message) {
const endpoint = 'https://api.openai.com/v1/chat/completions';

fetch(endpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${openaikey}`,
},
body: JSON.stringify({
model: 'gpt-3.5-turbo',
messages: [{ "role": "user", "content": `${message}`}],
temperature: 0.7,
}),
})
.then(response =>
response.json())
.then(data => {

console.log(data.choices[0].message.content);

})
.catch(error => {
// Handle errors here
console.error('Error:', error);
});
}

const endpoint = "https://api.openai.com/v1/chat/completions";

// openaiResponse("why do cats purr?")
return fetch(endpoint, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${openaikey}`,
},
body: JSON.stringify({
model: "gpt-3.5-turbo",
messages: [{ role: "user", content: `${message}` }],
temperature: 0.7,
}),
})
.then((response) => {
if (!response.ok) {
throw new Error(
`OpenAI API request failed with status ${response.status}`
);
}
return response.json();
})
.then((data) => {
if (
data.choices &&
data.choices.length > 0 &&
data.choices[0].message &&
data.choices[0].message.content
) {
return data.choices[0].message.content;
} else {
throw new Error("Unexpected response format from OpenAI API");
}
})
.catch((error) => {
console.error("Error in openaiResponse:", error);
throw error;
});
}

module.exports = { openaiResponse };
module.exports = { openaiResponse };

0 comments on commit 93a5f07

Please sign in to comment.