Implement madlibs

master
Chloe Fontenot 🏳️‍⚧️ 2023-04-06 15:54:44 +07:00
parent 1f70cb9b1c
commit 91784d7d7d
8 changed files with 197 additions and 19 deletions

@ -0,0 +1,94 @@
const { SlashCommandBuilder, Discord, ActionRowBuilder, ButtonBuilder, ButtonStyle, Events, StringSelectMenuBuilder } = require('discord.js');
//const { madlibState } = require('../main.cjs');
//exports.madlibState = madlibState;
//let gameChannel = madlibState;
module.exports = {
data: new SlashCommandBuilder()
.setName('startmadlib')
.setDescription('Starts a madlib game in the current channel.'),
async execute(interaction, client) {
const row = new ActionRowBuilder()
.addComponents(
new ButtonBuilder()
.setCustomId('yes')
.setLabel('Yes')
.setStyle(ButtonStyle.Primary),
)
.addComponents(
new ButtonBuilder()
.setCustomId('no')
.setLabel('No')
.setStyle(ButtonStyle.Danger),
);
const message = await interaction.reply({ content: "You have requested to start a madlib game in the current channel. I will intercept any message sent in this channel as game input until the game is over. Please refrain from using this in a busy channel, as it can be annoying for others. Would you like to continue?", fetchReply: true, components: [row], allowedMentions: { repliedUser: false, } });
client.on(Events.InteractionCreate, interaction => {
if (!interaction.isButton()) return;
if (interaction.customId == 'yes') {
console.log("User selected yes");
if (interaction.channel.id != undefined) {
initGame(interaction.channel.id, client, interaction);
}
} else if (interaction.customId == 'no') {
console.log("User selected no");
if (interaction.channel.id != undefined) {
const channel = client.channels.cache.get(interaction.channel.id);
channel.send("Game aborted.");
}
}
message.delete();
});
console.log("User " + interaction.user.tag + " ran /startmadlib");
},
};
function initGame(channelId, client, interaction) {
if(global.madlibState.gameChannel == undefined) {
console.log("Starting game in channel " + channelId);
madlibState.gameChannel = channelId;
//let selectedStory =
selectStory(interaction);
//global.madlibNextPrompt(client, 0, selectedStory);
} else {
const channel = client.channels.cache.get(interaction.channel.id);
channel.send("There is currently an active game! Wait for it to be finished before starting a new one.");
}
}
async function selectStory(interaction) {
const row = new ActionRowBuilder()
.addComponents(
new StringSelectMenuBuilder()
.setCustomId('selectStory')
.setPlaceholder('Automatically pIck a random story')
.addOptions(
buildOptionJSON()
),
);
await interaction.reply({ content: 'Select a story', components: [row] });
client.on(Events.InteractionCreate, interaction => {
if (!interaction.isStringSelectMenu()) return;
console.log(interaction);
});
}
function buildOptionJSON() {
const madlib = require("../madlibs/stories.json");
let returnObj = [];
for (let i = 0; i < Object.keys(madlib.stories).length; ++i) {
let entryObj = {};
entryObj["label"] = Object.keys(madlib.stories)[i];
entryObj["description"] = "Story " + (i+1);
entryObj["value"] = i;
returnObj.push(entryObj);
}
return returnObj;
}
console.log(buildOptionJSON());
/*
{
label: 'Select me',
description: 'This is a description',
value: 'first_option',
},
*/

