Compare commits
6
Commits
kopieerpasta
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
566704387d | ||
|
|
6fe6a756bb | ||
|
|
7be76c00c3 | ||
|
|
67a82abaca | ||
|
|
63ec2142ac | ||
|
|
70e462e8f8 |
No files matched your search
+295
-209
@@ -2,40 +2,34 @@ import discord
|
|||||||
from discord.ext import commands
|
from discord.ext import commands
|
||||||
import numpy as np
|
import numpy as np
|
||||||
import random
|
import random
|
||||||
import requests
|
|
||||||
import asyncio
|
import asyncio
|
||||||
import os
|
import os
|
||||||
import feedparser
|
import feedparser
|
||||||
import json
|
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
import re
|
import re
|
||||||
|
|
||||||
|
|
||||||
class Chatbot(commands.Cog):
|
class Chatbot(commands.Cog):
|
||||||
"""Een heuse chatbot. Under construction..."""
|
"""Een heuse chatbot. Under construction..."""
|
||||||
|
|
||||||
def __init__(self, bot):
|
def __init__(self, bot):
|
||||||
self.bot = bot
|
self.bot = bot
|
||||||
self.voice_states = {}
|
|
||||||
self.END_OF_MESSAGE = "<EOM>"
|
|
||||||
self.START_OF_MESSAGE = "<SOM>"
|
self.START_OF_MESSAGE = "<SOM>"
|
||||||
|
self.END_OF_MESSAGE = "<EOM>"
|
||||||
self.pmLast = datetime(2018, 1, 1, 1, 1, 1)
|
self.pmLast = datetime(2018, 1, 1, 1, 1, 1)
|
||||||
self.pmCount = 0
|
self.pmCount = 0
|
||||||
self.nosLast = datetime(2018, 1, 1, 1, 1, 1)
|
self.nosLast = datetime(2018, 1, 1, 1, 1, 1)
|
||||||
self.nosPosts = []
|
self.nosPosts = []
|
||||||
try:
|
self.recent_context = []
|
||||||
np.load('markov_dict.npy', allow_pickle=True)
|
self.wordDict = self.load_word_dict()
|
||||||
except FileNotFoundError:
|
|
||||||
#If there's no initial file, make a new one:
|
|
||||||
initFile = {'pairs':{self.START_OF_MESSAGE:{'Hoi':1},'Hoi':{self.END_OF_MESSAGE:1}}, 'trairs':{}, 'responsePairs':{}}
|
|
||||||
np.save("markov_dict.npy", initFile)
|
|
||||||
except:
|
|
||||||
print("ERROR! - Could not open or create Markov chat file")
|
|
||||||
self.wordDict = np.load("markov_dict.npy", allow_pickle=True).item()
|
|
||||||
self.wordPairDict = self.wordDict["pairs"]
|
self.wordPairDict = self.wordDict["pairs"]
|
||||||
self.forward_dict = self.wordPairDict
|
self.wordTrairDict = self.wordDict["trairs"]
|
||||||
self.reverse_dict = self.create_reverse_dict(self.forward_dict)
|
self.responsePairDict = self.wordDict["responsePairs"]
|
||||||
self.rijmwoordenboek = self.create_rijmwoordenboek(self.reverse_dict)
|
self.forward_dict = {}
|
||||||
|
self.reverse_dict = {}
|
||||||
|
self.rijmwoordenboek = {}
|
||||||
|
self.words_by_syls = {}
|
||||||
|
self.update_derived_dicts()
|
||||||
|
|
||||||
#Do stuff when a message comes in:
|
#Do stuff when a message comes in:
|
||||||
@self.bot.event
|
@self.bot.event
|
||||||
@@ -82,13 +76,58 @@ class Chatbot(commands.Cog):
|
|||||||
await self.respondToMessage(message)
|
await self.respondToMessage(message)
|
||||||
elif a < 10: #all other channels
|
elif a < 10: #all other channels
|
||||||
await self.respondToMessage(message)
|
await self.respondToMessage(message)
|
||||||
|
|
||||||
#process commands:
|
#process commands:
|
||||||
await self.bot.process_commands(message)
|
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):
|
def __check(self, ctx):
|
||||||
return True
|
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"
|
#The "Guus filter"
|
||||||
#Don't allow to learn from very large personal messages
|
#Don't allow to learn from very large personal messages
|
||||||
@@ -124,7 +163,7 @@ class Chatbot(commands.Cog):
|
|||||||
|
|
||||||
#If the message is only a tag, don't learn from it. return
|
#If the message is only a tag, don't learn from it. return
|
||||||
if message.count(' ') == 0 and message[0:2] == "<@":
|
if message.count(' ') == 0 and message[0:2] == "<@":
|
||||||
return newPairDict, newTrairDict;
|
return newPairDict, newTrairDict
|
||||||
|
|
||||||
message = self.START_OF_MESSAGE + " " + message + " " + self.END_OF_MESSAGE
|
message = self.START_OF_MESSAGE + " " + message + " " + self.END_OF_MESSAGE
|
||||||
corpus = message.split()
|
corpus = message.split()
|
||||||
@@ -152,7 +191,6 @@ class Chatbot(commands.Cog):
|
|||||||
newTrairDict[word_1][word_3] = 1
|
newTrairDict[word_1][word_3] = 1
|
||||||
else:
|
else:
|
||||||
newTrairDict[word_1] = {word_3 : 1}
|
newTrairDict[word_1] = {word_3 : 1}
|
||||||
|
|
||||||
return newPairDict, newTrairDict;
|
return newPairDict, newTrairDict;
|
||||||
|
|
||||||
#Learn to respond to messages
|
#Learn to respond to messages
|
||||||
@@ -161,7 +199,6 @@ class Chatbot(commands.Cog):
|
|||||||
STOP_WORDS = ["aan", "achter", "al", "ben", "dan", "dat", "de", "die", "dit", "een", "en", "er", "gehad", "had", "heb",
|
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",
|
"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"]
|
"a", "an", "the", "am", "was", "were", "be", "not", "at"]
|
||||||
|
|
||||||
newRespPairDict = wordDictResp
|
newRespPairDict = wordDictResp
|
||||||
|
|
||||||
#Split messages into words and remove stopwords:
|
#Split messages into words and remove stopwords:
|
||||||
@@ -184,30 +221,10 @@ class Chatbot(commands.Cog):
|
|||||||
newRespPairDict[word_1][word_2] = 1
|
newRespPairDict[word_1][word_2] = 1
|
||||||
else:
|
else:
|
||||||
newRespPairDict[word_1] = {word_2 : 1}
|
newRespPairDict[word_1] = {word_2 : 1}
|
||||||
|
|
||||||
return newRespPairDict
|
return newRespPairDict
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@commands.command(pass_context=True, hidden=True)
|
|
||||||
async def trainmarkovchat(self, ctx, channelId=409751773595566081, nrOfMessages=50):
|
|
||||||
"""Train that chain, jermaine
|
|
||||||
param channelId: use this channel to train
|
|
||||||
param nrOfMessages: use the x most recent messages
|
|
||||||
"""
|
|
||||||
|
|
||||||
channel=self.bot.get_channel(channelId)
|
|
||||||
await self.learnFromMessagesInChannel(channel, nrOfMessages)
|
|
||||||
|
|
||||||
await ctx.channel.send("Ik heb weer wat nieuwe woordjes geleerd. :slight_smile:")
|
|
||||||
|
|
||||||
|
|
||||||
#Learns from an x number of messages from a certain channel
|
#Learns from an x number of messages from a certain channel
|
||||||
async def learnFromMessagesInChannel(self, channel, nrOfMessages):
|
async def learnFromMessagesInChannel(self, channel, nrOfMessages):
|
||||||
|
|
||||||
#Open current chain:
|
|
||||||
wordDict = np.load('markov_dict.npy', allow_pickle=True).item()
|
|
||||||
|
|
||||||
#Iterate through the last x messages from the channel:
|
#Iterate through the last x messages from the channel:
|
||||||
messageIterator = channel.history(limit=nrOfMessages, before=None, after=None, oldest_first=False, around=None)
|
messageIterator = channel.history(limit=nrOfMessages, before=None, after=None, oldest_first=False, around=None)
|
||||||
allMessages = []
|
allMessages = []
|
||||||
@@ -215,6 +232,7 @@ class Chatbot(commands.Cog):
|
|||||||
msg = await anext(messageIterator)
|
msg = await anext(messageIterator)
|
||||||
allMessages.append(msg)
|
allMessages.append(msg)
|
||||||
|
|
||||||
|
learned_something = False
|
||||||
i = 0
|
i = 0
|
||||||
nextMessageIndex = -10
|
nextMessageIndex = -10
|
||||||
#Note: the loop goes from new to old
|
#Note: the loop goes from new to old
|
||||||
@@ -235,55 +253,41 @@ class Chatbot(commands.Cog):
|
|||||||
nosIds = re.findall(r'\d+', messageContent)
|
nosIds = re.findall(r'\d+', messageContent)
|
||||||
if nosIds:
|
if nosIds:
|
||||||
self.nosPosts.append(nosIds[0])
|
self.nosPosts.append(nosIds[0])
|
||||||
elif messageContent[0:7] == "http://" or messageContent[0:8] == "https://":
|
elif "http://" in messageContent or "https://" in messageContent:
|
||||||
pass # Een link. Negeer. TODO: post af en toe een random link die geen repost is
|
pass # Een link. Negeer. TODO: post af en toe een random link die geen repost is
|
||||||
else:
|
else:
|
||||||
# Usable message!
|
# Usable message!
|
||||||
wordDict['pairs'], wordDict['trairs'] = self.learnFrom(wordDict['pairs'], wordDict['trairs'], messageContent)
|
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
|
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
|
timeDelta = nextMessage.created_at - msg.created_at
|
||||||
#TODO check for different author
|
#TODO check for different author
|
||||||
if timeDelta.days == 0 and timeDelta.seconds < 3600: #less than an hour difference
|
if timeDelta.days == 0 and timeDelta.seconds < 3600: #less than an hour difference
|
||||||
#this is counted as a response. learn from it
|
#this is counted as a response. learn from it
|
||||||
wordDict['responsePairs'] = self.learnResponse(wordDict['responsePairs'], messageContent, nextMessageContent)
|
self.responsePairDict = self.learnResponse(self.responsePairDict, messageContent, nextMessageContent)
|
||||||
|
|
||||||
#save for next iteration:
|
#save for next iteration:
|
||||||
nextMessage = msg
|
nextMessage = msg
|
||||||
nextMessageContent = messageContent
|
nextMessageContent = messageContent
|
||||||
nextMessageIndex = i
|
nextMessageIndex = i
|
||||||
i += 1
|
i += 1
|
||||||
|
if learned_something: # Nieuwe woordjes! Werk bij en sla op
|
||||||
|
self.update_derived_dicts()
|
||||||
|
self.save_word_dict()
|
||||||
|
|
||||||
np.save("markov_dict.npy", wordDict)
|
@commands.command(hidden=True)
|
||||||
|
async def trainmarkovchat(self, ctx, channelId=69420, nrOfMessages=50):
|
||||||
|
"""Train that chain, jermaine
|
||||||
@commands.command(pass_context=True, hidden=False)
|
param channelId: use this channel to train
|
||||||
async def reageer(self, ctx):
|
param nrOfMessages: use the x most recent messages
|
||||||
"""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()
|
|
||||||
#print("respond to: ", wordsToRespondTo)
|
|
||||||
|
|
||||||
#Delete command
|
|
||||||
try:
|
try:
|
||||||
await ctx.message.delete()
|
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:
|
except:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
response = await self.getResponseForMessage(wordsToRespondTo)
|
|
||||||
await ctx.channel.send(response)
|
|
||||||
|
|
||||||
# Calculate probabilities and pick a next word from a word pair dict:
|
# 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
|
# https://stackoverflow.com/questions/835092/python-dictionary-are-keys-and-values-always-the-same-order
|
||||||
def pickNextWord(self, pairPossibilities):
|
def pickNextWord(self, pairPossibilities):
|
||||||
@@ -296,83 +300,47 @@ class Chatbot(commands.Cog):
|
|||||||
#Assumes the message isn't a command
|
#Assumes the message isn't a command
|
||||||
async def respondToMessage(self, message):
|
async def respondToMessage(self, message):
|
||||||
wordsToRespondTo = message.content.strip().split()
|
wordsToRespondTo = message.content.strip().split()
|
||||||
|
response = self.getResponseForMessage(wordsToRespondTo)
|
||||||
response = await self.getResponseForMessage(wordsToRespondTo)
|
|
||||||
await message.channel.send(response)
|
await message.channel.send(response)
|
||||||
|
|
||||||
#Gets a response
|
#Gets a response
|
||||||
async def getResponseForMessage(self, wordsToRespondTo, gptChance=0.1):
|
def getResponseForMessage(self, wordsToRespondTo):
|
||||||
if random.random() < 1-gptChance:
|
if random.random() <= 0.05:
|
||||||
try:
|
return self.get_uitspraak() #rip Geitje, leve Stroop!
|
||||||
# GPT request moet echt even in een non-blocking executortje, anders loopt de hele boel vast
|
|
||||||
response = await self.bot.loop.run_in_executor(None,self.getResponseForMessageOnline, wordsToRespondTo)
|
|
||||||
if response:
|
|
||||||
return response # Anders door naar local
|
|
||||||
except:
|
|
||||||
pass # Door naar local call
|
|
||||||
return self.getResponseForMessageLocal(wordsToRespondTo)
|
return self.getResponseForMessageLocal(wordsToRespondTo)
|
||||||
|
|
||||||
def translateTo(self, language, text):
|
|
||||||
req = requests.post('http://gpt.hoekveen.net/translate', json={"text": text, "source_lang": "auto", "target_lang": language})
|
|
||||||
print(req.json())
|
|
||||||
return req.json()["translations"][0]["text"]
|
|
||||||
|
|
||||||
def getResponseForMessageOnline(self, wordsToRespondTo):
|
|
||||||
prompt = " ".join(wordsToRespondTo)
|
|
||||||
if not prompt:
|
|
||||||
prompt = self.getResponseForMessageLocal([])
|
|
||||||
text = self.translateTo("en", prompt)
|
|
||||||
req = requests.post('http://gpt.hoekveen.net/complete', json={"prompt": text, "max_tokens": 80})
|
|
||||||
print(req.json())
|
|
||||||
respons = req.json()["text"]
|
|
||||||
respons = respons[0:respons.rfind(".")+1] # Alles weg na de laatste punt
|
|
||||||
return self.translateTo("nl", respons)
|
|
||||||
|
|
||||||
def getResponseForMessageLocal(self, wordsToRespondTo):
|
def getResponseForMessageLocal(self, wordsToRespondTo):
|
||||||
|
|
||||||
MAX_N_WORDS = 100 #Don't use more words than this
|
MAX_N_WORDS = 100 #Don't use more words than this
|
||||||
|
|
||||||
#Get dictionary/Markov chain
|
|
||||||
wordDict = np.load('markov_dict.npy', allow_pickle=True).item()
|
|
||||||
wordPairDict = wordDict['pairs']
|
|
||||||
wordTrairDict = wordDict['trairs']
|
|
||||||
responsePairDict = wordDict['responsePairs']
|
|
||||||
#TODO store in global variable to minimise IO?
|
|
||||||
|
|
||||||
#Start with <SOM>
|
#Start with <SOM>
|
||||||
chain = [self.START_OF_MESSAGE]
|
chain = [self.START_OF_MESSAGE]
|
||||||
|
|
||||||
#Go through the chain:
|
#Go through the chain:
|
||||||
for i in range(1, MAX_N_WORDS):
|
for i in range(1, MAX_N_WORDS):
|
||||||
|
|
||||||
if chain[-1] == self.END_OF_MESSAGE:
|
if chain[-1] == self.END_OF_MESSAGE:
|
||||||
break
|
break
|
||||||
|
|
||||||
#Find the possibilities:
|
#Find the possibilities:
|
||||||
pairPossibilities = wordPairDict[chain[-1]].copy()
|
pairPossibilities = self.wordPairDict[chain[-1]].copy()
|
||||||
|
|
||||||
#Increase score if it would be a good response:
|
#Increase score if it would be a good response:
|
||||||
for userWord in wordsToRespondTo:
|
for userWord in wordsToRespondTo:
|
||||||
if userWord in responsePairDict:
|
if userWord in self.responsePairDict:
|
||||||
for goodResponseWord in responsePairDict[userWord]:
|
for goodResponseWord in self.responsePairDict[userWord]:
|
||||||
if goodResponseWord in pairPossibilities.keys():
|
if goodResponseWord in pairPossibilities.keys():
|
||||||
if i == 1:
|
if i == 1:
|
||||||
pairPossibilities[goodResponseWord] += responsePairDict[userWord][goodResponseWord] * 2 #first word? try to respond
|
pairPossibilities[goodResponseWord] += self.responsePairDict[userWord][goodResponseWord] * 2 #first word? try to respond
|
||||||
else:
|
else:
|
||||||
pairPossibilities[goodResponseWord] += responsePairDict[userWord][goodResponseWord] * 0.1
|
pairPossibilities[goodResponseWord] += self.responsePairDict[userWord][goodResponseWord] * 0.1
|
||||||
#Increase score for trairs:
|
#Increase score for trairs:
|
||||||
if i > 1: #we can only compare trairs if we have at least two words already
|
if i > 1: #we can only compare trairs if we have at least two words already
|
||||||
if chain[-2] in wordTrairDict:
|
if chain[-2] in self.wordTrairDict:
|
||||||
trairPossibilities = wordTrairDict[chain[-2]].copy()
|
trairPossibilities = self.wordTrairDict[chain[-2]].copy()
|
||||||
#If a trair matches, increase the frequency of the pair
|
#If a trair matches, increase the frequency of the pair
|
||||||
for word2 in pairPossibilities.keys():
|
for word2 in pairPossibilities.keys():
|
||||||
if word2 in trairPossibilities.keys():
|
if word2 in trairPossibilities.keys():
|
||||||
pairPossibilities[word2] += trairPossibilities[word2]
|
pairPossibilities[word2] += trairPossibilities[word2]
|
||||||
|
|
||||||
#Pick a next word:
|
#Pick a next word:
|
||||||
chain.append(self.pickNextWord(pairPossibilities))
|
chain.append(self.pickNextWord(pairPossibilities))
|
||||||
|
|
||||||
|
|
||||||
if chain[0] == self.START_OF_MESSAGE:
|
if chain[0] == self.START_OF_MESSAGE:
|
||||||
chain = chain[1:-1] #remove <SOM> and <EOM>
|
chain = chain[1:-1] #remove <SOM> and <EOM>
|
||||||
else:
|
else:
|
||||||
@@ -384,13 +352,31 @@ class Chatbot(commands.Cog):
|
|||||||
a = random.randint(1,10)
|
a = random.randint(1,10)
|
||||||
if a != 1:
|
if a != 1:
|
||||||
chain[n] = "@jemoeder"
|
chain[n] = "@jemoeder"
|
||||||
|
|
||||||
#print(' '.join(chain))
|
|
||||||
#await ctx.channel.send(' '.join(chain))
|
|
||||||
return ' '.join(chain)
|
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
|
#Try to count the number of syllables in a word
|
||||||
#Used to make Haikus
|
#Used to make Haikus
|
||||||
@@ -405,7 +391,6 @@ class Chatbot(commands.Cog):
|
|||||||
#count vowels surrounded by consonants
|
#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("[bcdfghjklmnpqrstvwxyz]{1}[aeiouyëäïöüéèáà]{1,2}[bcdfghjklmnpqrstvwxz]{0,1}|[aeiouyëäïöüéèáà]{1,2}[bcdfghjklmnpqrstvwxz]{1}", word))
|
||||||
count += len(re.findall("[ëäï]", word)) #ideeën etc
|
count += len(re.findall("[ëäï]", word)) #ideeën etc
|
||||||
|
|
||||||
return max(1, count)
|
return max(1, count)
|
||||||
|
|
||||||
#Append a message change with a numer of syllables
|
#Append a message change with a numer of syllables
|
||||||
@@ -421,7 +406,6 @@ class Chatbot(commands.Cog):
|
|||||||
for poss in list(pairPossibilities.keys()):
|
for poss in list(pairPossibilities.keys()):
|
||||||
if self.countSyllables(poss) > nrOfSyl or poss == self.END_OF_MESSAGE: #TODO change to constant
|
if self.countSyllables(poss) > nrOfSyl or poss == self.END_OF_MESSAGE: #TODO change to constant
|
||||||
del pairPossibilities[poss]
|
del pairPossibilities[poss]
|
||||||
|
|
||||||
if len(pairPossibilities) == 0:
|
if len(pairPossibilities) == 0:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
@@ -436,36 +420,101 @@ class Chatbot(commands.Cog):
|
|||||||
#Make a nice Haiku
|
#Make a nice Haiku
|
||||||
def getHaiku(self):
|
def getHaiku(self):
|
||||||
MAX_N_TRIES = 50
|
MAX_N_TRIES = 50
|
||||||
|
for _ in range(MAX_N_TRIES):
|
||||||
#Get dictionary/Markov chain
|
|
||||||
wordDict = np.load('markov_dict.npy', allow_pickle=True).item()
|
|
||||||
wordPairDict = wordDict['pairs']
|
|
||||||
|
|
||||||
#try:
|
|
||||||
for i in range(1, MAX_N_TRIES):
|
|
||||||
chain = [self.START_OF_MESSAGE]
|
chain = [self.START_OF_MESSAGE]
|
||||||
|
chain = self.appendMessageWithNrOfSyllables(5, chain, self.wordPairDict)
|
||||||
chain = self.appendMessageWithNrOfSyllables(5, chain, wordPairDict)
|
|
||||||
if chain is not False:
|
if chain is not False:
|
||||||
chain.append("\n")
|
chain.append("\n")
|
||||||
chain = self.appendMessageWithNrOfSyllables(7, chain, wordPairDict)
|
chain = self.appendMessageWithNrOfSyllables(7, chain, self.wordPairDict)
|
||||||
if chain is not False:
|
if chain is not False:
|
||||||
chain.append("\n")
|
chain.append("\n")
|
||||||
chain = self.appendMessageWithNrOfSyllables(5, chain, wordPairDict)
|
chain = self.appendMessageWithNrOfSyllables(5, chain, self.wordPairDict)
|
||||||
if chain is not False:
|
if chain is not False:
|
||||||
break
|
break
|
||||||
|
|
||||||
chain = chain[1:] #remove <SOM>
|
chain = chain[1:] #remove <SOM>
|
||||||
return ' '.join(chain)
|
return ' '.join(chain)
|
||||||
|
|
||||||
@commands.command(pass_context=True, hidden=False)
|
@commands.command()
|
||||||
async def haiku(self, ctx):
|
async def haiku(self, ctx):
|
||||||
"""Stroop is een poëet. Laat hem een Haiku maken.
|
"""Stroop is een poëet. Laat hem een Haiku maken.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
response = self.getHaiku()
|
response = self.getHaiku()
|
||||||
await ctx.channel.send(response)
|
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
|
# Geeft eindrijm suffix voor gegeven woord
|
||||||
def get_eindrijm(self, word):
|
def get_eindrijm(self, word):
|
||||||
# handig bij rijmen en dichten zonder de broek op te hoeven lichten
|
# handig bij rijmen en dichten zonder de broek op te hoeven lichten
|
||||||
@@ -487,62 +536,79 @@ class Chatbot(commands.Cog):
|
|||||||
match = re.search(pattern, word)
|
match = re.search(pattern, word)
|
||||||
if match and match.group():
|
if match and match.group():
|
||||||
return match.group()
|
return match.group()
|
||||||
return word[-1] #niks rijmt op: brrr, zzz, pssjt. indexeren op laatste letter.
|
return "" #niks rijmt op: brrr, zzz, pssjt. of alfanumeriek.
|
||||||
|
|
||||||
# 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 rhyme_suffix not in rijmwoordenboek:
|
|
||||||
rijmwoordenboek[rhyme_suffix] = []
|
|
||||||
rijmwoordenboek[rhyme_suffix].append(word)
|
|
||||||
return rijmwoordenboek
|
|
||||||
|
|
||||||
# Draait de 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},
|
|
||||||
words_filter = ["<SOM>", "<EOM>"] #TODO misschien op andere manier filteren ten behoeve van modulariteit
|
|
||||||
reverse_dict = {}
|
|
||||||
for word, follow_words in forward_dict.items():
|
|
||||||
for follow_word, count in follow_words.items():
|
|
||||||
if follow_word not in reverse_dict:
|
|
||||||
reverse_dict[follow_word] = {}
|
|
||||||
if word not in words_filter:
|
|
||||||
reverse_dict[follow_word][word] = count
|
|
||||||
return reverse_dict
|
|
||||||
|
|
||||||
# random woord uit het vocabulaire van stroop op basis van lettergrepen
|
|
||||||
def get_random_word_by_sylls(self, syls: int):
|
|
||||||
words_with_n_sylls = []
|
|
||||||
for word in self.wordPairDict:
|
|
||||||
if self.countSyllables(word) == syls and word not in ("<SOM>", "<EOM>"):
|
|
||||||
words_with_n_sylls.append(word)
|
|
||||||
result = random.choice(words_with_n_sylls)
|
|
||||||
return result
|
|
||||||
|
|
||||||
# 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, wordPairDict):
|
|
||||||
if not msg_stem or syllables < 1:
|
|
||||||
return None
|
|
||||||
result = self.appendMessageWithNrOfSyllables(syllables, list(msg_stem), wordPairDict)
|
|
||||||
return result or None
|
|
||||||
|
|
||||||
# normaliseer zelfde woorden voor rijm checks
|
# normaliseer zelfde woorden voor rijm checks
|
||||||
def normalize(self, word):
|
def normalize(self, word):
|
||||||
return re.sub(r"^[^\w]+|[^\w]+$", "", word).lower()
|
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)
|
# 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):
|
def is_word_used(self, candidate, used_words):
|
||||||
c = self.normalize(candidate)
|
c = self.normalize(candidate)
|
||||||
@@ -552,8 +618,8 @@ class Chatbot(commands.Cog):
|
|||||||
return False
|
return False
|
||||||
|
|
||||||
# opvolgend in markov chain ? True : False
|
# opvolgend in markov chain ? True : False
|
||||||
def check_words_connect(self, word_1, word_2, wordPairDict):
|
def check_words_connect(self, word_1, word_2, word_dict):
|
||||||
return word_2 in wordPairDict.get(word_1, {})
|
return word_2 in word_dict.get(word_1, {})
|
||||||
|
|
||||||
# returns specificaties per dichtregel voor de limerick generator
|
# returns specificaties per dichtregel voor de limerick generator
|
||||||
def get_line_specs(self, line_number):
|
def get_line_specs(self, line_number):
|
||||||
@@ -613,7 +679,9 @@ class Chatbot(commands.Cog):
|
|||||||
|
|
||||||
# voor A1 en B1 verzinnen we een nieuw rijmwoord
|
# voor A1 en B1 verzinnen we een nieuw rijmwoord
|
||||||
if line_spec["new_rhyme"]:
|
if line_spec["new_rhyme"]:
|
||||||
word = self.get_random_word_by_sylls(random.randint(line_spec["min_end_syls"], line_spec["max_end_syls"]))
|
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)
|
end_of_line.append(word)
|
||||||
else: # A2,A3 rijmt op A1; B2 rijmt op B1
|
else: # A2,A3 rijmt op A1; B2 rijmt op B1
|
||||||
rhyme_group = used_rhymes[line_spec["rhyme_type"]] #gebruikt voor type; {"ing": ["koning", "ring"]}
|
rhyme_group = used_rhymes[line_spec["rhyme_type"]] #gebruikt voor type; {"ing": ["koning", "ring"]}
|
||||||
@@ -709,29 +777,48 @@ class Chatbot(commands.Cog):
|
|||||||
else:
|
else:
|
||||||
await ctx.channel.send("Sorry, geen inspiratie vandaag.")
|
await ctx.channel.send("Sorry, geen inspiratie vandaag.")
|
||||||
|
|
||||||
@commands.command(pass_context=True, hidden=False)
|
# slaat automatisch een stroop uitspraak op wanneer deze leuk bevonden is
|
||||||
async def uitspraak(self, ctx, numPosts=1):
|
def save_uitspraak(self, uitspraak):
|
||||||
"""Random uitspraak uit de hall of fame.
|
lines = uitspraak.splitlines()
|
||||||
Optioneel kan je een nummer meegeven voor meerdere uitspraken
|
if len(lines) > 1: #sla geen haiku's of limericks op als uitspraak
|
||||||
0 voor alle uitspraken."""
|
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:
|
try:
|
||||||
await ctx.message.delete()
|
await ctx.message.delete()
|
||||||
except:
|
except:
|
||||||
pass
|
pass
|
||||||
try:
|
|
||||||
message = ""
|
|
||||||
with open("uitspraken.txt", "r") as file:
|
|
||||||
uitspraken = file.readlines()
|
|
||||||
random.shuffle(uitspraken)
|
|
||||||
if numPosts == 0:
|
|
||||||
numPosts = len(uitspraken)
|
|
||||||
for i in range(numPosts):
|
|
||||||
message += uitspraken[i]
|
|
||||||
await ctx.channel.send(message)
|
await ctx.channel.send(message)
|
||||||
except:
|
|
||||||
pass
|
|
||||||
|
|
||||||
@commands.command(pass_context=True)
|
@commands.command()
|
||||||
async def nos(self, ctx, categorie=None):
|
async def nos(self, ctx, categorie=None):
|
||||||
"""Een leuk NOS artikel. Hoef je het zelf niet meer op te zoeken.
|
"""Een leuk NOS artikel. Hoef je het zelf niet meer op te zoeken.
|
||||||
Mag optioneel een categorie aangeven:
|
Mag optioneel een categorie aangeven:
|
||||||
@@ -766,11 +853,10 @@ class Chatbot(commands.Cog):
|
|||||||
if categorie in opties:
|
if categorie in opties:
|
||||||
artikelen = feedparser.parse("https://feeds.nos.nl/nosnieuws" + categorie).entries
|
artikelen = feedparser.parse("https://feeds.nos.nl/nosnieuws" + categorie).entries
|
||||||
artikel = random.choice(artikelen)
|
artikel = random.choice(artikelen)
|
||||||
#print(json.dumps(artikel, indent=4))
|
|
||||||
nosId = re.findall(r'\d+', artikel.id)[0]
|
nosId = re.findall(r'\d+', artikel.id)[0]
|
||||||
if nosId not in self.nosPosts:
|
if nosId not in self.nosPosts:
|
||||||
self.nosPosts.append(nosId)
|
self.nosPosts.append(nosId)
|
||||||
response = await self.getResponseForMessage(artikel.title, gptChance=0.5)
|
response = self.getResponseForMessage(artikel.title)
|
||||||
elif tries > 100:
|
elif tries > 100:
|
||||||
print("Oneindige loop voorkomen. Damn.")
|
print("Oneindige loop voorkomen. Damn.")
|
||||||
else:
|
else:
|
||||||
|
|||||||
+23
@@ -853,3 +853,26 @@ class Shitpost(commands.Cog):
|
|||||||
"""Is zaagmans al langsgeweest? Is de week al doormidden. Wie weet."""
|
"""Is zaagmans al langsgeweest? Is de week al doormidden. Wie weet."""
|
||||||
message = ctx.author.mention + ": " + self.get_zaagmans()
|
message = ctx.author.mention + ": " + self.get_zaagmans()
|
||||||
await ctx.channel.send(message)
|
await ctx.channel.send(message)
|
||||||
|
|
||||||
|
# checkt of de relevante xkcd bestaat
|
||||||
|
def xkcd_exists(self, url):
|
||||||
|
try:
|
||||||
|
response = requests.get(url, timeout=10)
|
||||||
|
return response.content.startswith(b"\x89PNG") > 0 #T/F
|
||||||
|
except requests.RequestException:
|
||||||
|
return False
|
||||||
|
|
||||||
|
@commands.command()
|
||||||
|
async def relevantxkcd(self, ctx, *, query: str):
|
||||||
|
"""There is always a relevant XKCD
|
||||||
|
Bijvoorbeeld:
|
||||||
|
!relevantxkcd bobby tables
|
||||||
|
"""
|
||||||
|
pic_url = "https://relevant-xkcd.com/@" + query.replace(" ", "_")
|
||||||
|
em = discord.Embed(description="Altijd weer relevant.")
|
||||||
|
em.set_image(url=pic_url)
|
||||||
|
|
||||||
|
if self.xkcd_exists(pic_url):
|
||||||
|
await ctx.channel.send(ctx.author.mention + ' een XKCD over "' + query + '":\n', embed=em)
|
||||||
|
else:
|
||||||
|
await ctx.channel.send(f'Ik kan helaas geen XKCD vinden met als onderwerp "{query}".')
|
||||||
Reference in new issue
Block a user