Markov bot

master
xenofem 2020-05-13 16:26:31 -04:00
commit f5f2dfbec8
3 changed files with 90 additions and 0 deletions

5
.gitignore vendored Normal file
View File

@ -0,0 +1,5 @@
token
*~
corpus.txt
markov.json
env/

55
markov-bot.py Executable file
View File

@ -0,0 +1,55 @@
#!/usr/bin/env python3
import discord
import json
import random
import sys
START = "__START"
END = "__END"
with open('markov.json') as f:
markov = json.load(f)
def gen_sentence():
cur = START
output = []
while True:
cur = random.choice(markov[cur])
if cur == END:
break
output.append(cur)
return ' '.join(output)
class MyClient(discord.Client):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.bg_task = self.loop.create_task(self.background())
async def on_ready(self):
print('logged in as {0.user}'.format(self), file=sys.stderr)
async def on_message(self, message):
if message.author == self.user or self.user not in message.mentions:
return
await message.channel.send(gen_sentence())
async def background(self):
await self.wait_until_ready()
while not self.is_closed():
for guild in self.guilds:
try:
channel = random.choice(guild.text_channels)
await channel.send(gen_sentence())
except:
pass
await asyncio.sleep(3600)
client = MyClient()
with open('token') as f:
token = f.read().strip()
client.run(token)

30
markov-prep.py Executable file
View File

@ -0,0 +1,30 @@
#!/usr/bin/env python3
import json
START = "__START"
END = "__END"
with open('corpus.txt') as f:
corpus = f.read().split()
markov = {}
def markov_add(cur, nxt):
if cur not in markov:
markov[cur] = []
markov[cur].append(nxt)
cur = START
for word in corpus:
if len(word) == 0:
continue
markov_add(cur, word)
if word[-1] in '.?!':
markov_add(word, END)
cur = START
else:
cur = word
with open('markov.json', 'w') as f:
json.dump(markov, f)