Files
stroopwafel/Chatbot.py
T
2026-11-11 18:30:37 +01:00

865 lines
38 KiB
Python

import discord
from discord.ext import commands
import numpy as np
import random
import asyncio
import os
import feedparser
from datetime import datetime
import re
class Chatbot(commands.Cog):
"""Een heuse chatbot. Under construction..."""
def __init__(self, bot):
self.bot = bot
self.START_OF_MESSAGE = "<SOM>"
self.END_OF_MESSAGE = "<EOM>"
self.pmLast = datetime(2018, 1, 1, 1, 1, 1)
self.pmCount = 0
self.nosLast = datetime(2018, 1, 1, 1, 1, 1)
self.nosPosts = []
self.recent_context = []
self.wordDict = self.load_word_dict()
self.wordPairDict = self.wordDict["pairs"]
self.wordTrairDict = self.wordDict["trairs"]
self.responsePairDict = self.wordDict["responsePairs"]
self.forward_dict = {}
self.reverse_dict = {}
self.rijmwoordenboek = {}
self.words_by_syls = {}
self.update_derived_dicts()
#Do stuff when a message comes in:
@self.bot.event
async def on_message(message):
if message.author.bot:
return #ignore your own messages, Stroop
if message.content.strip() == "" or message.content.strip()[0] != '!': #don't respond to a command
if message.content.lower() == "nihao":
await message.channel.send("kankerlauw")
return
if message.content.lower() == "lol":
await message.channel.send("laffing aut laut")
return
if self.bot.user.mentioned_in(message) and "@everyone" not in message.content:
MENTIONED_RESPONSES = [
"Hoi",
"hmm?",
"JA WAT?",
self.getResponseForMessageLocal("stroopwafel")
]
try:
MENTIONED_RESPONSES.append("Wat mot je, " + random.choice(self.bot.get_cog("Shitpost").insult) + "?")
except:
print("ERROR! - Could not import insults")
await message.channel.send(random.choice(MENTIONED_RESPONSES))
return
if re.match("^[0-9]+([,.]?[0-9]+)*?$", message.content.strip()) and random.randint(0,9) == 0:
await message.channel.send("That's Numberwang!") # https://www.youtube.com/watch?v=0obMRztklqU
return
if "DMChannel" in type(message.channel).__name__: #respond to messages in PM channels
if (self.isAllowedToLearnFromPm(message)): #avoid spam-learning
self.pmCount += 1
self.pmLast = datetime.now()
await self.learnFromMessagesInChannel(message.channel, 1)
await self.respondToMessage(message)
else:
a = random.randint(0,999) # probablity
if a < 40:
await self.learnFromMessagesInChannel(message.channel, 10)
if "stroop" in message.content.lower():
a = a / 20 # significantly increase the chance of responding if somebody talks about him.
if message.channel.id == os.getenv('STROOP_CHANNEL_SHITPOST') and a < 40: #shitpost channel
await self.respondToMessage(message)
elif a < 10: #all other channels
await self.respondToMessage(message)
#process commands:
await self.bot.process_commands(message)
#Do stuff when a reaction comes in:
@self.bot.event
async def on_reaction_add(reaction, user):
POSITIVE_REACTIONS = ["👍","👌","🥲","😅","😁","😄","☝️","❤️"]
if reaction.message.author != self.bot.user:
return
if str(reaction.emoji) not in POSITIVE_REACTIONS:
return
if sum(r.count for r in reaction.message.reactions if str(r.emoji) in POSITIVE_REACTIONS) <= 1:
uitspraak = str(reaction.message.content)
for word in self.recent_context: # Voorkom reacties op reacties
if word in uitspraak:
return
self.save_uitspraak(uitspraak)
reply_prefix = random.choice(["Haha,","Ja,","Nou,","Oh man,","Maar echt,","Precies,","Ik bedoel,","Tsja..."])
react_to = self.get_most_important_word(await self.get_context_as_string(reaction.message.channel.id))
for _ in range(10):
reply = self.try_append_syl_msg([f"{reply_prefix}", f"{react_to}"], random.randint(1,12), self.forward_dict)
if reply:
await reaction.message.channel.send(" ".join(reply))
break
self.update_recent_content(react_to) #fails willen we ook niet herhalen
return
def __check(self, ctx):
return True
def load_word_dict(self):
try:
return np.load('markov_dict.npy', allow_pickle=True).item()
except FileNotFoundError:
#If there's no initial file, make a new one:
init_file = {'pairs':{self.START_OF_MESSAGE:{'Hoi':1},'Hoi':{self.END_OF_MESSAGE:1}}, 'trairs':{}, 'responsePairs':{}}
np.save("markov_dict.npy", init_file)
return init_file
except Exception:
print("ERROR! - Could not open or create Markov chat file")
raise
def save_word_dict(self):
np.save("markov_dict.npy", self.wordDict)
def update_derived_dicts(self):
self.forward_dict = self.create_forward_dict(self.wordPairDict)
self.reverse_dict = self.create_reverse_dict(self.wordPairDict)
self.rijmwoordenboek = self.create_rijmwoordenboek(self.wordPairDict)
self.words_by_syls = self.create_words_by_syls(self.wordPairDict)
#The "Guus filter"
#Don't allow to learn from very large personal messages
#Only learn from 10 personal messages per hour at most
def isAllowedToLearnFromPm(self, message):
if len(message.content.strip()) > 150:
return False
diff = datetime.now() - self.pmLast
if diff.days > 0 or diff.seconds > 3600:
self.pmCount = 0
return True
if self.pmCount > 10:
return False
return True
#Make word pairs:
def makePairs(self, corpus):
for i in range(len(corpus)-1):
yield (corpus[i], corpus[i+1])
#Make word trairs. Yes, I completely made up "trair"
#It's like pairs, but with three, but not really, because there are two. OK?
#[1 0 1]
def makeTrairs(self, corpus):
for i in range(1, len(corpus)-1):
yield (corpus[i-1], corpus[i+1])
#Learn from a human message
#Returns an updated dict
def learnFrom(self, wordDictPairs, wordDictTrairs, message: str):
newPairDict = wordDictPairs
newTrairDict = wordDictTrairs
#If the message is only a tag, don't learn from it. return
if message.count(' ') == 0 and message[0:2] == "<@":
return newPairDict, newTrairDict
message = self.START_OF_MESSAGE + " " + message + " " + self.END_OF_MESSAGE
corpus = message.split()
for n, word in enumerate(corpus):
if word == "@everyone":
corpus[n] = "@iedereen"
pairs = self.makePairs(corpus)
trairs = self.makeTrairs(corpus)
#Add wordcounts to pair dict
for word_1, word_2 in pairs:
if word_1 in newPairDict.keys():
if word_2 in newPairDict[word_1].keys():
newPairDict[word_1][word_2] += 1
else:
newPairDict[word_1][word_2] = 1
else:
newPairDict[word_1] = {word_2 : 1}
#Add wordcounts to trair dict
for word_1, word_3 in trairs:
if word_1 in newTrairDict.keys():
if word_3 in newTrairDict[word_1].keys():
newTrairDict[word_1][word_3] += 1
else:
newTrairDict[word_1][word_3] = 1
else:
newTrairDict[word_1] = {word_3 : 1}
return newPairDict, newTrairDict;
#Learn to respond to messages
#Returns a new dict with response pairs
def learnResponse(self, wordDictResp, message1: str, message2: str):
STOP_WORDS = ["aan", "achter", "al", "ben", "dan", "dat", "de", "die", "dit", "een", "en", "er", "gehad", "had", "heb",
"hen", "het", "hun", "in", "is", "kon", "met", "na", "of", "om", "ook", "op", "tot", "van", "was", "wat", "zo",
"a", "an", "the", "am", "was", "were", "be", "not", "at"]
newRespPairDict = wordDictResp
#Split messages into words and remove stopwords:
message1List = []
message2List = []
for word in message1.split():
if word not in STOP_WORDS:
message1List.append(word)
for word in message2.split():
if word not in STOP_WORDS:
message2List.append(word)
#link words of response to words of initial message
for word_1 in message1List:
for word_2 in message2List:
if word_1 in newRespPairDict.keys():
if word_2 in newRespPairDict[word_1].keys():
newRespPairDict[word_1][word_2] += 1
else:
newRespPairDict[word_1][word_2] = 1
else:
newRespPairDict[word_1] = {word_2 : 1}
return newRespPairDict
#Learns from an x number of messages from a certain channel
async def learnFromMessagesInChannel(self, channel, nrOfMessages):
#Iterate through the last x messages from the channel:
messageIterator = channel.history(limit=nrOfMessages, before=None, after=None, oldest_first=False, around=None)
allMessages = []
for i in range(nrOfMessages):
msg = await anext(messageIterator)
allMessages.append(msg)
learned_something = False
i = 0
nextMessageIndex = -10
#Note: the loop goes from new to old
for msg in allMessages:
messageContent = msg.content.replace('(', '').replace(')', '').replace('"', '')
messageContent = messageContent.strip()
if messageContent == "":
pass # Bericht is leeg. Negeer.
elif msg.author.bot:
pass # Dit is een bot chat. Negeer.
elif messageContent[0] == "!":
pass # Dit is een commando. Negeer.
elif "```" in messageContent:
pass # Daar zit een codeblok in. Negeer.
elif "http" in messageContent and "nos" in messageContent:
# NOS link
nosIds = re.findall(r'\d+', messageContent)
if nosIds:
self.nosPosts.append(nosIds[0])
elif "http://" in messageContent or "https://" in messageContent:
pass # Een link. Negeer. TODO: post af en toe een random link die geen repost is
else:
# Usable message!
self.wordPairDict, self.wordTrairDict = self.learnFrom(self.wordPairDict, self.wordTrairDict, messageContent)
learned_something = True
if (i-nextMessageIndex) == 1 and msg.author != nextMessage.author: #the previous usable messages was the one right after this one and was not from the same author
timeDelta = nextMessage.created_at - msg.created_at
#TODO check for different author
if timeDelta.days == 0 and timeDelta.seconds < 3600: #less than an hour difference
#this is counted as a response. learn from it
self.responsePairDict = self.learnResponse(self.responsePairDict, messageContent, nextMessageContent)
#save for next iteration:
nextMessage = msg
nextMessageContent = messageContent
nextMessageIndex = i
i += 1
if learned_something: # Nieuwe woordjes! Werk bij en sla op
self.update_derived_dicts()
self.save_word_dict()
@commands.command(hidden=True)
async def trainmarkovchat(self, ctx, channelId=69420, nrOfMessages=50):
"""Train that chain, jermaine
param channelId: use this channel to train
param nrOfMessages: use the x most recent messages
"""
try:
channel=self.bot.get_channel(channelId)
await self.learnFromMessagesInChannel(channel, nrOfMessages)
await ctx.channel.send("Ik heb weer wat nieuwe woordjes geleerd. :slight_smile:")
except:
pass
# Calculate probabilities and pick a next word from a word pair dict:
# https://stackoverflow.com/questions/835092/python-dictionary-are-keys-and-values-always-the-same-order
def pickNextWord(self, pairPossibilities):
possible_words = list(pairPossibilities.keys())
weights = np.array(list(pairPossibilities.values()))
probs = weights / weights.sum()
return np.random.choice(possible_words, p=probs)
#Respond to a message.
#Assumes the message isn't a command
async def respondToMessage(self, message):
wordsToRespondTo = message.content.strip().split()
response = self.getResponseForMessage(wordsToRespondTo)
await message.channel.send(response)
#Gets a response
def getResponseForMessage(self, wordsToRespondTo):
if random.random() <= 0.05:
return self.get_uitspraak() #rip Geitje, leve Stroop!
return self.getResponseForMessageLocal(wordsToRespondTo)
def getResponseForMessageLocal(self, wordsToRespondTo):
MAX_N_WORDS = 100 #Don't use more words than this
#Start with <SOM>
chain = [self.START_OF_MESSAGE]
#Go through the chain:
for i in range(1, MAX_N_WORDS):
if chain[-1] == self.END_OF_MESSAGE:
break
#Find the possibilities:
pairPossibilities = self.wordPairDict[chain[-1]].copy()
#Increase score if it would be a good response:
for userWord in wordsToRespondTo:
if userWord in self.responsePairDict:
for goodResponseWord in self.responsePairDict[userWord]:
if goodResponseWord in pairPossibilities.keys():
if i == 1:
pairPossibilities[goodResponseWord] += self.responsePairDict[userWord][goodResponseWord] * 2 #first word? try to respond
else:
pairPossibilities[goodResponseWord] += self.responsePairDict[userWord][goodResponseWord] * 0.1
#Increase score for trairs:
if i > 1: #we can only compare trairs if we have at least two words already
if chain[-2] in self.wordTrairDict:
trairPossibilities = self.wordTrairDict[chain[-2]].copy()
#If a trair matches, increase the frequency of the pair
for word2 in pairPossibilities.keys():
if word2 in trairPossibilities.keys():
pairPossibilities[word2] += trairPossibilities[word2]
#Pick a next word:
chain.append(self.pickNextWord(pairPossibilities))
if chain[0] == self.START_OF_MESSAGE:
chain = chain[1:-1] #remove <SOM> and <EOM>
else:
chain = chain[:-1] #remove <EOM>
#remove 90% of tags:
for n, word in enumerate(chain):
if word[0:2] == "<@":
a = random.randint(1,10)
if a != 1:
chain[n] = "@jemoeder"
return ' '.join(chain)
@commands.command()
async def reageer(self, ctx):
"""Laat Stroop ergens op reageren.
Stroop leert van onze gesprekken. Hij kan zich nu voordoen als een van ons. Soort van.
"""
#Get previous message to respond to
messageIterator = ctx.channel.history(limit=3, before=None, after=None, oldest_first=False, around=None)
messageToRespondTo = await anext(messageIterator) #this will be the !reageer command. skip
messageToRespondTo = await anext(messageIterator)
if messageToRespondTo.content.strip()[0] == '!' or messageToRespondTo.author.bot: #another chance
messageToRespondTo = await anext(messageIterator) #but it's not a huge problem if he responds to himself
if messageToRespondTo.content.strip()[0] == '!':
wordsToRespondTo = []
else:
wordsToRespondTo = messageToRespondTo.content.strip().split()
try:
await ctx.message.delete() #Delete command
except:
pass
response = self.getResponseForMessage(wordsToRespondTo)
await ctx.channel.send(response)
#Try to count the number of syllables in a word
#Used to make Haikus
def countSyllables(self, word: str):
KNOWN_ACRONYMS = ["aub", "svp", "ivm", "nr", "zsm", "mbt", "tmi", "fyi", "afk", "omg", "idk", "coc"]
word = word.lower().strip()
#for acryonyms, just count the letters:
if word in KNOWN_ACRONYMS or re.match("^([a-z]{1}[.]{1}){2,}$", word) or re.match("^([bcdfghjklmnpqrstvwxz]){2,}$", word):
return len(word.replace(".", ""))
#count vowels surrounded by consonants
count = len(re.findall("[bcdfghjklmnpqrstvwxyz]{1}[aeiouyëäïöüéèáà]{1,2}[bcdfghjklmnpqrstvwxz]{0,1}|[aeiouyëäïöüéèáà]{1,2}[bcdfghjklmnpqrstvwxz]{1}", word))
count += len(re.findall("[ëäï]", word)) #ideeën etc
return max(1, count)
#Append a message change with a numer of syllables
#If it returns False, it couldn't find anything
#It's recursive, yo
def appendMessageWithNrOfSyllables(self, nrOfSyl: int, chain, wordPairDict):
#Find the possibilities:
if chain[-1] == "\n":
pairPossibilities = wordPairDict[chain[-2]].copy()
else:
pairPossibilities = wordPairDict[chain[-1]].copy()
for poss in list(pairPossibilities.keys()):
if self.countSyllables(poss) > nrOfSyl or poss == self.END_OF_MESSAGE: #TODO change to constant
del pairPossibilities[poss]
if len(pairPossibilities) == 0:
return False
#Pick a next word:
chain.append(self.pickNextWord(pairPossibilities))
if self.countSyllables(chain[-1]) == nrOfSyl:
return chain
#RECURSION!
return self.appendMessageWithNrOfSyllables( (nrOfSyl-self.countSyllables(chain[-1])) , chain, wordPairDict)
#Make a nice Haiku
def getHaiku(self):
MAX_N_TRIES = 50
for _ in range(MAX_N_TRIES):
chain = [self.START_OF_MESSAGE]
chain = self.appendMessageWithNrOfSyllables(5, chain, self.wordPairDict)
if chain is not False:
chain.append("\n")
chain = self.appendMessageWithNrOfSyllables(7, chain, self.wordPairDict)
if chain is not False:
chain.append("\n")
chain = self.appendMessageWithNrOfSyllables(5, chain, self.wordPairDict)
if chain is not False:
break
chain = chain[1:] #remove <SOM>
return ' '.join(chain)
@commands.command()
async def haiku(self, ctx):
"""Stroop is een poëet. Laat hem een Haiku maken.
"""
response = self.getHaiku()
await ctx.channel.send(response)
# Maakt forward_dict voor Limericks
def create_forward_dict(self, wordPairDict):
forward_dict = {}
# kopieert wordPairDict in feite, met wat poespas
for word, follow_words in wordPairDict.items():
if word not in forward_dict:
forward_dict[word] = {}
for follow_word, count in follow_words.items():
if follow_word == "<EOM>": # verlaag de kans dat <EOM> bereikt wordt zonder orphaned keys te maken
forward_dict[word][follow_word] = 1
else:
forward_dict[word][follow_word] = count
return forward_dict
# Draait een wordPairDict om. Dat rijmt wat makkelijker.
def create_reverse_dict(self, forward_dict):
# forward_dict: {word: {follow_word: count}} (wordPairDict)
# "de": {"kat": 3, "hond": 2},
# "een": {"kat": 4, "beer": 1},
# reverse_dict: {follow_word: {word: count}} (DictPairword) (:
# "kat": {"de": 3, "een": 4},
# "hond": {"de": 2},
# "beer": {"een" : 1},
reverse_dict = {}
for word, follow_words in forward_dict.items():
# the grande switcheroo: start wordt eind
if word == "<SOM>":
word = "<EOM>"
if word not in reverse_dict:
reverse_dict[word] = {}
for follow_word, count in follow_words.items():
# the grande switcheroo: eind wordt start
if follow_word == "<EOM>":
follow_word = "<SOM>"
if follow_word not in reverse_dict:
reverse_dict[follow_word] = {}
if word == "<EOM>": # verlaag de kans dat <EOM> bereikt wordt zonder orphaned keys te maken
reverse_dict[follow_word][word] = 1
else:
reverse_dict[follow_word][word] = count
reverse_dict.pop("<EOM>", None) # <EOM> kan geen key zijn (leeg na switcheroo)
return reverse_dict
# Indexeert woorden op basis van lettergrepen. dict of lists.
def create_words_by_syls(self, wordPairDict):
# {2: ["balpen", "stoofpeer"]},
# {3: ["atonaal", "stemhokje"]},...
# {5: ["hitteprotocol", "oorlogsverleden"]},...
words_by_syls = {}
for word in wordPairDict:
if word != self.START_OF_MESSAGE:
syls = self.countSyllables(word) # int
if syls < 12: #afvalwaterzuiveringsinstallatie
if syls not in words_by_syls:
words_by_syls[syls] = []
words_by_syls[syls].append(word)
return words_by_syls
# Genereert een rijmwoordenboek zodat je niet hoeft te hopen dat je loopje eindelijk
# de juiste combinatie van aantal lettergrepen + rijmuitgang genereert na 200 tries.
def create_rijmwoordenboek(self, raw_dict):
# {rhyme_suffix: [list of words]}
# {"ak": ["brak", "kak"]},
# {"elling": ["helling", "terschelling", "versnelling"]},
rijmwoordenboek = {}
for word in raw_dict:
rhyme_suffix = self.get_eindrijm(word)
if word == self.START_OF_MESSAGE:
continue
if rhyme_suffix not in rijmwoordenboek:
rijmwoordenboek[rhyme_suffix] = []
rijmwoordenboek[rhyme_suffix].append(word)
return rijmwoordenboek
# Geeft eindrijm suffix voor gegeven woord
def get_eindrijm(self, word):
# handig bij rijmen en dichten zonder de broek op te hoeven lichten
word = self.normalize(word)
if not word: #niks rijmt op empty strings.
return ""
V = "(?:ij|[aeiouyëäïöüéèáà])" #klinkers + ij
C = "[bcdfghjklmnpqrstvwxz]" #medeklinkers
rijmelarij = [
rf"{V}+{C}*(?:lijk|ig)+(?:e|en)?$", #uitzonderingen (WIP): heerlijk, eerlijk, buitensporig, saamhorig
rf"{V}+{C}+e[nrls]?s?$", #slepend rijm op C: lopen, kopen, roepen, poepen
rf"{V}+{C}+{V}+$", #slepend rijm op V: koffie, kloffie,
rf"{V}+{C}+$", #staand rijm op C: loop, koop, hond, mond
rf"{V}+$", #staand rijm op V: moe, koe
]
for pattern in rijmelarij:
match = re.search(pattern, word)
if match and match.group():
return match.group()
return "" #niks rijmt op: brrr, zzz, pssjt. of alfanumeriek.
# normaliseer zelfde woorden voor rijm checks
def normalize(self, word):
return re.sub(r"^[^\w]+|[^\w]+$", "", word).lower()
# store laatste 10 reply woorden om herhaling te voorkomen
def update_recent_content(self, word):
self.recent_context.append(word)
if len(self.recent_context) > 10:
self.recent_context.pop(0)
async def get_context_as_string(self, channel_id=69420, number_of_msg=15):
#pak laatste x berichten van een discussie
channel = self.bot.get_channel(channel_id)
#maak er 1 string van
message_iter = channel.history(limit=number_of_msg)
context_string = ""
for i in range(number_of_msg):
msg = await anext(message_iter)
if msg is None:
break
if not msg.author.bot and msg.content[0] != "!":
context_string += str(msg.content.strip()+"\n")
return context_string
# returns potentieel belangrijkste woord uit een zin
def get_most_important_word(self, sentence):
STOPWOORDJES = ["de", "het", "een", "ik", "jij", "je", "we", "wij", "ze", "hij", "ben", "dat",
"heeft", "kan", "moet", "niet", "geen", "wel", "ook", "nog", "dan", "toch", "ja", "nee",
"zo", "veel", "meer", "als", "omdat", "bij", "voor", "van", "naar", "met", "over", "op",
"maar", "en", "of", "er", "hoe", "is", "zijn", "was", "heb", "in", "uit", "aan", "door",
"mijn", "te", "om", "haha", "echt", "precies", "bedoel", "nou", "man"]
words = sorted(sentence.split(), key=len, reverse=True)
word_scores = {}
most_important_word = None
# houd de score bij in dict, filter contextloze woorden
for word in words:
score = 0
if self.normalize(word) not in STOPWOORDJES:
score = min(len(self.normalize(word)), 10)
score += min(words.count(word), 4)
score += 4 if any(char.isupper() for char in word) else 0
score -= 3 * sum(char in "@#(){}[]<>^*+/_=`~'\"\\|" for char in word)
if score > 0:
word_scores[word] = score
# sorteer op hoogste score
word_scores = dict(sorted(word_scores.items(), key=lambda item: item[1], reverse=True))
# pel af. return alleen als in dict om keyerrors te voorkomen
for word, score in word_scores.items():
if word in self.recent_context:
continue #sla over als al geweest
if word in self.wordPairDict:
most_important_word = word
break
elif self.normalize(word) in self.wordPairDict:
most_important_word = self.normalize(word)
break
return most_important_word or random.choice(["wat","dat","deze"])
# random woord uit het vocabulaire van stroop op basis van lettergrepen
def get_random_word_by_syls(self, syls: int):
words = self.words_by_syls.get(syls)
return random.choice(words) if words else None
# een wrapper voor appendMessageWithNrOfSyllables voor gebruik zonder chain manipulatie
# gebruikt om regels af te maken vanuit een gegeven lijst woorden die de "stam" vormen
def try_append_syl_msg(self, msg_stem, syllables, word_dict):
if not msg_stem or syllables < 1:
return None
result = self.appendMessageWithNrOfSyllables(syllables, list(msg_stem), word_dict)
return result or None
# checkt of een rijmwoord al gebruikt is, ook als dit om samengestelde woorden gaat (kerstliedjes X liedjes)
def is_word_used(self, candidate, used_words):
c = self.normalize(candidate)
for u in used_words:
if u.endswith(c) or c.endswith(u):
return True
return False
# opvolgend in markov chain ? True : False
def check_words_connect(self, word_1, word_2, word_dict):
return word_2 in word_dict.get(word_1, {})
# returns specificaties per dichtregel voor de limerick generator
def get_line_specs(self, line_number):
line_specs_dict = {
1: {
"syllables" : 9,
"rhyme_type" : "A",
"line_start" : ["Er was eens", "Een", "Er was eens een", "Er was ooit"],
"min_end_syls" : 2,
"max_end_syls" : 4,
"new_rhyme" : True,
},
2: {
"syllables" : 9,
"rhyme_type" : "A",
"line_start" : ["Die", "Die ging", "Die", "Die deed", "Die", "Die had"],
"min_end_syls" : 1,
"max_end_syls" : 3,
"new_rhyme" : False,
},
3: {
"syllables" : 5,
"rhyme_type" : "B",
"line_start" : ["Maar", "Toen", "Maar oh", "Ze", "Hij", "Op", "Voor", "Bij", "Met"],
"min_end_syls" : 1,
"max_end_syls" : 3,
"new_rhyme" : True,
},
4: {
"syllables" : 5,
"rhyme_type" : "B",
"line_start" : ["Zijn", "Haar", "Een", "Geen", "En"],
"min_end_syls" : 1,
"max_end_syls" : 2,
"new_rhyme" : False,
},
5: {
"syllables" : 9,
"rhyme_type" : "A",
"line_start" : ["Toen", "Dus", "Want", "Nu", "Met", "Dan"],
"min_end_syls" : 2,
"max_end_syls" : 4,
"new_rhyme" : False,
}
}
return line_specs_dict[line_number]
# genereert een limerick regel op basis van line_specs_dict
def get_line(self, line_number, used_rhymes, forward_dict, reverse_dict, rijmwoordenboek):
MAX_CANDIDATES = 20
line_spec = self.get_line_specs(line_number) #dict definities per limerickregel
line_start = random.choice(line_spec["line_start"]) #"Er was eens..."
start = line_start.split() # Start sectie, later bijplakken
end_of_line = ["\n"]
syls_remaining = line_spec["syllables"] - self.countSyllables(line_start)
# voor A1 en B1 verzinnen we een nieuw rijmwoord
if line_spec["new_rhyme"]:
word = self.get_random_word_by_syls(random.randint(line_spec["min_end_syls"], line_spec["max_end_syls"]))
if not word or self.get_eindrijm(word) == "":
return None
end_of_line.append(word)
else: # A2,A3 rijmt op A1; B2 rijmt op B1
rhyme_group = used_rhymes[line_spec["rhyme_type"]] #gebruikt voor type; {"ing": ["koning", "ring"]}
suffix = next(iter(rhyme_group)) #rijmuitgang is eerste (en enige) key; "ing"
used_words = rhyme_group[suffix] #woorden met deze uitgang zijn al gebruikt; ["koning", "ring"]
for _ in range(50):
# kies een woord dat rijmt op de rijmuitgang voor de betreffende A of B regel
candidate = random.choice(rijmwoordenboek[suffix])
# maar niet als deze al gebruikt is (of als het woord te lang is)
if self.is_word_used(candidate, used_words) or self.countSyllables(candidate) > line_spec["max_end_syls"]:
continue
end_of_line.append(candidate)
break
else:
return None
syls_remaining -= self.countSyllables(" ".join(end_of_line)) #opnieuw berekenen op basis van EoL
if syls_remaining < 0:
return None
if syls_remaining == 0: #als max syls bereikt, kijk of start aansluit op EoL
if self.check_words_connect(start[-1].lower(), end_of_line[-1].lower(), forward_dict):
return start + end_of_line[::-1]
else:
return None
# meet in the middle
# hak restant syls in 2 en check aansluiting
# start -> forwards <-> backwards <- end_of_line
forw_syls = syls_remaining // 2
backw_syls = syls_remaining - forw_syls
forwards = [] #kandidaten
backwards = []
if syls_remaining == 1: # 1 kun je niet meer splitsen; sluit aan op start
forwards = [start]
backw_syls = syls_remaining
else:
for _ in range(MAX_CANDIDATES): #voorwaarts vanaf start
candidate = self.try_append_syl_msg(start, forw_syls, forward_dict)
if candidate:
forwards.append(candidate)
for _ in range(MAX_CANDIDATES): #achterstevoren vanaf eind
candidate = self.try_append_syl_msg(end_of_line, backw_syls, reverse_dict)
if candidate:
backwards.append(candidate)
matches = []
for f in forwards:
for b in backwards:
#als laatste van forw aansluit op eerste backw slaan we de match op
if self.check_words_connect(f[-1].lower(), b[-1].lower(), forward_dict):
matches.append(f + b[::-1])
if matches:
return random.choice(matches) #en kiezen we een willekeurige om order bias te voorkomen
return None
# Make a nice Limerick
def get_limerick(self):
MAX_ATTEMPTS = 15
MAX_LINE_TRIES = 5
for _ in range(MAX_ATTEMPTS):
limerick = []
used_rhymes = {}
for line_number in range(1, 6):
line_success = False
for t in range(MAX_LINE_TRIES):
result = self.get_line(line_number, used_rhymes, self.forward_dict, self.reverse_dict, self.rijmwoordenboek)
if result: # voeg regel toe aan limerick en houd bij welke rijm en rijmwoorden gebruikt zijn
limerick.extend(result)
# "A": {"-elling": ["helling", "terschelling"]}
# "B": {"-ak": ["brak", "kak"]}
rhyme_type = self.get_line_specs(line_number)["rhyme_type"]
rhyme_suffix = self.get_eindrijm(result[-2])
if rhyme_type not in used_rhymes:
used_rhymes[rhyme_type] = {}
if rhyme_suffix not in used_rhymes[rhyme_type]:
used_rhymes[rhyme_type][rhyme_suffix] = []
used_rhymes[rhyme_type][rhyme_suffix].append(self.normalize(result[-2]))
line_success = True
break
if not line_success:
break
else:
return " ".join(limerick)
return None
@commands.command()
async def limerick(self, ctx):
"""Stroop is een schunnige rijmkoning. Laat hem een limerick maken."""
response = await asyncio.to_thread(self.get_limerick)
if response:
await ctx.channel.send(response)
else:
await ctx.channel.send("Sorry, geen inspiratie vandaag.")
# slaat automatisch een stroop uitspraak op wanneer deze leuk bevonden is
def save_uitspraak(self, uitspraak):
lines = uitspraak.splitlines()
if len(lines) > 1: #sla geen haiku's of limericks op als uitspraak
return
for word in self.recent_context: #sla geen reacties op reacties op
if word in uitspraak:
return
try:
with open("uitspraken.txt", "r", encoding="utf-8") as file:
uitspraken = file.read().split("\n")
if uitspraak not in uitspraken:
with open("uitspraken.txt", "a", encoding="utf-8") as file:
file.write(uitspraak+"\n")
except:
pass
def get_uitspraak(self):
DEFAULT_UITSPRAAK = "Ik ben Stroopwafel, een hele bijdehante bot!"
try:
with open("uitspraken.txt", "r", encoding="utf-8") as file:
uitspraken = file.readlines()
except FileNotFoundError:
with open("uitspraken.txt", "a", encoding="utf-8") as file:
file.write(f"{DEFAULT_UITSPRAAK}\n")
return DEFAULT_UITSPRAAK
except Exception:
print("ERROR - Could not open or create uitspraken.txt")
raise
return random.choice(uitspraken).strip()
@commands.command()
async def uitspraak(self, ctx):
"""Random uitspraak uit de hall of fame."""
message = self.get_uitspraak()
try:
await ctx.message.delete()
except:
pass
await ctx.channel.send(message)
@commands.command()
async def nos(self, ctx, categorie=None):
"""Een leuk NOS artikel. Hoef je het zelf niet meer op te zoeken.
Mag optioneel een categorie aangeven:
algemeen binnenland buitenland politiek economie opmerkelijk koningshuis cultuurenmedia tech """
try:
await ctx.message.delete()
except:
pass
diff = datetime.now() - self.nosLast
self.nosLast = datetime.now()
if diff.days <= 0 and diff.seconds <= 300:
await ctx.channel.send(f"Kappen nou {ctx.author.mention}")
return
opties = [
"algemeen",
"binnenland",
"buitenland",
"politiek",
"economie",
"opmerkelijk",
"koningshuis",
"cultuurenmedia",
"tech"
]
artikel = None
tries = 0
while artikel is None:
tries += 1
if not categorie:
categorie = random.choice(opties)
categorie = categorie.lower()
if categorie in opties:
artikelen = feedparser.parse("https://feeds.nos.nl/nosnieuws" + categorie).entries
artikel = random.choice(artikelen)
nosId = re.findall(r'\d+', artikel.id)[0]
if nosId not in self.nosPosts:
self.nosPosts.append(nosId)
response = self.getResponseForMessage(artikel.title)
elif tries > 100:
print("Oneindige loop voorkomen. Damn.")
else:
artikel = None
await ctx.channel.send(response + '\n' + artikel.link)