@ -8,7 +8,7 @@ const path = require('node:path');
const commands = [];
// Grab all the command files from the commands directory you created earlier
const commandsPath = path.join(__dirname, 'commands');
const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.ts'));
const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.cjs'));
// Grab the SlashCommandBuilder#toJSON() output of each command's data for deployment
for (const file of commandFiles) {

@ -0,0 +1,10 @@
{
"stories": {
"MadLib Gameshow": "<verb> on down! You're the next contestant on <celebrity>'s new gameshow, MadLib! Here's how it works. You will <verb> over a <noun> at a rate of <number> mph. After you jump over that item, you will <verb> over to the <adjective> <noun> and press the <noun> at the end. <adjective> time wins! Oh. I forgot to introduce our host. He's a <adjective> person who can't wait to <verb> in to the show. Please welcome, <proper name>! Alright players, on your mark. Get set. <silly word>! Alright, here goes <boy's name> on the first stage of the competition. And.. WOAH! He just <verb ending in ed> over the thing! That's gonna hurt him tommorow. But it'll be all worth it after he wins the grand prize of <number> dollars! Which he says will go towards <item you find at a store>. Very <adjective> investment, but it's his money! Here he comes around the second leg. AND WOAH, AGAIN HE LOOKS <adjective> ON NETWORK TELEVISION! This is what primetime is all about here on the network of <tv network>. And, he presses it! He finishes with a time of <time>. Will that be enough to win? Find out on <day of week> when <girl's name> will challenge him for the grand prize. For all of us here at MadLib, good night everyone!",
"Three Little Pigs": "Once upon a time, there were three <adjective> pigs. One day, their mother said, \"You are all grown up and must <verb> on your own.\" So they left to <verb> their houses. The first little pig wanted only to <verb> all day and quickly built his house out of <plural noun>. The second little pig wanted to <verb> and <verb> all day so he <past tense verb> his house with <plural noun>. The third <adjective> pig knew the wolf lived nearby and worked hard to <verb> his house out of <plural noun>. One day, the wolf knocked on the first pig's <noun>. \"Let me in or I'll <verb> your house down!\" The pig didn't, so the wolf <past tense verb> down the <noun>. The wolf knocked on the second pig's <noun>. \"Let me in or I'll blow your <noun> down!\" The pig didn't, so the wolf <past tense verb> down the house. Then the wolf knocked on the third <adjective> pig's door. \"Let me in or I'll blow your house down!\" The little pig didn't, so the wolf <past tense verb> and <past tense verb>.He could not blow the house down. All the pigs went to live in the <noun> house and they all <past tense verb> happily ever after.",
"AMC Cinemas Pre-Show Policy": "Thank you for choosing AMC Cinemas. Where we make movie moments AMC <adjective ending in ing>. Your safety is <adjective> to us, so remember, keep a <body part> on your valuables. Be sure to report any <adjective> behavior. And please take a moment to find any emergency exits near you. Make sure to stock up on <soda brand> and <food> at the concessions bar. Enjoy your movie, <movie title> and we thank you for choosing AMC Cinemas as your destination to watch that movie. Please, silence your <device> now and be quiet and courteous of your peers. And now, ladies and gentlemen, here are some special previews coming to an AMC near you.",
"NFL on What Channel?!": "The NFL is back! On our new home! Welcome to the most in-depth pregame show in all of pregame shows. This is the NFL on <tv network> brought to you by <food brand>! Hang tight and we'll be right back! Scene 2: Welcome in to Sunday on <same tv network>! My name is <celebrity>, and I am sitting alongside four celebrities, <celebrity>, <celebrity>, <celebrity>, and <celebrity>. Welcome guys. Week <number> is looking promising as we have three key games to focus on. First off, the <nfl team> take on the <nfl team>, our afternoon game, the <nfl team> vs the <nfl team>. Finally, our primetime game, the <nfl team> vs the <nfl team>. A lot of action today, and we will break that down soon in the <amount of time> coming. Before we do anything, let's take a live look inside <stadium> where the first key match will be playred, and we have our field reporter, <celebrity> who is covering our action. Scene 3: Alright, thank you. Now, it's time for kickoff of our first key game. We hope you enjoy the game and we will <verb> you at halftime.",
"Awards Show": "Welcome everyone to <famous city> and the <year> MadLib awards show. Here are the nominees for <random award show category>. First, <former president>. Next, <actor/actress>. And finally, <random silly name>. And the winner is... <one of the names you put>! <winner> could not be here tonight so he recorded a message for us to see. Take a look. Winner: Hello all. Thank you, the fans, for voting. I really appreciate it. I am sorry I couldn't be there.",
"Caleb wanted me to do a thing now it will commence": "Once upon a time in the land of <city>, there was a lovely little chap called <name>, but everyone just <verb ending in ed> to call him <silly word>. You see, he was the hero of the nearby city of <another city>, and that made the mayor of the city he lived in, <celebrity>, very unhappy. So, in an act of <noun>, he created his own <noun> army to take over the world. Now <same silly word> did not like this, so he <verb ending in ed> up to the main robot, which the mayor was in, and told him \"<phrase>\". The mayor, hearing those words, instantly surrendered and <verb>. He was then charged for 3 major acts of <noun>."
}
}

@ -1,9 +1,13 @@
"use strict";
// Require the necessary discord.js classes
const { Client, Events, GatewayIntentBits, REST, Routes, Collection, FLAGS, MessageMentionOptions, codeBlock, SlashCommandBuilder } = require('discord.js');
const Discord = require('discord.js');
const { clientId, guildId, token } = require('./key.json');
let fs = require('node:fs');
let path = require('node:path');
global.madlibState = { gameChannel: undefined, storyTitle:undefined, currentStory: undefined, storyIterate: 0, storyReplaceContent: [], storyLength: undefined};
//export {madlibState};
// Create a new client instance
const client = new Discord.Client({
@ -68,9 +72,10 @@ client.on(Events.InteractionCreate, async interaction => {
// My code
var abbreviationKey = require("./abbreviation_key.json");
const { start } = require('node:repl');
function arrayRotate(arr, reverse, amount) {
for (var i = 0; i < amount; i++) {
for (let i = 0; i < amount; i++) {
if (reverse) arr.unshift(arr.pop());
else arr.push(arr.shift());
return arr;
@ -105,23 +110,26 @@ function replyMessage(message, correctedMessage, abbrsUsed) {
if (stringLength > 2000) {
replyString = "Sorry, I detected " + plural + ", but the resultant response was " + stringLength + " characters long, and Discord only allows a maximum of 2000."
}
message.reply({content: replyString, allowedMentions: { repliedUser: false }});
message.reply({ content: replyString, allowedMentions: { repliedUser: false } });
}
client.on('messageCreate', message => {
if (global.madlibState.gameChannel == message.channel.id && message.author.id != "1091120267851485215") { // Pass message to madlib game handler if message was sent in the active game channel.
madlibNextMessage(message.content, client);
}
checkMessage(message);
checkInsult(message);
});
client.on('messageUpdate', (undefined, newMessage) => {
checkMessage(newMessage);
checkInsult(newMessage);
checkMessage(newMessage);
checkInsult(newMessage);
});
function checkMessage(message) {
if (message.content == "<@1091120267851485215>, what are your pronouns?") {
message.reply({content: "My pronouns are she/her ☺️", allowedMentions: { repliedUser: false }})
message.reply({ content: "My pronouns are she/her ☺️", allowedMentions: { repliedUser: false } })
}
console.log(`${message.author.tag} in #${message.channel.name} sent: ${message.content}`);
//console.log(message.author);
@ -213,4 +221,81 @@ function checkInsult(message) {
}
}
}
}
// Madlib game logic
// Setup story
function startMadlib(selectedStory) {
// Load story
const madlib = require("./madlibs/stories.json");
console.log("Madlib story count: " + Object.keys(madlib.stories).length);
let storyCount = Object.keys(madlib.stories).length;
if (selectedStory == undefined) {
//Pick random story:
let storyTitle = Object.keys(madlib.stories)[Math.trunc(Math.random() * storyCount)];
} else {
let storyTitle = Object.keys(madlib.stories)[selectedStory];
}
console.log("Current story: " + storyTitle);
let currentStory = madlib.stories[storyTitle];
let storyLength = currentStory.match(/<([^>]+)>/g).length;
// Update global variables with states.
global.madlibState.storyTitle = storyTitle;
global.madlibState.currentStory = currentStory;
global.madlibState.storyLength = storyLength;
//Print story title
const channel = client.channels.cache.get(madlibState.gameChannel);
channel.send("Current story: " + storyTitle);
}
/*
* This function sends a prompt for the next keyword for the madlib story.
*/
global.madlibNextPrompt = function madlibNextPrompt(client, iteration, selectedStory) {
console.log("Next prompt requested");
if (global.madlibState.currentStory == undefined) {
startMadlib(selectedStory);
}
let currentStory = global.madlibState.currentStory;
//Find all <> in the string and return it.
let phrase = currentStory.match(/(?<=<)[^>]+(?=>)/g);
//remove every other element in array, so we only have the prompts
console.log(phrase);
// Send a message in the gameChannel with the next prompt.
const channel = client.channels.cache.get(madlibState.gameChannel);
channel.send("Give me a(n) " + phrase[iteration]);
}
/*
* This function is executed when a player is sending a new message.
*/
global.madlibNextMessage = function madlibNextMessage(promptAnswerString, client) {
global.madlibState.storyIterate++;
//Process message
console.log("Processing next message...");
console.log("Player responded with: \"" + promptAnswerString +"\"");
global.madlibState.storyReplaceContent.push("`" + promptAnswerString + "`");
console.log(madlibState.storyReplaceContent);
// Check how many times we've iterated, and if we're not done collecting content for the story, continue
if (global.madlibState.storyIterate < global.madlibState.storyLength) {
global.madlibNextPrompt(client, global.madlibState.storyIterate, undefined);
} else { //Story content has been obtained! Now we just need to build the story and return it.
endMadlib();
}
}
function endMadlib() {
// Build story string, send the message, and set all of the madlibState variables to their defaults.
let currentStory = global.madlibState.currentStory;
let storyReplaceContent = global.madlibState.storyReplaceContent;
for (let i = 0; i < storyReplaceContent.length; ++i) {
currentStory = currentStory.replace(/<([^>]+)>/, storyReplaceContent[i]);
}
console.log(currentStory);
const channel = client.channels.cache.get(madlibState.gameChannel);
channel.send("Story is complete! \n" + currentStory);
//Reset madlibState.
global.madlibState = { gameChannel: undefined, storyTitle:undefined, currentStory: undefined, storyIterate: 0, storyReplaceContent: [], storyLength: undefined};
}

@ -1,3 +0,0 @@
files.encoding=UTF-8
site.root.folder=
source.folder=

@ -1,9 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://www.netbeans.org/ns/project/1">
<type>org.netbeans.modules.web.clientproject</type>
<configuration>
<data xmlns="http://www.netbeans.org/ns/clientside-project/1">
<name>nomoreacronyms</name>
</data>
</configuration>
</project>

@ -3,6 +3,7 @@
"version": "1.0.0",
"description": "",
"main": "main.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},