Compare commits

..

No commits in common. "main" and "nodGPT" have entirely different histories.
main ... nodGPT

26 changed files with 441 additions and 790 deletions

BIN
.DS_Store vendored Normal file

Binary file not shown.

23
.github/workflows/docker-image.yml vendored Normal file
View File

@ -0,0 +1,23 @@
name: Docker Image CI
on:
workflow_dispatch:
env:
DHUB_UNAME: ${{ secrets.DHUB_UNAME }}
DHUB_PWORD: ${{ secrets.DHUB_PWORD }}
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Build the Docker image
run: docker build . --file Dockerfile --tag v0idf1sh/nodbot
- name: Log into Docker Hub
run: docker login -u $DHUB_UNAME -p $DHUB_PWORD
- name: Push image to Docker Hub
run: docker push v0idf1sh/nodbot

View File

@ -1,35 +0,0 @@
name: NodBot Production Dockerization
on:
commit:
branches:
- pe
env:
DHUB_UNAME: ${{ secrets.DHUB_UNAME }}
DHUB_PWORD: ${{ secrets.DHUB_PWORD }}
jobs:
build:
runs-on: self-hosted
steps:
- name: Pull latest from Git
run: |
pwd
whoami
cd /root/nodbot
git pull
git checkout pe
- name: Build the Docker image
run: |
cd /root/nodbot
docker build . --file Dockerfile --tag v0idf1sh/nodbot-pe
- name: Log into Docker Hub
run: docker login -u $DHUB_UNAME -p $DHUB_PWORD
- name: Push image to Docker Hub
run: |
cd /root/nodbot
docker push v0idf1sh/nodbot-pe

View File

@ -1,35 +0,0 @@
name: NodBot Production Dockerization
on:
pull_request:
branches:
- main
env:
DHUB_UNAME: ${{ secrets.DHUB_UNAME }}
DHUB_PWORD: ${{ secrets.DHUB_PWORD }}
jobs:
build:
runs-on: self-hosted
steps:
- name: Pull latest from Git
run: |
pwd
whoami
cd /root/nodbot
git pull
git checkout $GITHUB_HEAD_REF
- name: Build the Docker image
run: |
cd /root/nodbot
docker build . --file Dockerfile --tag v0idf1sh/nodbot
- name: Log into Docker Hub
run: docker login -u $DHUB_UNAME -p $DHUB_PWORD
- name: Push image to Docker Hub
run: |
cd /root/nodbot
docker push v0idf1sh/nodbot

4
.gitignore vendored
View File

@ -2,7 +2,8 @@
.vscode .vscode
package-lock.json package-lock.json
.VSCodeCounter/ .VSCodeCounter/
.env* env.dev
env.prod
# Custom folders # Custom folders
# gifs/* # gifs/*
@ -114,4 +115,3 @@ dist
# TernJS port file # TernJS port file
.tern-port .tern-port
.DS_Store

View File

@ -1,52 +0,0 @@
module.exports = {
GifData: class {
constructor() {
this.id = 0;
this.name = "";
this.url = "";
}
// Initial GifData configuration
// Can also be used to update the data piecemeal
setInfo(name, url, id) {
// Check for existing or incoming name
if ((this.name === "") && (typeof name !== 'string')) throw `Error: This Gif doesn't have existing name, and no name is going to be set.`;
// Check for existing content or incoming content
if ((this.url === "") && (typeof url !== 'string')) throw `Error: This Gif doesn't have existing url, and no url is going to be set.`;
// Property is set if the variable is the right type,
// otherwise it keeps the existing property
this.id = typeof id === 'number' ? id : this.id;
this.name = typeof name === 'string' ? name : this.name;
this.url = typeof url === 'string' ? url : this.url;
return this; // For chaining
}
},
PastaData: class {
constructor() {
this.id = 0;
this.name = "";
this.content = "";
this.iconUrl = "";
}
// Initial PastaData configuration
// Can also be used to update the data piecemeal
setInfo(name, content, iconUrl, id) {
// Check for existing or incoming name
if ((this.name === "") && (typeof name !== 'string')) throw `Error: This Pasta doesn't have existing name, and no name is going to be set.`;
// Check for existing content or incoming content
if ((this.content === "") && (typeof content !== 'string')) throw `Error: This Pasta doesn't have existing content, and no content is going to be set.`;
// Property is set if the variable is the right type,
// otherwise it keeps the existing property
this.id = typeof id === 'number' ? id : this.id;
this.name = typeof name === 'string' ? name : this.name;
this.content = typeof content === 'string' ? content : this.content;
this.iconUrl = typeof iconUrl === 'string' ? iconUrl : this.iconUrl;
return this; // For chaining
}
}
}

View File

@ -1,9 +1,8 @@
FROM node:18 FROM node:16
RUN mkdir -p /usr/src/app RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app WORKDIR /usr/src/app
COPY package.json ./ COPY package.json ./
RUN npm install RUN npm install
COPY . . COPY . .
# CMD ["/bin/sh", "-c", "node main.js 2> /logs/nodbot.error 1> /logs/nodbot.log"] CMD ["/bin/sh", "-c", "node main.js 2> /logs/nodbot.error 1> /logs/nodbot.log"]
CMD ["/bin/sh", "-c", "node main.js 2> /logs/$(date +%Y-%m-%d_%H-%M-%S)-error.txt 1> /logs/$(date +%Y-%m-%d_%H-%M-%S)-status.txt"]

View File

@ -1,5 +1,4 @@
{ {
"guildId": "868542949737246730", "guildId": "868542949737246730",
"validCommands": [], "validCommands": []
"roaches": []
} }

View File

