Skip to content

Commit

Permalink
make art btn is pog
Browse files Browse the repository at this point in the history
  • Loading branch information
bramses committed Aug 29, 2023
1 parent 4a5d5a8 commit a478717
Show file tree
Hide file tree
Showing 5 changed files with 166 additions and 48 deletions.
114 changes: 75 additions & 39 deletions bot.js
@@ -1,52 +1,88 @@

import fs from 'node:fs';
import path from 'node:path';
import { Client, Collection, Events, GatewayIntentBits } from 'discord.js';
import fs from "node:fs";
import path from "node:path";
import { Client, Collection, Events, GatewayIntentBits } from "discord.js";
import { main } from "./commands/dalle/aart.js";
import { invocationWorkflow } from "./invocation.js";

const client = new Client({ intents: [GatewayIntentBits.Guilds] });
import config from './config.json' assert { "type": "json" };
import config from "./config.json" assert { "type": "json" };

client.on('ready', () => {
client.on("ready", () => {
console.log(`Logged in as ${client.user.tag}!`);
});

client.commands = new Collection();
const foldersPath = new URL('./commands', import.meta.url).pathname;
const foldersPath = new URL("./commands", import.meta.url).pathname;
const commandFolders = fs.readdirSync(foldersPath);

for (const folder of commandFolders) {
const commandsPath = path.join(foldersPath, folder);
const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const filePath = path.join(commandsPath, file);
const command = await import(filePath);
// Set a new item in the Collection with the key as the command name and the value as the exported module
if ('data' in command && 'execute' in command) {
client.commands.set(command.data.name, command);
} else {
console.log(`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`);
}
}
const commandsPath = path.join(foldersPath, folder);
const commandFiles = fs
.readdirSync(commandsPath)
.filter((file) => file.endsWith(".js"));
for (const file of commandFiles) {
const filePath = path.join(commandsPath, file);
const command = await import(filePath);
// Set a new item in the Collection with the key as the command name and the value as the exported module
if ("data" in command && "execute" in command) {
client.commands.set(command.data.name, command);
} else {
console.log(
`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`
);
}
}
}

client.on(Events.InteractionCreate, async interaction => {
if (!interaction.isChatInputCommand()) return;

const command = client.commands.get(interaction.commandName);

if (!command) return;

try {
await command.execute(interaction);
} catch (error) {
console.error(error);
console.log(`[ERROR] There was an error while executing the command ${interaction.commandName}.`);
console.log(`[ERROR] ${JSON.stringify(error.rawError.errors.content)}`);
if (interaction.replied || interaction.deferred) {
await interaction.followUp({ content: 'There was an error while executing this command!', ephemeral: true });
} else {
await interaction.reply({ content: 'There was an error while executing this command!', ephemeral: true });
}
}
client.on(Events.InteractionCreate, async (interaction) => {
if (!interaction.isChatInputCommand() && !interaction.isButton()) return;

if (interaction.isButton()) {
console.log(interaction);
console.log(interaction.customId);
if (interaction.customId === "button_id") {
await interaction.deferReply();
console.log(`Button was clicked by: ${interaction.user.username}`);
// Here you can call your function
console.log(interaction.message.content);
const { prompt, imageUrl } = await main(interaction.message.content);
// console.log(prompt);

if (interaction.replied || interaction.deferred) {
await interaction.followUp(`Art Prompt (save the image it disappears in 24 hours!): ${prompt} \n Image: [(url)](${imageUrl})`);
} else {
await interaction.reply(`Art Prompt (save the image it disappears in 24 hours!): ${prompt} \n Image: [(url)](${imageUrl})`);
}
// set interaction command name to aart
interaction.commandName = "aart";
await invocationWorkflow(interaction, true);
}
return;
} else {
const command = client.commands.get(interaction.commandName);

if (!command) return;

try {
await command.execute(interaction);
} catch (error) {
console.error(error);
console.log(
`[ERROR] There was an error while executing the command ${interaction.commandName}.`
);
console.log(`[ERROR] ${JSON.stringify(error.rawError.errors.content)}`);
if (interaction.replied || interaction.deferred) {
await interaction.followUp({
content: "There was an error while executing this command!",
ephemeral: true,
});
} else {
await interaction.reply({
content: "There was an error while executing this command!",
ephemeral: true,
});
}
}
}
});
client.login(config.token);
client.login(config.token);
5 changes: 2 additions & 3 deletions commands/dalle/aart.js
Expand Up @@ -26,7 +26,7 @@ async function complete(text) {
return completion.choices[0].message.content;
}

async function main(prompt) {
export async function main(prompt) {
prompt = await complete(prompt);
prompt = prompt.replace("Art Prompt: ", "").trim();
const image = await openai.images.generate({ prompt: prompt });
Expand All @@ -35,8 +35,7 @@ async function main(prompt) {
return {
prompt,
imageUrl,
}

}
}

export const data = new SlashCommandBuilder()
Expand Down
20 changes: 18 additions & 2 deletions commands/quoordinates/quos.js
@@ -1,5 +1,11 @@
import config from "../../config.json" assert { "type": "json" };
import { SlashCommandBuilder, ChannelType } from "discord.js";
import {
SlashCommandBuilder,
ChannelType,
ActionRowBuilder,
ButtonBuilder,
ButtonStyle,
} from "discord.js";
import { invocationWorkflow, preWorkflow } from "../../invocation.js";
import { lookupBook } from "../../books.js";

Expand Down Expand Up @@ -60,8 +66,18 @@ export async function execute(interaction) {
reason: "Sending quotes as separate messages in one thread",
});

const confirm = new ButtonBuilder()
.setCustomId("button_id")
.setLabel("Make Art")
.setStyle(ButtonStyle.Primary);

const row = new ActionRowBuilder().addComponents(confirm);

for (const quote of quotes) {
await thread.send(quote);
await thread.send({
content: quote,
components: [row],
});
}
await interaction.editReply(`Results: ${quoordinate.length} quotes`);
await invocationWorkflow(interaction);
Expand Down
57 changes: 57 additions & 0 deletions commands/spotify/companion.js
@@ -0,0 +1,57 @@
// const axios = require('axios');

// // Your OpenAI and Spotify API credentials
// const openaiApiKey = 'your-openai-api-key';
// const spotifyClientId = 'your-spotify-client-id';
// const spotifyClientSecret = 'your-spotify-client-secret';

// // The text input
// const text = "They're thirty metres up in the air now, ten storeys. There's a stabbing pain developing in her left eye. She kicks her shoes off and throws the gun away. She goes to the edge and contemplates the drop for a disbelieving second. She jumps. It takes two heart-stopping seconds of freefall for her to hit the water. The chilled hammerblow of the impact is enough to blank her mind out. By the time she surfaces she doesn't remember where she fell from, or why. And likewise, the skyscraper-sized being which claimed Marness and the boat has forgotten about her. 'What the hell,' she gasps, treading water. 'What the hell, where the hell?' There is nothing above her, no explanation. Only the symptoms of the drug cocktail give her any indication of what just happened: a sensation like hundreds of tiny lumps of hot solder in her brain, and pain and exhaustion spreading to all of her tendons. She wants to die. Swim, says part of her. Get to shore first. Then you can die.";

// // Use OpenAI's ChatGPT completion API to analyze the text and generate a list of genres
// axios.post('https://api.openai.com/v1/chat/completions', {
// model: "gpt-3.5-turbo",
// messages: [
// {"role": "system", "content": "You are a helpful assistant."},
// {"role": "user", "content": `Given the following text, suggest three music genres that would fit the mood and themes:\n\n${text}`}
// ],
// max_tokens: 60,
// }, {
// headers: {
// 'Authorization': `Bearer ${openaiApiKey}`,
// 'Content-Type': 'application/json'
// }
// }).then(response => {
// // Extract the genres from the response
// const genres = response.data.choices[0].text.trim().split(', ');

// // Get an access token from the Spotify API
// return axios.post('https://accounts.spotify.com/api/token', new URLSearchParams({
// 'grant_type': 'client_credentials',
// }), {
// headers: {
// 'Authorization': `Basic ${Buffer.from(`${spotifyClientId}:${spotifyClientSecret}`).toString('base64')}`,
// 'Content-Type': 'application/x-www-form-urlencoded'
// }
// }).then(response => {
// return { accessToken: response.data.access_token, genres };
// });
// }).then(({ accessToken, genres }) => {
// // Use the Spotify API to get recommendations based on the genres
// return axios.get('https://api.spotify.com/v1/recommendations', {
// headers: {
// 'Authorization': `Bearer ${accessToken}`
// },
// params: {
// seed_genres: genres.join(','),
// limit: 3
// }
// });
// }).then(response => {
// // Print the recommended tracks
// for (const track of response.data.tracks) {
// console.log(track.name);
// }
// }).catch(error => {
// console.error(error);
// });
18 changes: 14 additions & 4 deletions invocation.js
Expand Up @@ -29,12 +29,22 @@ const addUser = (interaction, invocations) => {
}

// add invocation to invocations.json
const addInvocation = (interaction, invocations) => {
const addInvocation = (interaction, invocations, isButton = false) => {
const userName = getUserName(interaction);
let query = null;

if (isButton) {
// use interaction.message.content as query
query = interaction.message.content;
} else {
// use interaction.options.getString('input') as query
query = interaction.options.getString('input') || null;
}

invocations[userName].commands.push({
command: interaction.commandName,
time: new Date().toISOString(),
query: interaction.options.getString('input') || null,
query: query,
});
if (interaction.commandName in invocations[userName].commandInvocations) {
invocations[userName].commandInvocations[interaction.commandName] += 1;
Expand Down Expand Up @@ -97,9 +107,9 @@ const loadCommandLimits = () => {


// main function
export const invocationWorkflow = async (interaction) => {
export const invocationWorkflow = async (interaction, isButton = false) => {
let invocations = loadInvocations();
invocations = addInvocation(interaction, invocations);
invocations = addInvocation(interaction, invocations, isButton);
saveInvocations(invocations);

return invocations;
Expand Down

0 comments on commit a478717

Please sign in to comment.