Updated Code

master
Chloe Fontenot 🏳️‍⚧️ 2019-12-16 16:19:10 +07:00
parent 2b6afd75ce
commit a1066e9850
4 changed files with 136 additions and 155 deletions

@ -9,79 +9,43 @@ import discord
import re
import sys
import random
import platform
import argparse
import os
#Setup Discord functions
class MyClient(discord.Client):
async def on_ready(self):
print('Logged on as', self.user)
# Announce on Discord that we are connected
message.channel.send('madlibs.py - Discord Edition has successfully connected!')
# check to see if termcolor is installed, we need it for color to work
try:
from termcolor import colored
except ImportError:
print("termcolor is not installed! Please install termcolor with" '\n', '\n', "pip install termcolor", '\n','\n'+"Note: You may need to run pip as root")
exit()
if debug == 1:
print("termcolor is installed!")
# If we are on Windows, we need to do a little more to get color to work
if platform.system() == 'Windows':
os.system('color')
# ArgSparce
parser = argparse.ArgumentParser()
parser.add_argument("-s", "--setup", help="Explains how to setup .txt file", action="store_true")
parser.add_argument("-c", "--story", type=int, help="Write story count to file")
args = parser.parse_args()
import asyncio
async def gameLoop():
# convert the integer to a string because pickiness
StoryCount = str(args.story)
StoryCount = str(args.story)
#if statements for ArgSparce
#if statements for ArgSparce
# line 36 fails if args.story reads as "None", so we need to clear that string if it reads as such.
if args.story == None:
# line 36 fails if args.story reads as "None", so we need to clear that string if it reads as such.
if args.story == None:
exec('args.story = int(0)')
# args.story should now read as 0
if args.story > 0:
f = open('storyCount.txt', "r+")
IntStoryCount = f.read()
print("There are currently", IntStoryCount, "in stories.txt")
f.seek(0)
f.write(StoryCount)
f.close()
print("Writing", StoryCount, "to txt file!")
# Introduce yourself
await channel.send("<<madlibsDiscord.py - Written by Caleb Fontenot>>")
await channel.send("Initial project started on July 13, 2019")
await channel.send("Discord Bot started on December 16, 2019")
# Notify if verbose
if debug == 1:
await channel.send("Debug mode is enabled! Being verbose!")
# Now on to business!
exit()
if args.setup == True:
sys.exit("If you want to include your own MadLibs story, you need to do the following:"+'\n'+"1. Open "+"\"stories.txt\""+'\n'+"2. Put the title of the story on all of the odd lines"+'\n'+"3. Put the entire story on one line, and put words you wish to replace in <>. Use the example as a reference."+'\n'+"4. When you are done, run me with the -c or --story flag to update how many stories are in stories.txt.")
# Linux easter egg
if platform.system() == 'Linux':
print('Linux master race! XD')
# Introduce yourself
print (colored("<<madlibs.", 'red')+colored("p", 'yellow')+colored("y", 'blue'), colored("- Written by Caleb Fontenot>>", 'red'), '\n' "Project started on July 13, 2019")
print("I pull txt files in the directory you place me in for stories!" '\n' '\n' "Run me with the --setup flag for instructions on setting a story up!" '\n')
print("Final Build*", '\n')
# Notify if verbose
if debug == 1:
print("Debug mode is enabled! Being verbose!", '\n')
else:
print('\n')
# Now on to business!
# Load files
f = open('storyCount.txt', 'r')
StoryCount = f.read()
IntStoryCount = int(StoryCount)
print("Detected", IntStoryCount, "stories")
# Randomly pick what story we will use
story = random.randint(1, IntStoryCount)
# Load files
f = open('storyCount.txt', 'r')
StoryCount = f.read()
IntStoryCount = int(StoryCount)
await channel.send("Detected "+IntStoryCount+" stories")
# Randomly pick what story we will use
story = random.randint(1, IntStoryCount)
#Declare vars
storyContentStr = []
storyNameStr = []
# Alright, let's get the data from stories.txt
i = 1
f = open('stories.txt', 'r')
for line in f.readlines():
#Declare vars
storyContentStr = []
storyNameStr = []
# Alright, let's get the data from stories.txt
i = 1
f = open('stories.txt', 'r')
for line in f.readlines():
if i % 2 == 0 :
storyContent = line
storyContentStr.append(storyContent)
@ -89,86 +53,103 @@ for line in f.readlines():
storyName = line
storyNameStr.append(storyName)
i+=1
f.close()
print(storyNameStr)
# Print current story title, but remove the brackets first
filteredTitle = re.findall(r'<(.*?)>', storyNameStr[story-1])
f.close()
print(storyNameStr)
# Print current story title, but remove the brackets first
filteredTitle = re.findall(r'<(.*?)>', storyNameStr[story-1])
# print the first result
print("Current story title is", '"'+filteredTitle[0]+'"','\n')
# print the first result
print("Current story title is", '"'+filteredTitle[0]+'"','\n')
# Alright, now onto the tricky part. We need to filter out all of the bracketed words in stories.txt, putting them into a list, replacing them with incremental strings. We also need to count how many there are for later.
# Pull all of the items with the <> brackets
filtered = re.findall(r'<(.*?)>', storyContentStr[story-1])
# We got them!
if debug == 1:
filtered = re.findall(r'<(.*?)>', storyContentStr[story-1])
# We got them!
if debug == 1:
print(filtered, '\n')
# Now we need to count them
replacedNumber = len(filtered)
# Now we need to count them
replacedNumber = len(filtered)
# Run a loop to get the words
# Run a loop to get the words
replaceList = []
#replaceList =['', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24']
replaceList.append("")
print("Type a noun, verb, adjective, or adverb depending on what it asks you, followed by enter.", '\n')
replaceList = []
#replaceList =['', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24']
replaceList.append("")
print("Type a noun, verb, adjective, or adverb depending on what it asks you, followed by enter.", '\n')
for loopCount in range(replacedNumber):
for loopCount in range(replacedNumber):
replaceVar = input("Give me a(n) "+colored(filtered[loopCount], 'blue')+": ")
replaceList.append(replaceVar)
print(replaceList)
print(replaceList)
# Run a loop to replace the words
print("Replacing Words...")
print("Replacing Words...")
# Split the Story Content into a list
storyContentList = re.split(r'<.*?>', storyContentStr[story-1])
# Count the items in the list
storyContentCount = len(storyContentList)
x = 0
for loopCount in range(storyContentCount):
# Split the Story Content into a list
storyContentList = re.split(r'<.*?>', storyContentStr[story-1])
# Count the items in the list
storyContentCount = len(storyContentList)
x = 0
for loopCount in range(storyContentCount):
#print(storyContentList[loopCount])
storyContentList.insert(x, replaceList[loopCount])
x = x+2
# To get colored words for our output, we need to add the appropiate commands to our variable.
storyContentListColored = re.split(r'<.*?>', storyContent)
x = 0
# To get colored words for our output, we need to add the appropiate commands to our variable.
storyContentListColored = re.split(r'<.*?>', storyContent)
x = 0
# Merge lists into a string
generatedStory = ""
generatedStory = generatedStory.join(storyContentList)
# Merge lists into a string
generatedStory = ""
generatedStory = generatedStory.join(storyContentList)
print(generatedStory)
#exit()
#Alright! We're done! Let's save the story to a file
now = datetime.now()
print(generatedStory)
#exit()
#Alright! We're done! Let's save the story to a file
now = datetime.now()
if os.path.exists("saved stories"):
if os.path.exists("saved stories"):
pass
else:
else:
os.system("mkdir \"saved stories\"")
currentDate = now.strftime("%d-%m-%Y-%H:%M:%S")
saveFile = 'saved stories/generatedStory-'+currentDate
print("Saving story to .txt file")
file = open(saveFile+'.txt', 'w+')
currentDate = now.strftime("%d-%m-%Y-%H:%M:%S")
saveFile = 'saved stories/generatedStory-'+currentDate
print("Saving story to .txt file")
file = open(saveFile+'.txt', 'w+')
line_offset = []
offset = 0
for line in file:
line_offset = []
offset = 0
for line in file:
line_offset.append(offset)
offset += len(line)
file.seek(0)
file.write(filteredTitle[0]+'\n'+'\n')
file.write(generatedStory)
file.write('\n'+"Generated by Caleb Fontenot\'s madlibs.py")
file.close()
#Setup Discord functions and announce on discord that we are ready
class MyClient(discord.Client):
async def on_ready(self):
print('Logged on as', self.user)
channel = client.get_channel(656233549837631508)
await channel.send("madlibs.py - Discord Edition has successfully connected!")
await channel.send("Run `mad!start` to start a a game")
print("Ready!")
async def on_message(self, message):
if message.content == 'mad!start':
await asyncio.set_event_loop(gameLoop())
file.seek(0)
file.write(filteredTitle[0]+'\n'+'\n')
file.write(generatedStory)
file.write('\n'+"Generated by Caleb Fontenot\'s madlibs.py")
file.close()
# say the tts
print('\n'+"Processing Text-To-Speech, please wait..."+'\n')
tts = gTTS(text=generatedStory+"This story was generated by Caleb Fontenot's MadLibs.py", lang='en')
tts.save("TTS.mp3")
#os.system("play TTS.mp3")
os.system("mv TTS.mp3 "+"\""+saveFile+".mp3"+"\"")
#Run main Game loop
# Connect Bot To Discord and start running
client = MyClient()
client.run('')
exit()
# say the tts
#print('\n'+"Processing Text-To-Speech, please wait..."+'\n')
#tts = gTTS(text=generatedStory+"This story was generated by Caleb Fontenot's MadLibs.py", lang='en')
#tts.save("TTS.mp3")
##os.system("play TTS.mp3")
#os.system("mv TTS.mp3 "+"\""+saveFile+".mp3"+"\"")
#Start Discord Bot loop