@ -13,7 +13,7 @@ module.exports = {
async execute(message, commandData) { async execute(message, commandData) {
// if (message.deletable) message.delete(); // if (message.deletable) message.delete();
const client = message.client; const client = message.client;
if (!client.gifs.has(commandData.args.toLowerCase())) { if (!client.gifs.has(commandData.args)) {
if (process.env.isDev) console.log('https://tenor.googleapis.com/v2/search?' + `&q=${commandData.args}` + `&key=${process.env.tenorAPIKey}` + '&limit=1&contentfilter=off'); if (process.env.isDev) console.log('https://tenor.googleapis.com/v2/search?' + `&q=${commandData.args}` + `&key=${process.env.tenorAPIKey}` + '&limit=1&contentfilter=off');
const q = await axios.get( const q = await axios.get(
'https://tenor.googleapis.com/v2/search?' + 'https://tenor.googleapis.com/v2/search?' +
@ -43,11 +43,11 @@ module.exports = {
// }).catch(err => console.error(err)); // }).catch(err => console.error(err));
} else { } else {
// message.reply(commandData.args + ' requested by ' + message.author.username + '\n' + client.gifs.get(commandData.args).embed_url); // message.reply(commandData.args + ' requested by ' + message.author.username + '\n' + client.gifs.get(commandData.args).embed_url);
const gifData = client.gifs.get(commandData.args.toLowerCase()); commandData.embed_url = client.gifs.get(commandData.args).embed_url;
// message.reply(fn.embeds.gif(commandData)); // message.reply(fn.embeds.gif(commandData));
// message.channel.send(`> ${commandData.author} - ${commandData.args}.gif`); // message.channel.send(`> ${commandData.author} - ${commandData.args}.gif`);
// message.channel.send(commandData.embed_url); // message.channel.send(commandData.embed_url);
message.reply(gifData.url); message.reply(commandData.embed_url);
} }
} }
} }

View File

@ -5,33 +5,13 @@ module.exports = {
name: 'joint', name: 'joint',
description: 'Send a random weed-themed phrase.', description: 'Send a random weed-themed phrase.',
usage: '.joint', usage: '.joint',
alias: ['bong', 'blunt', 'bowl', 'pipe', 'dab', 'vape', 'dabs', 'shatter', 'edible', 'edibles', 'doobie', 'spliff', 'gummy', 'gummies', 'hash', 'toke', 'big doinks'], alias: ['bong', 'blunt', 'bowl', 'pipe'],
execute(message, commandData) { execute(message, commandData) {
let joints = []; let joints = [];
// Create a simple array of the joint texts
for (const entry of message.client.joints.map(joint => joint.content)) { for (const entry of message.client.joints.map(joint => joint.content)) {
joints.push(entry); joints.push(entry);
} }
// Generate a random number between 0 and the length of the joints array const randIndex = Math.floor(Math.random() * joints.length);
let randIndex = Math.floor(Math.random() * joints.length);
// Grab the joint text from the array
let joint = joints[randIndex];
// Check if the joint has already been smoked
while (message.client.roaches.has(joint)) {
// Regenerate a random number and recheck
randIndex = Math.floor(Math.random() * joints.length);
joint = joints[randIndex];
}
// Send the joint
message.reply(`${joints[randIndex]} ${emoji.joint}`); message.reply(`${joints[randIndex]} ${emoji.joint}`);
// Check how full the roach collection is
if (message.client.roaches.size / joints.length >= 0.85) {
// If the roach collection is 85% of the joints collection
// Empty it out
message.client.roaches.clear();
}
// Add the joint to the roach collection
message.client.roaches.set(joint, "baked");
} }
} }

View File

@ -6,14 +6,14 @@ module.exports = {
usage: '<Copypasta Name>.pasta', usage: '<Copypasta Name>.pasta',
execute(message, commandData) { execute(message, commandData) {
const client = message.client; const client = message.client;
let pastaData; let replyBody = '';
let iconUrl;
if (!client.pastas.has(commandData.args)) { if (!client.pastas.has(commandData.args)) {
pastaData = { commandData.content = 'Sorry I couldn\'t find that pasta.';
content: "Sorry, I couldn't find that pasta."
};
} else { } else {
pastaData = client.pastas.get(commandData.args); commandData.content = client.pastas.get(commandData.args).content;
commandData.iconUrl = client.pastas.get(commandData.args).iconUrl;
} }
message.reply(fn.embeds.pasta(commandData, pastaData)); message.reply(fn.embeds.pasta(commandData));
} }
} }

View File

@ -10,33 +10,20 @@ module.exports = {
// message.reply(fn.spongebob(commandData)).then(() => { // message.reply(fn.spongebob(commandData)).then(() => {
// message.delete(); // message.delete();
// }); // });
if (message.reference != undefined) { // message.reference is undefined if the message isn't a reply to another message if (message.reference != undefined) {
if (commandData.args !== "") { // If the replying message isn't just .sb const repliedMessageId = message.reference.messageId;
const repliedMessageId = message.reference.messageId; // grab the message Id of the replied-to msg message.channel.messages.fetch(repliedMessageId)
message.channel.messages.fetch(repliedMessageId) // Fetch the message because with our luck it isn't in the cache .then(repliedMessage => {
.then(repliedMessage => { repliedMessage.reply(fn.spongebob({ args: repliedMessage.content })).then(() => {
repliedMessage.reply(fn.spongebob({ args: commandData.args })).then(() => { // Use the pre-command text of the replying message to sb-ify if (message.deletable) message.delete();
if (message.deletable) message.delete(); // If the initiating message is deletable, delete it.
});
})
.catch(err => {
console.error(err);
}); });
} else { // We're working with a basic ".sb" and can proceed as we did before... })
const repliedMessageId = message.reference.messageId; // grab the message Id of the replied-to msg .catch(err => {
message.channel.messages.fetch(repliedMessageId) // Fetch the message because with our luck it isn't in the cache console.error(err);
.then(repliedMessage => { });
repliedMessage.reply(fn.spongebob({ args: repliedMessage.content })).then(() => { } else {
if (message.deletable) message.delete();
});
})
.catch(err => {
console.error(err);
});
}
} else { // The message isn't a reply, so just sb it like we did from the very beginning
message.channel.send(fn.spongebob(commandData)).then(() => { message.channel.send(fn.spongebob(commandData)).then(() => {
if (message.deletable) message.delete(); // If the initiating message is deletable, delete it. if (message.deletable) message.delete();
}); });
} }
} }

View File

