Skip to content

Commit

Permalink
refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
jmhayes3 committed Aug 23, 2024
1 parent b9ba5a8 commit bd0dfc7
Show file tree
Hide file tree
Showing 20 changed files with 270 additions and 302 deletions.
10 changes: 0 additions & 10 deletions commands/core/about.js

This file was deleted.

102 changes: 42 additions & 60 deletions commands/core/chat.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
require('dotenv').config();

const { SlashCommandBuilder } = require('discord.js');
const { OpenAI } = require("openai");
import 'dotenv/config';
import { SlashCommandBuilder } from 'discord.js';
import { OpenAI } from 'openai';
import { splitString } from '../../utils.js';

const openai = new OpenAI({
apiKey: process.env['OPENAI_API_KEY'],

Check failure on line 7 in commands/core/chat.js

View workflow job for this annotation

GitHub Actions / test (18)

'process' is not defined

Check failure on line 7 in commands/core/chat.js

View workflow job for this annotation

GitHub Actions / lint

'process' is not defined

Check failure on line 7 in commands/core/chat.js

View workflow job for this annotation

GitHub Actions / test (20)

'process' is not defined

Check failure on line 7 in commands/core/chat.js

View workflow job for this annotation

GitHub Actions / test (22)

'process' is not defined
Expand Down Expand Up @@ -38,76 +38,58 @@ const addMessage = (threadId, content) => {
)
}

function splitString(str, length) {
if (length <= 0) {
throw new Error('Length must be greater than 0');
}

const segments = [];
for (let i = 0; i < str.length; i += length) {
segments.push(str.slice(i, i + length));
}

return segments;
}
export const data = new SlashCommandBuilder().setName('chat').setDescription('Chat with an AI assistant').addStringOption((option) => option.setName('message').setDescription('Input text.').setRequired(true)).addStringOption((option) => option.setName('assistant').setDescription('Assistant ID.').setRequired(false));

module.exports = {
data: new SlashCommandBuilder()
.setName('chat')
.setDescription('Chat with an AI assistant.')
.addStringOption((option) => option.setName('message').setDescription('Input text.').setRequired(true))
.addStringOption((option) => option.setName('assistant').setDescription('Assistant ID.').setRequired(false)),
async execute(interaction) {
await interaction.deferReply();
export async function execute(interaction) {
await interaction.deferReply();

const channelId = await interaction.channelId;
console.log("Channel ID: ", channelId);
const channelId = await interaction.channelId;
console.log("Channel ID: ", channelId);

const interactionId = interaction.id;
console.log("Interaction ID: ", interactionId);
const interactionId = interaction.id;
console.log("Interaction ID: ", interactionId);

const message = interaction.options.getString('message');
console.log("Message: ", message);
const message = interaction.options.getString('message');
console.log("Message: ", message);

const assistantId = interaction.options.getString('assistant');
console.log("Assistant ID: ", assistantId);
const assistantId = interaction.options.getString('assistant');
console.log("Assistant ID: ", assistantId);

const thread = await openai.beta.threads.create();
const openaiThreadId = thread.id;
const thread = await openai.beta.threads.create();
const openaiThreadId = thread.id;

await addMessage(openaiThreadId, message);
await addMessage(openaiThreadId, message);

const run = await openai.beta.threads.runs.create(
openaiThreadId,
{ assistant_id: assistantId || process.env.ASSISTANT_ID }
)
const status = await statusCheckLoop(openaiThreadId, run.id);
console.log("Status: ", status);
const run = await openai.beta.threads.runs.create(
openaiThreadId,
{ assistant_id: assistantId || process.env.ASSISTANT_ID }

Check failure on line 65 in commands/core/chat.js

View workflow job for this annotation

GitHub Actions / test (18)

'process' is not defined

Check failure on line 65 in commands/core/chat.js

View workflow job for this annotation

GitHub Actions / lint

'process' is not defined

Check failure on line 65 in commands/core/chat.js

View workflow job for this annotation

GitHub Actions / test (20)

'process' is not defined

Check failure on line 65 in commands/core/chat.js

View workflow job for this annotation

GitHub Actions / test (22)

'process' is not defined
)
const status = await statusCheckLoop(openaiThreadId, run.id);
console.log("Status: ", status);

const messages = await openai.beta.threads.messages.list(openaiThreadId);
const response = messages.data[0].content[0].text.value;
const messages = await openai.beta.threads.messages.list(openaiThreadId);
const response = messages.data[0].content[0].text.value;

const responses = splitString(response, 2000);
const responses = splitString(response, 2000);

console.log("Num Responses: ", responses.length);
console.log("Responses: ", responses);
console.log("Num Responses: ", responses.length);
console.log("Responses: ", responses);

await interaction.followUp(responses[0]);
await interaction.followUp(responses[0]);

if (interaction.channel.isThread()) {
console.log("is thread");
console.log(interaction.channel);
} else {
console.log("not thread");
console.log(interaction.channel);
}
if (interaction.channel.isThread()) {
console.log("is thread");
console.log(interaction.channel);
} else {
console.log("not thread");
console.log(interaction.channel);
}

if (responses.length > 1) {
for (let i = 1; i < responses.length; ++i) {
console.log(responses[i]);
if (responses.length > 1) {
for (let i = 1; i < responses.length; ++i) {
console.log(responses[i]);

await interaction.followUp(responses[i]);
}
await interaction.followUp(responses[i]);
}
},
}
};
75 changes: 30 additions & 45 deletions commands/core/dump.js
Original file line number Diff line number Diff line change
@@ -1,59 +1,44 @@
const { SlashCommandBuilder } = require('discord.js');
const { OpenAI } = require("openai");
import 'dotenv/config';
import { SlashCommandBuilder } from 'discord.js';
import { OpenAI } from 'openai';
import { splitString } from '../../utils.js';

const openai = new OpenAI({
apiKey: process.env['OPENAI_API_KEY'],

Check failure on line 7 in commands/core/dump.js

View workflow job for this annotation

GitHub Actions / test (18)

'process' is not defined

Check failure on line 7 in commands/core/dump.js

View workflow job for this annotation

GitHub Actions / lint

'process' is not defined

Check failure on line 7 in commands/core/dump.js

View workflow job for this annotation

GitHub Actions / test (20)

'process' is not defined

Check failure on line 7 in commands/core/dump.js

View workflow job for this annotation

GitHub Actions / test (22)

'process' is not defined
});

function splitString(str, length) {
if (length <= 0) {
throw new Error('Length must be greater than 0');
}

const segments = [];
for (let i = 0; i < str.length; i += length) {
segments.push(str.slice(i, i + length));
}

return segments;
}
export const data = new SlashCommandBuilder().setName('dump').setDescription('Dump messages from an OpenAI thread into a Discord thread.').addStringOption((option) => option.setName('thread').setDescription('OpenAI thread ID.').setRequired(true));

module.exports = {
data: new SlashCommandBuilder()
.setName('dump')
.setDescription('Dump messages from an OpenAI thread.')
.addStringOption((option) => option.setName('thread').setDescription('OpenAI thread ID.').setRequired(true)),
async execute(interaction) {
await interaction.deferReply();
export async function execute(interaction) {
await interaction.deferReply();

const openaiThreadId = interaction.options.getString('thread');
console.log(openaiThreadId);
const openaiThreadId = interaction.options.getString('thread');
console.log(openaiThreadId);

const messagesList = await openai.beta.threads.messages.list(openaiThreadId);
console.log("Messages List:", messagesList);
const messagesList = await openai.beta.threads.messages.list(openaiThreadId);
console.log("Messages List:", messagesList);

const messages = Array.from(messagesList.data).map(msg => msg.content).reverse();
console.log(messages);
const messages = Array.from(messagesList.data).map(msg => msg.content).reverse();
console.log(messages);

for await (const msg of messages) {
let content = null;
if (msg[0].text) {
content = msg[0].text.value;
console.log("Content:", content);
const replies = splitString(content, 2000);
for (let i = 0; i < replies.length; i++) {
console.log(replies[i]);
await interaction.followUp({ content: replies[i] });
}
} else if (msg[0].image_file) {
const image = msg[0].image_file;
console.log("Image file:", image);
await interaction.followUp({ content: image });
} else if (msg[0].image_url) {
const image = msg[0].image_url;
console.log("Image url:", image);
await interaction.followUp({ content: image });
for await (const msg of messages) {
let content = null;
if (msg[0].text) {
content = msg[0].text.value;
console.log("Content:", content);
const replies = splitString(content, 2000);
for (let i = 0; i < replies.length; i++) {
console.log(replies[i]);
await interaction.followUp({ content: replies[i] });
}
} else if (msg[0].image_file) {
const image = msg[0].image_file;
console.log("Image file:", image);
await interaction.followUp({ content: image });
} else if (msg[0].image_url) {
const image = msg[0].image_url;
console.log("Image url:", image);
await interaction.followUp({ content: image });
}
}
};
9 changes: 9 additions & 0 deletions commands/core/info.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { SlashCommandBuilder } from 'discord.js';

export const data = new SlashCommandBuilder().setName('info').setDescription('Display app information');

export async function execute(interaction) {
await interaction.deferReply({ ephemeral: true });
const content = "App info.";
await interaction.followUp({ content: content, ephemeral: true });
};
34 changes: 20 additions & 14 deletions commands/core/list.js
Original file line number Diff line number Diff line change
@@ -1,25 +1,31 @@
const { SlashCommandBuilder } = require('discord.js');
const { OpenAI } = require("openai");
import 'dotenv/config';
import { SlashCommandBuilder } from 'discord.js';
import { OpenAI } from 'openai';

const openai = new OpenAI({
apiKey: process.env['OPENAI_API_KEY'],

Check failure on line 6 in commands/core/list.js

View workflow job for this annotation

GitHub Actions / test (18)

'process' is not defined

Check failure on line 6 in commands/core/list.js

View workflow job for this annotation

GitHub Actions / lint

'process' is not defined

Check failure on line 6 in commands/core/list.js

View workflow job for this annotation

GitHub Actions / test (20)

'process' is not defined

Check failure on line 6 in commands/core/list.js

View workflow job for this annotation

GitHub Actions / test (22)

'process' is not defined
});

const getAssistants = async () => {
const payload = await openai.beta.assistants.list();
return Array.from(payload.data).map(msg => msg.name);
// console.log(payload);
const data = [];
for (let i = 0; i < payload.data.length; i++) {
console.log(payload.data[i]);
const text = payload.data[i].name + " " + "(" + payload.data[i].model + ")";
data.push(text);
}
return data;
}

module.exports = {
data: new SlashCommandBuilder()
.setName('list')
.setDescription('List all available OpenAI assistants.'),
async execute(interaction) {
await interaction.deferReply();
export const data = new SlashCommandBuilder().setName('list').setDescription('List all available OpenAI assistants.');

const assistants = await getAssistants();
const reply = assistants.join("\n");
export async function execute(interaction) {
await interaction.deferReply();

await interaction.followUp({ content: reply, ephemeral: true });
},
};
const assistants = await getAssistants();
console.log(assistants);
const reply = assistants.join("\n");

await interaction.followUp({ content: reply, ephemeral: true });
}
48 changes: 23 additions & 25 deletions commands/core/load.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
const { SlashCommandBuilder } = require('discord.js');
const { OpenAI } = require("openai");
import 'dotenv/config';
import { SlashCommandBuilder } from 'discord.js';
import { OpenAI } from 'openai';

const openai = new OpenAI({
apiKey: process.env['OPENAI_API_KEY'],

Check failure on line 6 in commands/core/load.js

View workflow job for this annotation

GitHub Actions / test (18)

'process' is not defined

Check failure on line 6 in commands/core/load.js

View workflow job for this annotation

GitHub Actions / lint

'process' is not defined

Check failure on line 6 in commands/core/load.js

View workflow job for this annotation

GitHub Actions / test (20)

'process' is not defined

Check failure on line 6 in commands/core/load.js

View workflow job for this annotation

GitHub Actions / test (22)

'process' is not defined
Expand All @@ -16,33 +17,30 @@ const addMessage = (threadId, content) => {
)
}

module.exports = {
data: new SlashCommandBuilder()
.setName('load')
.setDescription('Load messages into an OpenAI thread.'),
async execute(interaction) {
await interaction.deferReply();
export const data = new SlashCommandBuilder().setName('load').setDescription('Load messages into an OpenAI thread.');

const thread = await openai.beta.threads.create();
const openaiThreadId = thread.id;
export async function execute(interaction) {
await interaction.deferReply();

// load messages from thread
if (interaction.channel.isThread()) {
const messagesRaw = await interaction.channel.messages.fetch();
const thread = await openai.beta.threads.create();
const openaiThreadId = thread.id;

// load oldest messages first
const messages = Array.from(messagesRaw.values()).map(msg => msg.content).reverse();
console.log(messages);
// load messages from thread
if (interaction.channel.isThread()) {
const messagesRaw = await interaction.channel.messages.fetch();

// remove empty messages
const filteredMessages = messages.filter(msg => !!msg && msg !== '')
console.log(filteredMessages);
// load oldest messages first
const messages = Array.from(messagesRaw.values()).map(msg => msg.content).reverse();
console.log(messages);

await Promise.all(filteredMessages.map(msg => addMessage(openaiThreadId, msg)));
// remove empty messages
const filteredMessages = messages.filter(msg => !!msg && msg !== '')
console.log(filteredMessages);

await interaction.followUp("Messages loaded into OpenAI thread: " + openaiThreadId);
} else {
await interaction.followUp({ content: "Load failed. Not in a thread." });
}
},
await Promise.all(filteredMessages.map(msg => addMessage(openaiThreadId, msg)));

await interaction.followUp("Messages loaded into OpenAI thread: " + openaiThreadId);
} else {
await interaction.followUp({ content: "Load failed. Not in a thread." });
}
};
14 changes: 5 additions & 9 deletions commands/core/ping.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,8 @@
const { SlashCommandBuilder } = require('discord.js');
import { SlashCommandBuilder } from 'discord.js';

module.exports = {
data: new SlashCommandBuilder()
.setName('ping')
.setDescription('Send a ping.'),
async execute(interaction) {
const sent = await interaction.reply({ content: 'Pinging...', fetchReply: true, ephemeral: true });
export const data = new SlashCommandBuilder().setName('ping').setDescription('Send a ping.');

await interaction.editReply(`Round-trip latency: ${sent.createdTimestamp - interaction.createdTimestamp}ms`);
},
export async function execute(interaction) {
const sent = await interaction.reply({ content: 'Pinging...', fetchReply: true, ephemeral: true });
await interaction.editReply(`Round-trip latency: ${sent.createdTimestamp - interaction.createdTimestamp}ms`);
};
14 changes: 14 additions & 0 deletions commands/core/profile.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { ContextMenuCommandBuilder, ApplicationCommandType } from 'discord.js';

export const data = new ContextMenuCommandBuilder().setName('Profile').setType(ApplicationCommandType.User);

export async function execute(interaction) {
if (!interaction.isUserContextMenuCommand()) return;

await interaction.deferReply({ ephemeral: true });

const username = interaction.user.username;
console.log(username);

await interaction.followUp({ content: username, ephemeral: true });
};
10 changes: 0 additions & 10 deletions commands/core/server.js

This file was deleted.

Loading

0 comments on commit bd0dfc7

Please sign in to comment.