@ -0,0 +1,5 @@
Three Little Pigs
Once upon a time, there were three asdf pigs. One day, their mother said, "You are all grown up and must asd on your own." So they left to fasdf their houses. The first little pig wanted only to asd all day and quickly built his house out of fas. The second little pig wanted to dfa and sdf all day so he asdf his house with asdf. The third asdf pig knew the wolf lived nearby and worked hard to asfd his house out of . One day, the wolf knocked on the first pig's afsd. "Let me in or I'll afsd your house down!" The pig didn't, so the wolf afsd down the asfd. The wolf knocked on the second pig's afsd. "Let me in or I'll blow your afsd down!" The pig didn't, so the wolf fsad down the house. Then the wolf knocked on the third afsd pig's door. "Let me in or I'll blow your house down!" The little pig didn't, so the wolf afsd and afsd.He could not blow the house down. All the pigs went to live in the house and they all asfd happily ever after.
Generated by Caleb Fontenot's madlibs.py

@ -7,11 +7,6 @@ Thank you for choosing AMC Cinemas. Where we make movie moments AMC <adjective e
<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>
<<<<<<< HEAD
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>.
=======
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 the winner 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. I want to thank <random name>, for being there every step. Also, i'd like to thank my wife, <random girls name>, for <verb ending in ing>. Thank you all. Good <time of day>.
>>>>>>> 695ea65cb7dd2948b93f151627019e5be55fa160