@ -22,8 +22,20 @@ const Discord = require('discord.js');
const FuzzySearch = require('fuzzy-search'); const FuzzySearch = require('fuzzy-search');
// OpenAI // OpenAI
// const OpenAI = require("openai"); const { Configuration, OpenAIApi } = require("openai");
// const openai = new OpenAI();
const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
async function openAIStatus(o) {
const response = await o.listModels();
const models = response.data.data;
models.forEach(e => {
console.log(`Model ID: ${e.id}`);
});
};
openAIStatus(openai);
// Various imports from other files // Various imports from other files
const config = require('./config.json'); const config = require('./config.json');
@ -33,7 +45,6 @@ const dotCommandFiles = fs.readdirSync('./dot-commands/').filter(file => file.en
// MySQL database connection // MySQL database connection
const mysql = require('mysql'); const mysql = require('mysql');
const { GifData, PastaData } = require('./CustomModules/NodBot');
const db = new mysql.createPool({ const db = new mysql.createPool({
connectionLimit: 10, connectionLimit: 10,
host: dbHost, host: dbHost,
@ -91,13 +102,12 @@ const functions = {
if (!client.gifs) client.gifs = new Discord.Collection(); if (!client.gifs) client.gifs = new Discord.Collection();
client.gifs.clear(); client.gifs.clear();
for (const row of rows) { for (const row of rows) {
// const gif = { const gif = {
// id: row.id, id: row.id,
// name: row.name, name: row.name,
// embed_url: row.embed_url embed_url: row.embed_url
// }; };
const gifData = new GifData().setInfo(row.name, row.embed_url); client.gifs.set(gif.name, gif);
client.gifs.set(gifData.name, gifData);
} }
if (isDev) console.log('GIFs Collection Built'); if (isDev) console.log('GIFs Collection Built');
}, },
@ -117,8 +127,13 @@ const functions = {
if (!client.pastas) client.pastas = new Discord.Collection(); if (!client.pastas) client.pastas = new Discord.Collection();
client.pastas.clear(); client.pastas.clear();
for (const row of rows) { for (const row of rows) {
const pastaData = new PastaData().setInfo(row.name, row.content, row.iconurl, row.id); const pasta = {
client.pastas.set(pastaData.name, pastaData); id: row.id,
name: row.name,
content: row.content,
iconUrl: row.iconurl,
};
client.pastas.set(pasta.name, pasta);
} }
if (isDev) console.log('Pastas Collection Built'); if (isDev) console.log('Pastas Collection Built');
}, },
@ -149,7 +164,7 @@ const functions = {
if (isDev) console.log('Strains Collection Built'); if (isDev) console.log('Strains Collection Built');
}, },
medicalAdvice(rows, client) { medicalAdvice(rows, client) {
if (!client.medicalAdviceColl) client.medicalAdviceColl = new Discord.Collection(); if (!client.medicalAdviceCol) client.medicalAdviceColl = new Discord.Collection();
client.medicalAdviceColl.clear(); client.medicalAdviceColl.clear();
for (const row of rows) { for (const row of rows) {
const medicalAdvice = { const medicalAdvice = {
@ -160,18 +175,13 @@ const functions = {
} }
if (isDev) console.log('Medical Advice Collection Built'); if (isDev) console.log('Medical Advice Collection Built');
}, },
roaches(client) {
if (!client.roaches) client.roaches = new Discord.Collection();
client.roaches.clear();
if (isDev) console.log('Medical Advice Collection Built');
}
}, },
dot: { dot: {
getCommandData(message) { getCommandData(message) {
const commandData = {}; const commandData = {};
// Split the message content at the final instance of a period // Split the message content at the final instance of a period
const finalPeriod = message.content.lastIndexOf('.'); const finalPeriod = message.content.lastIndexOf('.');
// if(isDev) console.log(message.content); if(isDev) console.log(message.content);
// If the final period is the last character, or doesn't exist // If the final period is the last character, or doesn't exist
if (finalPeriod < 0) { if (finalPeriod < 0) {
if (isDev) console.log(finalPeriod); if (isDev) console.log(finalPeriod);
@ -182,8 +192,8 @@ const functions = {
// Get the first part of the message, everything leading up to the final period // Get the first part of the message, everything leading up to the final period
commandData.args = message.content.slice(0,finalPeriod).toLowerCase(); commandData.args = message.content.slice(0,finalPeriod).toLowerCase();
// Get the last part of the message, everything after the final period // Get the last part of the message, everything after the final period
commandData.command = message.content.slice(finalPeriod + 1).toLowerCase(); commandData.command = message.content.slice(finalPeriod).replace('.','').toLowerCase();
commandData.author = `${message.author.username}`; commandData.author = `${message.author.username}#${message.author.discriminator}`;
return this.checkCommand(commandData); return this.checkCommand(commandData);
}, },
checkCommand(commandData) { checkCommand(commandData) {
@ -205,7 +215,7 @@ const functions = {
// Construct the Help Embed // Construct the Help Embed
const helpEmbed = new Discord.MessageEmbed() const helpEmbed = new Discord.MessageEmbed()
.setColor('BLUE') .setColor('BLUE')
.setAuthor({name: 'Help Page'}) .setAuthor('Help Page')
.setDescription(strings.help.description) .setDescription(strings.help.description)
.setThumbnail(strings.urls.avatar); .setThumbnail(strings.urls.avatar);
@ -258,25 +268,25 @@ const functions = {
}, },
gif(commandData) { gif(commandData) {
return { embeds: [new Discord.MessageEmbed() return { embeds: [new Discord.MessageEmbed()
.setAuthor({name: `${commandData.args}.${commandData.command}`}) .setAuthor(`${commandData.args}.${commandData.command}`)
.setImage(commandData.embed_url) .setImage(commandData.embed_url)
.setTimestamp() .setTimestamp()
.setFooter({text: commandData.author})]}; .setFooter(commandData.author)]};
}, },
pasta(commandData, pastaData) { pasta(commandData) {
return { embeds: [ new Discord.MessageEmbed() return { embeds: [ new Discord.MessageEmbed()
.setAuthor({name: `${commandData.args}.${commandData.command}`}) .setAuthor(`${commandData.args}.${commandData.command}`)
.setDescription(pastaData.content) .setDescription(commandData.content)
.setThumbnail("https://assets.vfsh.dev/shednod.png") .setThumbnail(commandData.iconUrl)
.setTimestamp() .setTimestamp()
.setFooter({text: commandData.author})]}; .setFooter(commandData.author)]};
}, },
pastas(commandData) { pastas(commandData) {
const pastasArray = []; const pastasArray = [];
const pastasEmbed = new Discord.MessageEmbed() const pastasEmbed = new Discord.MessageEmbed()
.setAuthor({name: commandData.command}) .setAuthor(commandData.command)
.setTimestamp() .setTimestamp()
.setFooter({text: commandData.author}); .setFooter(commandData.author);
for (const row of commandData.pastas) { for (const row of commandData.pastas) {
pastasArray.push(`#${row.id} - ${row.name}.pasta`); pastasArray.push(`#${row.id} - ${row.name}.pasta`);
@ -287,27 +297,34 @@ const functions = {
return { embeds: [pastasEmbed], ephemeral: true }; return { embeds: [pastasEmbed], ephemeral: true };
}, },
gifs(commandData, gifList) { gifs(commandData) {
const gifsArray = [];
const gifsEmbed = new Discord.MessageEmbed() const gifsEmbed = new Discord.MessageEmbed()
.setAuthor({name: commandData.command}) .setAuthor(commandData.command)
.setTimestamp() .setTimestamp()
.setFooter({text: commandData.author}) .setFooter(commandData.author);
.setDescription(gifList.join('\n'));
for (const row of commandData.gifs) {
gifsArray.push(`#${row.id} - ${row.name}.gif`);
}
const gifsString = gifsArray.join('\n');
gifsEmbed.setDescription(gifsString);
return { embeds: [gifsEmbed] }; return { embeds: [gifsEmbed] };
}, },
text(commandData) { text(commandData) {
return { embeds: [new Discord.MessageEmbed() return { embeds: [new Discord.MessageEmbed()
.setAuthor({name: commandData.command}) .setAuthor(commandData.command)
.setDescription(commandData.content) .setDescription(commandData.content)
.setTimestamp() .setTimestamp()
.setFooter({text: commandData.author})]}; .setFooter(commandData.author)]};
}, },
requests(commandData) { requests(commandData) {
const requestsEmbed = new Discord.MessageEmbed() const requestsEmbed = new Discord.MessageEmbed()
.setAuthor({name: commandData.command}) .setAuthor(commandData.command)
.setTimestamp() .setTimestamp()
.setFooter({text: commandData.author}); .setFooter(commandData.author);
const requestsArray = []; const requestsArray = [];
@ -372,9 +389,9 @@ const functions = {
}, },
gpt(prompt, response, usage) { gpt(prompt, response, usage) {
const gptEmbed = new Discord.MessageEmbed() const gptEmbed = new Discord.MessageEmbed()
.setAuthor({ name: "NodBot powered by GPT-3.5", iconURL: "https://assets.vfsh.dev/openai-logos/PNGs/openai-logomark.png" }) .setAuthor({ name: "NodBot powered by GPT-3", iconURL: "https://assets.vfsh.dev/openai-logos/PNGs/openai-logomark.png" })
.setDescription(`**Prompt**\n${prompt}\n\n**Response**\n${response}`) .setDescription(`**Prompt**\n${prompt}\n\n**Response**\n${response}`)
.setFooter({ text: `This prompt used ${usage.tokens} tokens for a cost of ${usage.usdc}¢. Generated using ${strings.ai.chatModel}` }) .setFooter({ text: `This prompt used ${usage.tokens} tokens for a cost of ${usage.usdc}¢` })
return { embeds: [gptEmbed] }; return { embeds: [gptEmbed] };
}, },
generatingResponse() { generatingResponse() {
@ -400,13 +417,12 @@ const functions = {
functions.download.requests(client); functions.download.requests(client);
}); });
}, },
async pasta(pastaData, client) { pasta(pastaData, client) {
const query = `INSERT INTO pastas (name, content) VALUES (${db.escape(pastaData.name)},${db.escape(pastaData.content)}) ON DUPLICATE KEY UPDATE content=${db.escape(pastaData.content)}`; const query = `INSERT INTO pastas (name, content) VALUES (${db.escape(pastaData.name)},${db.escape(pastaData.content)})`;
await db.query(query, (err, rows, fields) => { db.query(query, (err, rows, fields) => {
if (err) throw err; if (err) throw err;
functions.download.pastas(client); functions.download.pastas(client);
}); });
return;
}, },
joint(content, client) { joint(content, client) {
const query = `INSERT INTO joints (content) VALUES (${db.escape(content)})`; const query = `INSERT INTO joints (content) VALUES (${db.escape(content)})`;
@ -415,9 +431,9 @@ const functions = {
functions.download.joints(client); functions.download.joints(client);
}); });
}, },
async gif(gifData, client) { gif(gifData, client) {
const query = `INSERT INTO gifs (name, embed_url) VALUES (${db.escape(gifData.name)}, ${db.escape(gifData.url)}) ON DUPLICATE KEY UPDATE embed_url=${db.escape(gifData.url)}`; const query = `INSERT INTO gifs (name, embed_url) VALUES (${db.escape(gifData.name)}, ${db.escape(gifData.embed_url)})`;
await db.query(query, (err, rows, fields) => { db.query(query, (err, rows, fields) => {
if (err) throw err; if (err) throw err;
functions.download.gifs(client); functions.download.gifs(client);
}); });
@ -471,7 +487,7 @@ const functions = {
const description = db.escape(( interaction.options.getString('description') || 'Unknown' )); const description = db.escape(( interaction.options.getString('description') || 'Unknown' ));
const flavor = db.escape(( interaction.options.getString('flavor') || 'Unknown' )); const flavor = db.escape(( interaction.options.getString('flavor') || 'Unknown' ));
const rating = db.escape(( interaction.options.getString('rating') || '3' )); const rating = db.escape(( interaction.options.getString('rating') || '3' ));
const strainQuery = `INSERT INTO strains (strain, type, effects, description, flavor, rating) VALUES (${strain}, ${type}, ${effects}, ${description}, ${flavor}, ${rating}) ON DUPLICATE KEY UPDATE strain=${db.escape(strain)}, type=${db.escape(type)}, effects=${db.escape(effects)}, description=${db.escape(description)}, flavor=${db.escape(flavor)}, rating=${db.escape(rating)}`; const strainQuery = `INSERT INTO strains (strain, type, effects, description, flavor, rating) VALUES (${strain}, ${type}, ${effects}, ${description}, ${flavor}, ${rating})`;
console.log(strainQuery); console.log(strainQuery);
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
db.query(strainQuery, (err, rows, fields) => { db.query(strainQuery, (err, rows, fields) => {
@ -503,9 +519,9 @@ const functions = {
functions.collections.pastas(rows, client); functions.collections.pastas(rows, client);
}); });
}, },
async gifs(client) { gifs(client) {
const query = 'SELECT * FROM gifs ORDER BY id ASC'; const query = 'SELECT * FROM gifs ORDER BY id ASC';
await db.query(query, (err, rows, fields) => { db.query(query, (err, rows, fields) => {
if (err) throw err; if (err) throw err;
functions.collections.gifs(rows, client); functions.collections.gifs(rows, client);
}); });
@ -564,17 +580,16 @@ const functions = {
openAI: { openAI: {
chatPrompt(userPrompt) { chatPrompt(userPrompt) {
return new Promise(async (resolve, reject) => { return new Promise(async (resolve, reject) => {
const response = await openai.chat.completions.create({ const response = await openai.createCompletion({
messages: [{ model: 'text-davinci-003',
role: 'user', prompt: userPrompt,
content: userPrompt temperature: 0.7,
}], max_tokens: 250
model: strings.ai.chatModel
}).catch(e => { }).catch(e => {
reject(e); reject(e);
return null; return null;
}); });
resolve(response); resolve(response.data);
}); });
}, },
imagePrompt(userPrompt, size, userId) { imagePrompt(userPrompt, size, userId) {
@ -593,16 +608,6 @@ const functions = {
}); });
} }
}, },
search: {
gifs(query, client) {
const gifSearcher = new FuzzySearch(client.gifs.map(element => element.name));
return gifSearcher.search(query).slice(0,25);
},
pastas(query, client) {
const pastaSearcher = new FuzzySearch(client.pastas.map(element => element.name));
return pastaSearcher.search(query).slice(0,25);
}
},
// Parent-Level functions (miscellaneuous) // Parent-Level functions (miscellaneuous)
closeRequest(requestId, interaction) { closeRequest(requestId, interaction) {
if (interaction.user.id == ownerId) { if (interaction.user.id == ownerId) {
@ -622,7 +627,6 @@ const functions = {
}, },
spongebob(commandData) { spongebob(commandData) {
let newText = ''; let newText = '';
let lastIsUpper = 0;
for (const letter of commandData.args) { for (const letter of commandData.args) {
if (letter == ' ') { if (letter == ' ') {
newText += letter; newText += letter;
@ -630,85 +634,21 @@ const functions = {
} }
if (letter == 'i' || letter == 'I') { if (letter == 'i' || letter == 'I') {
newText += 'i'; newText += 'i';
lastIsUpper = 0;
continue; continue;
} }
if (letter == 'l' || letter == 'L') { if (letter == 'l' || letter == 'L') {
newText += 'L'; newText += 'L';
lastIsUpper = 1;
continue; continue;
} }
if (lastIsUpper === 0) { if (Math.random() > 0.5) {
newText += letter.toUpperCase(); newText += letter.toUpperCase();
lastIsUpper = 1;
} else { } else {
newText += letter.toLowerCase(); newText += letter.toLowerCase();
lastIsUpper = 0;
} }
} }
return newText + ' <:spongebob:1053398825965985822>'; return newText + ' <:spongebob:1053398825965985822>';
}, },
autoresponses: { // Specific responses for certain keywords in sent messages
checkForAll(messageContent) {
let responses = [];
if (this.bigDoinks(messageContent)) responses.push("bigDoinks");
if (this.ligma(messageContent)) responses.push("ligma");
if (this.ong(messageContent)) responses.push("ong");
if (this.fuckYou(messageContent)) responses.push("fuckYou");
return responses;
},
bigDoinks(messageContent) {
let count = 0;
const { keywords } = strings.autoresponses.bigDoinks;
keywords.forEach(e => {
if (messageContent.includes(e)) count++;
});
if (count === keywords.length) {
return true;
}
},
ligma(messageContent) {
let count = 0;
const { keywords } = strings.autoresponses.ligma;
keywords.forEach(e => {
if (messageContent.includes(e)) count++;
});
if (count > 0) {
return true;
}
},
ong(messageContent) {
let count = 0;
const { keywords } = strings.autoresponses.ong;
keywords.forEach(e => {
if (messageContent.includes(e)) count++;
});
if (count > 0) {
return true;
}
},
fuckYou(messageContent) {
let count = 0;
const { keywords } = strings.autoresponses.fuckYou;
keywords.forEach(e => {
if (messageContent.includes(e)) count++;
});
if (count === keywords.length) {
return true;
}
},
send(message, responseType) {
const { responses } = strings.autoresponses[responseType];
const randomIndex = Math.floor(Math.random() * responses.length);
const response = responses[randomIndex];
try {
message.reply(response);
} catch(e) {
console.log(new Error(e));
}
}
},
generateErrorId() { generateErrorId() {
const digitCount = 10; const digitCount = 10;
const digits = []; const digits = [];

64
main.js
View File

@ -27,14 +27,12 @@ const { MessageActionRow, MessageButton } = require('discord.js');
const fn = require('./functions.js'); const fn = require('./functions.js');
const config = require('./config.json'); const config = require('./config.json');
const strings = require('./strings.json'); const strings = require('./strings.json');
const { GifData } = require('./CustomModules/NodBot.js');
const isDev = process.env.isDev; const isDev = process.env.isDev;
client.once('ready', () => { client.once('ready', () => {
fn.collections.slashCommands(client); fn.collections.slashCommands(client);
fn.collections.dotCommands(client); fn.collections.dotCommands(client);
fn.collections.setvalidCommands(client); fn.collections.setvalidCommands(client);
fn.collections.roaches(client);
fn.download.gifs(client); fn.download.gifs(client);
fn.download.pastas(client); fn.download.pastas(client);
fn.download.joints(client); fn.download.joints(client);
@ -110,11 +108,10 @@ client.on('interactionCreate', async interaction => {
interaction.update(strings.temp.gifs[newIndex].embed_url); interaction.update(strings.temp.gifs[newIndex].embed_url);
break; break;
case 'confirmGif': case 'confirmGif':
// const gifData = { const gifData = {
// name: strings.temp.gifName, name: strings.temp.gifName,
// url: strings.temp.gifs[strings.temp.gifIndex].embed_url, embed_url: strings.temp.gifs[strings.temp.gifIndex].embed_url,
// }; };
const gifData = new GifData().setInfo(strings.temp.gifName, strings.temp.gifs[strings.temp.gifIndex].embed_url);
fn.upload.gif(gifData, client); fn.upload.gif(gifData, client);
interaction.update({ content: `I've saved the GIF as ${gifData.name}.gif`, components: [] }); interaction.update({ content: `I've saved the GIF as ${gifData.name}.gif`, components: [] });
fn.download.gifs(interaction.client); fn.download.gifs(interaction.client);
@ -179,39 +176,14 @@ client.on('interactionCreate', async interaction => {
// Handle autocomplete requests // Handle autocomplete requests
if (interaction.isAutocomplete()) { if (interaction.isAutocomplete()) {
switch (interaction.commandName) { if (interaction.commandName == 'strain') {
case 'strain': const searchString = interaction.options.getFocused();
const searchString = interaction.options.getFocused(); const choices = fn.weed.strain.lookup(searchString, interaction.client);
const choices = fn.weed.strain.lookup(searchString, interaction.client); await interaction.respond(
await interaction.respond( choices.map(choice => ({ name: choice, value: choice }))
choices.map(choice => ({ name: choice, value: choice })) )
); } else {
break; return;
case "edit":
//TODO
switch (interaction.options.getSubcommand()) {
case 'gif':
const gifQuery = interaction.options.getFocused();
const gifChoices = fn.search.gifs(gifQuery, interaction.client);
await interaction.respond(
gifChoices.map(choice => ({ name: choice, value: choice }))
);
break;
case 'pasta':
const pastaQuery = interaction.options.getFocused();
const pastaChoices = fn.search.pastas(pastaQuery, interaction.client);
await interaction.respond(
pastaChoices.map(choice => ({ name: choice, value: choice }))
);
break;
default:
break;
}
break;
default:
break;
} }
} }
}); });
@ -221,12 +193,14 @@ client.on('messageCreate', message => {
// Some basic checking to prevent running unnecessary code // Some basic checking to prevent running unnecessary code
if (message.author.bot) return; if (message.author.bot) return;
// Automatic Responses, will respond if any message contains the keyword(s), excluding self-messages // Wildcard Responses, will respond if any message contains the trigger word(s), excluding self-messages
const lowerContent = message.content.toLowerCase(); const lowerContent = message.content.toLowerCase();
const autoresponses = fn.autoresponses.checkForAll(lowerContent); if (lowerContent.includes('big') && lowerContent.includes('doinks')) message.reply('gang.');
autoresponses.forEach(e => { if (lowerContent.includes('ligma')) message.reply('ligma balls, goteem');
fn.autoresponses.send(message, e); if (lowerContent.includes('frfr') || lowerContent.includes('fr fr') || lowerContent.includes('bussin') || lowerContent.includes(' ong') || lowerContent.startsWith('ong')) {
}); const randIndex = Math.floor(Math.random() * strings.capbacks.length);
message.reply(strings.capbacks[randIndex]);
}
// Break the message down into its components and analyze it // Break the message down into its components and analyze it
const commandData = fn.dot.getCommandData(message); const commandData = fn.dot.getCommandData(message);

View File

@ -1,6 +1,6 @@
{ {
"name": "nodbot", "name": "nodbot",
"version": "3.2.3", "version": "3.2.0",
"description": "Nods and Nod Accessories, now with ChatGPT!", "description": "Nods and Nod Accessories, now with ChatGPT!",
"main": "main.js", "main": "main.js",
"dependencies": { "dependencies": {
@ -12,7 +12,7 @@
"dotenv": "^10.0.0", "dotenv": "^10.0.0",
"fuzzy-search": "^3.2.1", "fuzzy-search": "^3.2.1",
"mysql": "^2.18.1", "mysql": "^2.18.1",
"openai": "^4.12.0", "openai": "^3.2.1",
"tenorjs": "^1.0.10" "tenorjs": "^1.0.10"
}, },
"engines": { "engines": {

27
slash-commands/chat.js Normal file
View File

@ -0,0 +1,27 @@
const { SlashCommandBuilder } = require('@discordjs/builders');
const fn = require('../functions.js');
module.exports = {
data: new SlashCommandBuilder()
.setName('chat')
.setDescription('Send a message to ChatGPT')
.addStringOption(o =>
o.setName("prompt")
.setDescription("Prompt to send to ChatGPT")
.setRequired(true)
),
async execute(interaction) {
await interaction.deferReply();
await interaction.editReply(fn.embeds.generatingResponse());
const userPrompt = interaction.options.getString("prompt");
const response = await fn.openAI.chatPrompt(userPrompt).catch(e => console.error(e));
const responseText = response.choices[0].text;
const usage = {
tokens: response.usage.total_tokens,
usdc: response.usage.total_tokens * ( 0.2 / 1000 ) // 0.2¢ per 1000 tokens or 0.0002¢ per token.
};
const gptEmbed = fn.embeds.gpt(userPrompt, responseText, usage);
await interaction.editReply(gptEmbed);
fn.upload.openai(interaction.user.id, userPrompt, "gpt-3.5-turbo", usage.tokens, usage.usdc);
},
};

40
slash-commands/dalle.js Normal file
View File

@ -0,0 +1,40 @@
const { SlashCommandBuilder } = require('@discordjs/builders');
const fn = require('../functions.js');
const strings = require("../strings.json");
module.exports = {
data: new SlashCommandBuilder()
.setName('dalle')
.setDescription('Generate an image with DALL-e')
.addStringOption(o =>
o.setName("prompt")
.setDescription("Prompt to send to DALL-e")
.setRequired(true)
)
.addStringOption(o =>
o.setName("size")
.setDescription("1024x1024, 512x512, 256x256")
.setRequired(false)
.addChoices(
{ name: "1024x1024 (2¢)", value: "1024x1024" },
{ name: "512x512 (1.8¢)", value: "512x512" },
{ name: "256x256 (1.6¢)", value: "256x256" }
)),
async execute(interaction) {
try {
await interaction.deferReply();
await interaction.editReply(fn.embeds.generatingResponse());
const userPrompt = interaction.options.getString("prompt");
const size = interaction.options.getString("size") ? interaction.options.getString("size") : "512x512";
const imageUrl = await fn.openAI.imagePrompt(userPrompt, size);
const dalleEmbed = fn.embeds.dalle(userPrompt, imageUrl, size);
await interaction.editReply(dalleEmbed);
fn.upload.openai(interaction.user.id, userPrompt, "dalle", 0, strings.costs.dalle[size]);
} catch (err) {
const errorId = fn.generateErrorId();
console.error(`${errorId}: ${err}`);
await interaction.editReply(`An error has occured. Error ID: ${errorId}\n${err}`);
}
},
};

View File

@ -1,110 +0,0 @@
const tenor = require('tenorjs').client({
'Key': process.env.tenorAPIKey, // https://tenor.com/developer/keyregistration
'Filter': 'off', // "off", "low", "medium", "high", not case sensitive
'Locale': 'en_US',
'MediaFilter': 'minimal',
'DateFormat': 'D/MM/YYYY - H:mm:ss A',
});
const { SlashCommandBuilder } = require('@discordjs/builders');
const { MessageActionRow, MessageButton } = require('discord.js');
const { GifData, PastaData } = require('../CustomModules/NodBot');
const fn = require('../functions.js');
const strings = require('../strings.json');
const { emoji } = strings;
module.exports = {
data: new SlashCommandBuilder()
.setName('edit')
.setDescription('Edit content in Nodbot\'s database.')
// GIF
.addSubcommand(subcommand =>
subcommand
.setName('gif')
.setDescription('Edit a GIF URL')
.addStringOption(option =>
option
.setName('name')
.setDescription('The name of the GIF to edit')
.setRequired(true)
.setAutocomplete(true)
)
.addStringOption(option =>
option
.setName('url')
.setDescription('The new URL')
.setRequired(true)
)
)
// Pasta
.addSubcommand(subcommand =>
subcommand
.setName('pasta')
.setDescription('Edit a copypasta\'s content')
.addStringOption(option =>
option
.setName('name')
.setDescription('The name of the copypasta')
.setRequired(true)
.setAutocomplete(true)
)
.addStringOption(option =>
option
.setName('content')
.setDescription('The new content of the copypasta')
.setRequired(true)
)
),
async execute(interaction) {
await interaction.deferReply({ ephemeral: true });
try {
// Code Here...
const subcommand = interaction.options.getSubcommand();
switch (subcommand) {
// GIF
case "gif":
//TODO
await this.editGif(interaction, interaction.options.getString('name'), interaction.options.getString('url'));
break;
// Joint
case "joint":
//TODO
break;
// MD
case "md":
//TODO
break;
// Pasta
case "pasta":
//TODO
await this.editPasta(interaction, interaction.options.getString('name'), interaction.options.getString('content'));
break;
// Strain
case "strain":
//TODO
break;
break;
// Default
default:
break;
}
} catch (err) {
const errorId = fn.generateErrorId();
console.error(`${errorId}: err`);
await interaction.editReply(`Sorry, an error has occured. Error ID: ${errorId}`);
}
},
async editGif(interaction, name, url) {
const gifData = new GifData().setInfo(name, url);
await fn.upload.gif(gifData, interaction.client);
await fn.download.gifs(interaction.client);
await interaction.editReply(`I've updated ${gifData.name}.gif`);
},
async editPasta(interaction, name, content) {
const pastaData = new PastaData().setInfo(name, content);
await fn.upload.pasta(pastaData, interaction.client);
await fn.download.gifs(interaction.client);
await interaction.editReply(`I've updated ${name}.pasta`);
}
};

View File

@ -11,26 +11,23 @@ module.exports = {
interaction.reply('For some reason I don\'t have access to the collection of gifs. Sorry about that!'); interaction.reply('For some reason I don\'t have access to the collection of gifs. Sorry about that!');
return; return;
} }
// const gifsMap = interaction.client.gifs.map(e => {e.name, e.url}); const gifsMap = interaction.client.gifs.map(e => {
// const commandData = { return {
// gifs: [], id: e.id,
// command: 'gifs', name: e.name,
// author: interaction.user.tag, };
// };
// for (const row of gifsMap) {
// commandData.gifs.push({
// id: row.id,
// name: row.name,
// });
// }
let gifList = [];
interaction.client.gifs.forEach(element => {
gifList.push(`[${element.name}](${element.url})`);
}); });
const commandData = { const commandData = {
command: "/gifs", gifs: [],
author: interaction.member.displayName command: 'gifs',
author: interaction.user.tag,
}; };
interaction.reply(fn.embeds.gifs(commandData, gifList)); for (const row of gifsMap) {
commandData.gifs.push({
id: row.id,
name: row.name,
});
}
interaction.reply(fn.embeds.gifs(commandData));
}, },
}; };

View File

@ -1,240 +0,0 @@
const tenor = require('tenorjs').client({
'Key': process.env.tenorAPIKey, // https://tenor.com/developer/keyregistration
'Filter': 'off', // "off", "low", "medium", "high", not case sensitive
'Locale': 'en_US',
'MediaFilter': 'minimal',
'DateFormat': 'D/MM/YYYY - H:mm:ss A',
});
const { SlashCommandBuilder } = require('@discordjs/builders');
const { MessageActionRow, MessageButton } = require('discord.js');
const fn = require('../functions.js');
const strings = require('../strings.json');
const { GifData } = require('../CustomModules/NodBot.js');
const { emoji } = strings;
module.exports = {
data: new SlashCommandBuilder()
.setName('save')
.setDescription('Save content to Nodbot\'s database.')
// GIF Search
.addSubcommand(subcommand =>
subcommand
.setName('gifsearch')
.setDescription('Search Tenor for a GIF.')
.addStringOption(option =>
option
.setName('query')
.setDescription('Search Query')
.setRequired(true))
.addStringOption(option =>
option
.setName('name')
.setDescription('What to save the gif as')
.setRequired(true))
)
// GIF URL
.addSubcommand(subcommand =>
subcommand
.setName('gifurl')
.setDescription('Specify a URL to save.')
.addStringOption(option =>
option
.setName('url')
.setDescription('URL Link to the GIF')
.setRequired(true))
.addStringOption(option =>
option
.setName('name')
.setDescription('What to save the gif as')
.setRequired(true))
)
// Joint
.addSubcommand(subcommand =>
subcommand
.setName('joint')
.setDescription('Roll a joint and stash it in the database.')
.addStringOption(option =>
option
.setName('joint-content')
.setDescription('Phrase to save')
.setRequired(true)
)
)
// MD
.addSubcommand(subcommand =>
subcommand
.setName('md')
.setDescription('Add medical advice to the database.')
.addStringOption(option =>
option
.setName('advice-content')
.setDescription('Advice to save')
.setRequired(true)
)
)
// Pasta
.addSubcommand(subcommand =>
subcommand
.setName('pasta')
.setDescription('Save a copypasta to the database.')
.addStringOption(option =>
option
.setName('pasta-name')
.setDescription('Title of the copypasta')
.setRequired(true)
)
.addStringOption(option =>
option
.setName('pasta-content')
.setDescription('Content of the copypasta')
.setRequired(true)
)
)
// Strain
.addSubcommand(subcommand =>
subcommand
.setName('strain')
.setDescription('Store a new Strain in the database!')
.addStringOption(option =>
option
.setName('name')
.setDescription('Name of the Strain')
.setRequired(true))
.addStringOption(option =>
option
.setName('type')
.setDescription('Indica/Sativa/Hybrid')
.setRequired(true)
.addChoices(
{ name: "Indica", value: "Indica" },
{ name: "Hybrid", value: "Hybrid" },
{ name: "Sativa", value: "Sativa" }
)
)
.addStringOption(option =>
option
.setName('effects')
.setDescription('The effects given by the strain')
.setRequired(false))
.addStringOption(option =>
option
.setName('flavor')
.setDescription('Flavor notes')
.setRequired(false))
.addStringOption(option =>
option
.setName('rating')
.setDescription('Number of stars')
.setRequired(false))
.addStringOption(option =>
option
.setName('description')
.setDescription('Description of the strain')
.setRequired(false))
),
async execute(interaction) {
await interaction.deferReply({ ephemeral: true });
try {
// Code Here...
const subcommand = interaction.options.getSubcommand();
switch (subcommand) {
// GIF Search
case "gifsearch":
// TODO Check on option names
// Previous GIF button
const prevButton = new MessageButton().setCustomId('prevGif').setLabel('Previous GIF').setStyle('SECONDARY').setDisabled(true);
// Confirm GIF Button
const confirmButton = new MessageButton().setCustomId('confirmGif').setLabel('Confirm').setStyle('PRIMARY');
// Next GIF Button
const nextButton = new MessageButton().setCustomId('nextGif').setLabel('Next GIF').setStyle('SECONDARY');
// Cancel Button
const cancelButton = new MessageButton().setCustomId('cancelGif').setLabel('Cancel').setStyle('DANGER');
// Put all the above into an ActionRow to be sent as a component of the reply
const actionRow = new MessageActionRow().addComponents(prevButton, confirmButton, nextButton, cancelButton);
// Get the query
const query = interaction.options.getString('query');
strings.temp.gifName = interaction.options.getString('name').toLowerCase();
// Search Tenor for the GIF
tenor.Search.Query(query, '10').then(res => {
strings.temp.gifs = [];
strings.temp.gifIndex = 0;
strings.temp.gifLimit = res.length - 1;
strings.temp.gifUserId = interaction.user.id;
if (res[0] == undefined) {
interaction.editReply('Sorry I was unable to find a GIF of ' + query);
return;
}
for (const row of res) {
strings.temp.gifs.push({
embed_url: row.media_formats.gif.url,
});
}
interaction.editReply({ content: strings.temp.gifs[0].embed_url, components: [actionRow], ephemeral: true });
});
break;
// GIF URL
case "gifurl":
//TODO Check on option names
// const gifData = {
// name: interaction.options.getString('name').toLowerCase(),
// url: interaction.options.getString('url'),
// };
const gifData = new GifData().setInfo(interaction.options.getString('name').toLowerCase(), interaction.options.getString('url'));
fn.upload.gif(gifData, interaction.client);
interaction.editReply({ content: `I've saved the GIF as ${gifData.name}.gif`, ephemeral: true });
fn.download.gifs(interaction.client);
break;
// Joint
case "joint":
//TODO
fn.upload.joint(interaction.options.getString('joint-content'), interaction.client);
interaction.editReply({ content: `The joint has been rolled${emoji.joint}`, ephemeral: true });
break;
// MD
case "md":
//TODO
fn.upload.medicalAdvice(interaction.options.getString('advice-content'), interaction.client);
interaction.editReply({ content: `The advice has been saved!`, ephemeral: true });
break;
// Pasta
case "pasta":
//TODO
const pastaData = {
name: interaction.options.getString('pasta-name').toLowerCase(),
content: interaction.options.getString('pasta-content'),
};
await fn.upload.pasta(pastaData, interaction.client);
interaction.editReply({content: `The copypasta has been saved as ${pastaData.name}.pasta`, ephemeral: true });
break;
// Strain
case "strain":
//TODO
fn.upload.strain(interaction).then(res => {
interaction.editReply({
content: `The strain information has been saved. (${interaction.options.getString('name')})`,
ephemeral: true
});
}).catch(err => {
console.log(`E: ${err}`);
interaction.editReply({
content: 'There was a problem saving the strain.',
ephemeral: true
});
});
break;
// Default
default:
break;
}
} catch (err) {
const errorId = fn.generateErrorId();
console.error(`${errorId}: err`);
await interaction.editReply(`Sorry, an error has occured. Error ID: ${errorId}`);
}
}
};

93
slash-commands/savegif.js Normal file
View File

@ -0,0 +1,93 @@
const tenor = require('tenorjs').client({
'Key': process.env.tenorAPIKey, // https://tenor.com/developer/keyregistration
'Filter': 'off', // "off", "low", "medium", "high", not case sensitive
'Locale': 'en_US',
'MediaFilter': 'minimal',
'DateFormat': 'D/MM/YYYY - H:mm:ss A',
});
const { SlashCommandBuilder } = require('@discordjs/builders');
const { MessageActionRow, MessageButton } = require('discord.js');
const fn = require('../functions.js');
const strings = require('../strings.json');
module.exports = {
data: new SlashCommandBuilder()
.setName('savegif')
.setDescription('Save a GIF to Nodbot\'s database.')
.addSubcommand(subcommand =>
subcommand
.setName('searchgif')
.setDescription('Search Tenor for a GIF.')
.addStringOption(option =>
option.setName('query')
.setDescription('Search Query')
.setRequired(true))
.addStringOption(option =>
option.setName('name')
.setDescription('What to save the gif as')
.setRequired(true))
)
.addSubcommand(subcommand =>
subcommand
.setName('enterurl')
.setDescription('Specify a URL to save.')
.addStringOption(option =>
option
.setName('url')
.setDescription('URL Link to the GIF')
.setRequired(true))
.addStringOption(option =>
option.setName('name')
.setDescription('What to save the gif as')
.setRequired(true))
),
async execute(interaction) {
if (interaction.options.getSubcommand() == 'searchgif') {
// Previous GIF button
const prevButton = new MessageButton().setCustomId('prevGif').setLabel('Previous GIF').setStyle('SECONDARY').setDisabled(true);
// Confirm GIF Button
const confirmButton = new MessageButton().setCustomId('confirmGif').setLabel('Confirm').setStyle('PRIMARY');
// Next GIF Button
const nextButton = new MessageButton().setCustomId('nextGif').setLabel('Next GIF').setStyle('SECONDARY');
// Cancel Button
const cancelButton = new MessageButton().setCustomId('cancelGif').setLabel('Cancel').setStyle('DANGER');
// Put all the above into an ActionRow to be sent as a component of the reply
const actionRow = new MessageActionRow().addComponents(prevButton, confirmButton, nextButton, cancelButton);
// Get the query
const query = interaction.options.getString('query');
strings.temp.gifName = interaction.options.getString('name').toLowerCase();
// Search Tenor for the GIF
tenor.Search.Query(query, '10').then(res => {
strings.temp.gifs = [];
strings.temp.gifIndex = 0;
strings.temp.gifLimit = res.length - 1;
strings.temp.gifUserId = interaction.user.id;
if (res[0] == undefined) {
interaction.reply('Sorry I was unable to find a GIF of ' + query);
return;
}
for (const row of res) {
strings.temp.gifs.push({
embed_url: row.media[0].gif.url,
});
}
interaction.reply({ content: strings.temp.gifs[0].embed_url, components: [actionRow], ephemeral: true });
});
}
if (interaction.options.getSubcommand() == 'enterurl') {
const gifData = {
name: interaction.options.getString('name'),
embed_url: interaction.options.getString('url'),
};
fn.upload.gif(gifData, interaction.client);
interaction.reply({ content: `I've saved the GIF as ${gifData.name}.gif`, ephemeral: true });
fn.download.gifs(interaction.client);
}
},
};

View File

@ -0,0 +1,17 @@
const { SlashCommandBuilder } = require('@discordjs/builders');
const fn = require('../functions.js');
const { emoji } = require('../strings.json');
module.exports = {
data: new SlashCommandBuilder()
.setName('savejoint')
.setDescription('Save a phrase for /joint!')
.addStringOption(option =>
option.setName('joint-content')
.setDescription('What is the phrase?')
.setRequired(true)),
async execute(interaction) {
fn.upload.joint(interaction.options.getString('joint-content'), interaction.client);
interaction.reply({ content: `The joint has been rolled${emoji.joint}`, ephemeral: true });
},
};

17
slash-commands/savemd.js Normal file
View File

@ -0,0 +1,17 @@
const { SlashCommandBuilder } = require('@discordjs/builders');
const fn = require('../functions.js');
// const { emoji } = require('../strings.json');
module.exports = {
data: new SlashCommandBuilder()
.setName('savemd')
.setDescription('Add medical advice to NodBot\'s Database!')
.addStringOption(option =>
option.setName('advice-content')
.setDescription('What is the advice?')
.setRequired(true)),
async execute(interaction) {
fn.upload.medicalAdvice(interaction.options.getString('advice-content'), interaction.client);
interaction.reply({ content: `The advice has been saved!`, ephemeral: true });
},
};

View File

@ -0,0 +1,24 @@
const { SlashCommandBuilder } = require('@discordjs/builders');
const fn = require('../functions.js');
module.exports = {
data: new SlashCommandBuilder()
.setName('savepasta')
.setDescription('Save a copypasta!')
.addStringOption(option =>
option.setName('pasta-name')
.setDescription('What should the name of the copypasta be?')
.setRequired(true))
.addStringOption(option =>
option.setName('pasta-content')
.setDescription('What is the content of the copypasta?')
.setRequired(true)),
async execute(interaction) {
const pastaData = {
name: interaction.options.getString('pasta-name'),
content: interaction.options.getString('pasta-content'),
};
fn.upload.pasta(pastaData, interaction.client);
interaction.reply({content: `The copypasta has been saved as ${pastaData.name}.pasta`, ephemeral: true });
},
};

View File

@ -0,0 +1,54 @@
const { SlashCommandBuilder } = require('@discordjs/builders');
const fn = require('../functions.js');
const { emoji } = require('../strings.json');
// Strain Name | Type | Effects | Flavor | Rating | Description
module.exports = {
data: new SlashCommandBuilder()
.setName('savestrain')
.setDescription('Store a new Strain in the database!')
.addStringOption(option =>
option.setName('name')
.setDescription('Name of the Strain')
.setRequired(true))
.addStringOption(option =>
option.setName('type')
.setDescription('Indica/Sativa/Hybrid')
.setRequired(true)
.addChoices(
{ name: "Indica", value: "Indica" },
{ name: "Hybrid", value: "Hybrid" },
{ name: "Sativa", value: "Sativa" }
))
.addStringOption(option =>
option.setName('effects')
.setDescription('The effects given by the strain')
.setRequired(false))
.addStringOption(option =>
option.setName('flavor')
.setDescription('Flavor notes')
.setRequired(false))
.addStringOption(option =>
option.setName('rating')
.setDescription('Number of stars')
.setRequired(false))
.addStringOption(option =>
option.setName('description')
.setDescription('Description of the strain')
.setRequired(false)),
async execute(interaction) {
fn.upload.strain(interaction).then(res => {
interaction.reply({
content: `The strain information has been saved. (${interaction.options.getString('name')})`,
ephemeral: true
});
}).catch(err => {
console.log(`E: ${err}`);
interaction.reply({
content: 'There was a problem saving the strain.',
ephemeral: true
});
});
},
};

View File

@ -14,6 +14,14 @@
"urls": { "urls": {
"avatar": "https://cdn.discordapp.com/avatars/513184762073055252/12227aa23a06d5178853e59b72c7487b.webp?size=128" "avatar": "https://cdn.discordapp.com/avatars/513184762073055252/12227aa23a06d5178853e59b72c7487b.webp?size=128"
}, },
"capbacks": [
"on god?!",
"fr fr?!",
"no cap?!",
"no cap fr",
"bussin fr, no cap",
"ongggg no :billed_cap: fr fr"
],
"costs": { "costs": {
"gpt": { "gpt": {
"gpt-3.5-turbo": 0.2 "gpt-3.5-turbo": 0.2
@ -24,61 +32,5 @@
"1024x1024": 2.0 "1024x1024": 2.0
} }
}, },
"ai": {
"chatModel": "gpt-3.5-turbo",
"chatPromptCentsPer": 0.15,
"chatPromptUnits": 1000,
"chatResCentsPer": 0.2,
"chatResUnits": 1000
},
"autoresponses": {
"bigDoinks": {
"keywords": ["big", "doinks"],
"responses": [
"<:bigdoinks:1053706618853924905> Gang.",
"<:bigdoinks:1053706618853924905> Out here in Amish",
"<:bigdoinks:1053706618853924905> Out here in Amish, smoking Big Doinks in Amish... Gang."
]
},
"ligma": {
"keywords": ["ligma"],
"responses": [
"ligma balls lmao gottem",
"ligma balls ahaha",
"https://tenor.com/view/ligma-balls-gif-12236083",
"<:deadmonkey:1139186312444911707>"
]
},
"ong": {
"keywords": [
"frfr",
"fr fr",
"bussin",
"no cap",
" ong "
],
"responses": [
"on god?!",
"fr fr?!",
"no cap?!",
"no cap fr",
"bussin fr, no cap",
"ongggg no :billed_cap: fr fr"
]
},
"fuckYou": {
"keywords": [
"fuck",
"nodbot"
],
"responses": [
"no u",
"go fuck yourself",
"why does everyone hate me :sob:",
"<:kms:1253790048696926298>",
"Eat a bag of dicks"
]
}
},
"temp": {} "temp": {}
} }