python-project/madlibs/madlibsDiscord.py

169 lines
5.3 KiB
Python
Raw Normal View History

#!/usr/bin/python
# Toggle me for debugging
debug = 1
# Import the libraries we will use
from datetime import datetime
from gtts import gTTS
import discord
import re
import sys
import random
import os
2019-12-16 16:19:10 -06:00
import asyncio
2019-12-16 16:19:10 -06:00
2019-12-16 22:59:05 -06:00
async def gameLoop():
# Set bot presence
await client.change_presence(activity=discord.Game(name='madlibs.py'))
2019-12-16 16:19:10 -06:00
# Introduce yourself
2019-12-16 22:59:05 -06:00
channel = client.get_channel(656233549837631508)
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**")
2019-12-16 16:19:10 -06:00
# Notify if verbose
if debug == 1:
await channel.send("Debug mode is enabled! Being verbose!")
# Now on to business!
# Load files
2019-12-16 22:59:05 -06:00
async with channel.typing():
f = open('storyCount.txt', 'r')
StoryCount = f.read()
IntStoryCount = int(StoryCount)
await channel.send("Detected "+str(IntStoryCount)+" stories")
2019-12-16 16:19:10 -06:00
# 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():
if i % 2 == 0 :
storyContent = line
storyContentStr.append(storyContent)
else:
storyName = line
storyNameStr.append(storyName)
i+=1
f.close()
2019-12-16 22:59:05 -06:00
await channel.send(storyNameStr)
2019-12-16 16:19:10 -06:00
# Print current story title, but remove the brackets first
filteredTitle = re.findall(r'<(.*?)>', storyNameStr[story-1])
# print the first result
2019-12-16 22:59:05 -06:00
await channel.send("Current story title is "+'"'+str(filteredTitle[0])+'"'+'\n')
2019-12-16 16:19:10 -06:00
# 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
2019-12-16 16:19:10 -06:00
filtered = re.findall(r'<(.*?)>', storyContentStr[story-1])
# We got them!
if debug == 1:
2019-12-16 22:59:05 -06:00
await channel.send(str(filtered))
2019-12-16 16:19:10 -06:00
# Now we need to count them
replacedNumber = len(filtered)
# 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("")
2019-12-16 22:59:05 -06:00
await channel.send(str("Type a noun, verb, adjective, or adverb depending on what it asks you, followed by enter."))
2019-12-16 16:19:10 -06:00
for loopCount in range(replacedNumber):
2019-12-16 22:59:05 -06:00
#Wait for user to reply
await channel.send("Give me a(n) "+"**"+str(filtered[loopCount])+"**"+": ")
raw_message = await client.wait_for('message')
replaceVar = raw_message.content
print("You gave me: "+replaceVar)
2019-12-16 16:19:10 -06:00
replaceList.append(replaceVar)
print(replaceList)
# Run a loop to replace the words
2019-12-16 22:59:05 -06:00
await channel.send("Replacing Words...")
2019-12-16 16:19:10 -06:00
# 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.
x = 0
# Merge lists into a string
generatedStory = ""
generatedStory = generatedStory.join(storyContentList)
2019-12-16 22:59:05 -06:00
# Send Story to Discord
await channel.send(generatedStory)
2019-12-16 16:19:10 -06:00
#exit()
#Alright! We're done! Let's save the story to a file
now = datetime.now()
2019-12-16 22:59:05 -06:00
currentDate = now.strftime("%d-%m-%Y-%H:%M:%S")
saveFile = 'saved stories/generatedStory-'+currentDate
2019-12-16 16:19:10 -06:00
if os.path.exists("saved stories"):
pass
else:
os.system("mkdir \"saved stories\"")
2019-12-16 22:59:05 -06:00
2019-12-16 16:19:10 -06:00
print("Saving story to .txt file")
2019-12-16 22:59:05 -06:00
await channel.send("Saving story to .txt file")
async with channel.typing():
file = open(saveFile+'.txt', 'w+')
line_offset = []
offset = 0
for line in file:
line_offset.append(offset)
offset += len(line)
2019-12-16 16:19:10 -06:00
file.seek(0)
file.write(filteredTitle[0]+'\n'+'\n')
file.write(generatedStory)
file.write('\n'+"Generated by Caleb Fontenot\'s madlibs.py")
file.close()
2019-12-16 22:59:05 -06:00
#Send generated txt file to Discord
await channel.send("Sending .txt file...")
discordFile = discord.File(saveFile+'.txt', filename="generatedStory.txt")
await channel.send(file=discordFile)
2019-12-16 16:19:10 -06:00
#Setup Discord functions and announce on discord that we are ready
2019-12-16 22:59:05 -06:00
2019-12-16 16:19:10 -06:00
class MyClient(discord.Client):
2019-12-16 22:59:05 -06:00
2019-12-16 16:19:10 -06:00
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!")
2019-12-16 22:59:05 -06:00
async def on_message(self, message, pass_context=True):
2019-12-16 16:19:10 -06:00
if message.content == 'mad!start':
2019-12-16 22:59:05 -06:00
channel = client.get_channel(656233549837631508)
2019-12-16 23:22:46 -06:00
await gameLoop()
2019-12-16 22:59:05 -06:00
await channel.send("Done!")
2019-12-16 16:19:10 -06:00
#Run main Game loop
2019-12-16 23:22:46 -06:00
# The Discord bot ID isn't stored in this script for security reasons, so we have to go get it
f = open('botID.txt', 'r')
BotID = f.read()
2019-12-16 16:19:10 -06:00
# Connect Bot To Discord and start running
client = MyClient()
2019-12-16 23:22:46 -06:00
client.run(BotID)
2019-12-16 16:19:10 -06:00
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