Commands updates

This commit is contained in:
2023-11-26 02:38:31 -07:00
parent ae5e194add
commit 66a37d03c2
9 changed files with 217 additions and 83 deletions

View File

@ -1,3 +1,4 @@
# Tokens
DISCORD_TOKEN=
OPENAI_API_KEY=
OPENAI_API_KEY=
STABILITY_API_KEY=

View File

@ -28,11 +28,11 @@ export class UserCommand extends Command {
private async sendBorf(interactionOrMessage: Message | Command.ChatInputCommandInteraction | Command.ContextMenuCommandInteraction) {
const dogResponse = await fetch('https://dog.ceo/api/breeds/image/random');
const dogData = await dogResponse.json();
const dogData = (await dogResponse.json()) as { message: string; status: string };
interactionOrMessage instanceof Message
? await interactionOrMessage.channel.send({
content: dogData.status === 'success' ? dogData.message : 'Error: I had troubles fetching perfect puppies for you... :('
content: dogData?.status === 'success' ? dogData.message : 'Error: I had troubles fetching perfect puppies for you... :('
})
: await interactionOrMessage.reply({
content: dogData.status === 'success' ? dogData.message : 'Error: I had troubles fetching perfect puppies for you... :(',

51
src/commands/credits.ts Normal file
View File

@ -0,0 +1,51 @@
import { ApplyOptions } from '@sapphire/decorators';
import { Command } from '@sapphire/framework';
import { Message } from 'discord.js';
// @ts-ignore
@ApplyOptions<Command.Options>({
description: 'Check how many credits I have left!'
})
export class UserCommand extends Command {
// Register Chat Input and Context Menu command
public override registerApplicationCommands(registry: Command.Registry) {
registry.registerChatInputCommand((builder) => builder.setName(this.name).setDescription(this.description));
}
// Message command
public async messageRun(message: Message) {
return this.credits(message);
}
// Chat Input (slash) command
public async chatInputRun(interaction: Command.ChatInputCommandInteraction) {
return this.credits(interaction);
}
private async credits(interactionOrMessage: Message | Command.ChatInputCommandInteraction | Command.ContextMenuCommandInteraction) {
const askMessage =
interactionOrMessage instanceof Message
? await interactionOrMessage.channel.send({ content: '🤔 Thinking... 🤔' })
: await interactionOrMessage.reply({ content: '🤔 Thinking... 🤔', fetchReply: true });
const creditCountResponse = await fetch(`https://api.stability.ai/v1/user/balance`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${process.env.STABILITY_API_KEY}`
}
});
const balance = ((await creditCountResponse.json()) as { credits: number }).credits || 0;
const content = `I have ${balance} credits remaining for image generation!`;
if (interactionOrMessage instanceof Message) {
return askMessage.edit({ content });
}
return interactionOrMessage.editReply({
content: content
});
}
}

View File

@ -32,7 +32,7 @@ export class UserCommand extends Command {
Accept: 'application/json'
}
});
const jokeData = await jokeResponse.json();
const jokeData = (await jokeResponse.json()) as { status: number; joke: string };
interactionOrMessage instanceof Message
? await interactionOrMessage.channel.send({

View File

@ -52,7 +52,7 @@ export class UserCommand extends Command {
prompt,
n: 1,
size: '1024x1024',
quality: 'hd'
quality: 'standard'
});
const imageUrl = response.data[0].url || '';

View File

@ -1,17 +1,15 @@
import { ApplyOptions } from '@sapphire/decorators';
import { Args, BucketScope, Command } from '@sapphire/framework';
import { AttachmentBuilder, Message } from 'discord.js';
import OpenAI from 'openai';
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY
});
// This is literally the worlds messiest TS code. Please don't judge me...
// @ts-ignore
@ApplyOptions<Command.Options>({
description: 'Generate a pic every 4 minutes!',
options: ['prompt'],
cooldownDelay: 400_000,
description: 'Make a picture... but high res!',
options: ['prompt', 'number of pictures'],
// 10mins
cooldownDelay: 100,
cooldownLimit: 1,
// Yes... I did hardcode myself.
cooldownFilteredUsers: ['83679718401904640'],
@ -27,65 +25,143 @@ export class UserCommand extends Command {
.addStringOption((option) =>
option.setName('prompt').setDescription('The prompt you will use to generate an image!').setRequired(true)
)
.addStringOption((option) =>
option
.setName('amount')
.setDescription('The number of images you would like to generate. Maximum 2.')
.setChoices(
...[
{ name: '1', value: '1' },
{ name: '2', value: '2' }
]
)
)
);
}
// Message command
public async messageRun(message: Message, args: Args) {
return this.pic(message, args.getOption('prompt') || 'NOTHING');
const amount = Math.abs(Number(args.getOption('amount')));
return this.picHr(message, args.getOption('prompt') || 'Scold me for not passing any prompt in.', amount <= 2 ? amount : 1);
}
// Chat Input (slash) command
public async chatInputRun(interaction: Command.ChatInputCommandInteraction) {
return this.pic(interaction, interaction.options.getString('prompt') || 'NOTHING');
const amount = Number(interaction.options.getString('amount'));
return this.picHr(interaction, interaction.options.getString('prompt') || 'NOTHING', amount || 1);
}
private async pic(interactionOrMessage: Message | Command.ChatInputCommandInteraction | Command.ContextMenuCommandInteraction, prompt: string) {
private async picHr(
interactionOrMessage: Message | Command.ChatInputCommandInteraction | Command.ContextMenuCommandInteraction,
prompt: string,
amount: number
) {
const askMessage =
interactionOrMessage instanceof Message
? await interactionOrMessage.channel.send({ content: '🤔 Thinking... 🤔' })
: await interactionOrMessage.reply({ content: '🤔 Thinking... 🤔', fetchReply: true });
try {
const response = await openai.images.generate({
model: 'dall-e-3',
prompt,
n: 1,
size: '1024x1024',
quality: 'standard'
const creditCountResponse = await fetch(`https://api.stability.ai/v1/user/balance`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${process.env.STABILITY_API_KEY}`
}
});
const balance = ((await creditCountResponse.json()) as { credits: number }).credits || 0;
if (balance > 5) {
const imageGenResponse = await fetch(`https://api.stability.ai/v1/generation/stable-diffusion-xl-1024-v1-0/text-to-image`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
Authorization: `Bearer ${process.env.STABILITY_API_KEY}`
},
body: JSON.stringify({
text_prompts: [
{
text: prompt
}
],
cfg_scale: 6,
clip_guidance_preset: 'FAST_BLUE',
height: 1024,
width: 1024,
samples: amount,
steps: 32,
seed: Number(String(interactionOrMessage.member?.user.id).substring(0, 5)) || 0
})
});
const imageUrl = response.data[0].url || '';
// get an array buffer
const imageBuffer = await fetch(imageUrl).then((r) => r.arrayBuffer());
const imageAttachment: AttachmentBuilder[] = [];
imageAttachment.push(
new AttachmentBuilder(Buffer.from(new Uint8Array(imageBuffer)), {
name: 'himbot_response.jpg',
description: `An image generated by Himbot using the prompt: ${prompt}`
})
);
const content = `Prompt: ${prompt}:`;
if (interactionOrMessage instanceof Message) {
return askMessage.edit({ content, files: imageAttachment });
interface GenerationResponse {
artifacts: Array<{
base64: string;
seed: number;
finishReason: string;
}>;
}
return interactionOrMessage.editReply({
content,
files: imageAttachment
});
} catch (error) {
const content = "Sorry, I can't complete the prompt for: " + prompt + '\n' + error;
if (!imageGenResponse.ok) {
const content = `Sorry, I can't complete the prompt for: ${prompt}`;
if (interactionOrMessage instanceof Message) {
return askMessage.edit({ content });
}
return interactionOrMessage.editReply({
content: content
});
} else {
const responseJSON = (await imageGenResponse.json()) as GenerationResponse;
const imageAttachment: AttachmentBuilder[] = [];
for (let i = 0; i < responseJSON.artifacts.length; i++) {
imageAttachment.push(
new AttachmentBuilder(Buffer.from(responseJSON.artifacts[i].base64, 'base64'), {
name: 'response.jpg',
description: "Himbot's Response"
})
);
}
const newCreditCountResponse = await fetch(`https://api.stability.ai/v1/user/balance`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${process.env.STABILITY_API_KEY}`
}
});
const newBalance = ((await newCreditCountResponse.json()) as { credits: number }).credits || 0;
const content =
`Credits Used: ${balance - newBalance}\nPrompt: ${prompt}${
balance <= 300
? `\n\n⚠I am now at ${balance} credits. If you'd like to help fund this command, please type "/support" for details!`
: ''
}` || 'ERROR!';
if (interactionOrMessage instanceof Message) {
return askMessage.edit({ content, files: imageAttachment });
}
return interactionOrMessage.editReply({
content,
files: imageAttachment
});
}
} else {
const content = `Oops! We're out of credits for this. If you'd like to help fund this command, please type "/support" for details!`;
if (interactionOrMessage instanceof Message) {
return askMessage.edit({ content });
}
return interactionOrMessage.editReply({ content });
return interactionOrMessage.editReply({
content: content
});
}
}
}

View File

@ -28,7 +28,7 @@ export class UserCommand extends Command {
private async sendQuack(interactionOrMessage: Message | Command.ChatInputCommandInteraction | Command.ContextMenuCommandInteraction) {
const duckResponse = await fetch('https://random-d.uk/api/v2/quack');
const duckData = await duckResponse.json();
const duckData = (await duckResponse.json()) as { url: string };
interactionOrMessage instanceof Message
? await interactionOrMessage.channel.send({