Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
65088fc69d | ||
|
|
002be0b882 | ||
|
|
8517f544d5 | ||
|
|
925e908865 | ||
|
|
ce23527eee | ||
|
|
84287234e2 | ||
|
|
56f90e7829 | ||
|
|
38877451c5 | ||
|
|
b3efbaa291 | ||
|
|
896bc3afd7 | ||
|
|
99513b16d4 | ||
|
|
cc7a5f2f28 | ||
|
|
c919386fcb | ||
|
|
9d00b319aa | ||
|
|
3b9ac14719 | ||
|
|
d6bc6327a2 | ||
|
|
916a45715b | ||
|
|
3f5fc17833 | ||
|
|
29da1d218b | ||
|
|
07d22768fe | ||
|
|
392e19f4b3 | ||
|
|
9852f21ef7 | ||
|
|
41c2dc17d1 | ||
|
|
d1a699ee46 | ||
|
|
acbe8c6110 | ||
|
|
a53598b2c3 | ||
|
|
be6380d6b8 | ||
|
|
527164a040 | ||
|
|
f76f7a48c9 |
No files matched your search
+28
-28
@@ -2,34 +2,34 @@ kind: pipeline
|
||||
name: default
|
||||
|
||||
steps:
|
||||
- name: test
|
||||
image: python:3.11
|
||||
environment:
|
||||
STROOP_DISCORD_TOKEN:
|
||||
from_secret: STROOP_DISCORD_TOKEN
|
||||
STROOP_TWITTER_KEY:
|
||||
from_secret: STROOP_TWITTER_KEY
|
||||
STROOP_TWITTER_SECRET:
|
||||
from_secret: STROOP_TWITTER_SECRET
|
||||
STROOP_REDDIT_ID:
|
||||
from_secret: STROOP_REDDIT_ID
|
||||
STROOP_REDDIT_SECRET:
|
||||
from_secret: STROOP_REDDIT_SECRET
|
||||
STROOP_WEERLIVE:
|
||||
from_secret: STROOP_WEERLIVE
|
||||
STROOP_CALDAV_HOST:
|
||||
from_secret: STROOP_CALDAV_HOST
|
||||
STROOP_CALDAV_CAL:
|
||||
from_secret: STROOP_CALDAV_CAL
|
||||
STROOP_IMGFLIP_PASSWORD:
|
||||
from_secret: STROOP_IMGFLIP_PASSWORD
|
||||
STROOP_RESET_PASSWORD:
|
||||
from_secret: STROOP_RESET_PASSWORD
|
||||
STROOP_CHANNEL_SHITPOST:
|
||||
from_secret: STROOP_CHANNEL_SHITPOST
|
||||
commands:
|
||||
- pip install -r requirements.txt
|
||||
- python -m unittest tests
|
||||
- name: test
|
||||
image: python:3.13
|
||||
environment:
|
||||
STROOP_DISCORD_TOKEN:
|
||||
from_secret: STROOP_DISCORD_TOKEN
|
||||
STROOP_TWITTER_KEY:
|
||||
from_secret: STROOP_TWITTER_KEY
|
||||
STROOP_TWITTER_SECRET:
|
||||
from_secret: STROOP_TWITTER_SECRET
|
||||
STROOP_REDDIT_ID:
|
||||
from_secret: STROOP_REDDIT_ID
|
||||
STROOP_REDDIT_SECRET:
|
||||
from_secret: STROOP_REDDIT_SECRET
|
||||
STROOP_WEERLIVE:
|
||||
from_secret: STROOP_WEERLIVE
|
||||
STROOP_CALDAV_HOST:
|
||||
from_secret: STROOP_CALDAV_HOST
|
||||
STROOP_CALDAV_CAL:
|
||||
from_secret: STROOP_CALDAV_CAL
|
||||
STROOP_IMGFLIP_PASSWORD:
|
||||
from_secret: STROOP_IMGFLIP_PASSWORD
|
||||
STROOP_RESET_PASSWORD:
|
||||
from_secret: STROOP_RESET_PASSWORD
|
||||
STROOP_CHANNEL_SHITPOST:
|
||||
from_secret: STROOP_CHANNEL_SHITPOST
|
||||
commands:
|
||||
- pip install -r requirements.txt
|
||||
- python -m unittest tests
|
||||
trigger:
|
||||
event:
|
||||
exclude:
|
||||
|
||||
+379
-76
@@ -5,12 +5,14 @@ import random
|
||||
import requests
|
||||
import asyncio
|
||||
import os
|
||||
import feedparser
|
||||
import json
|
||||
from datetime import datetime
|
||||
import re
|
||||
|
||||
class Chatbot(commands.Cog):
|
||||
"""Een heuse chatbot. Under construction..."""
|
||||
|
||||
|
||||
def __init__(self, bot):
|
||||
self.bot = bot
|
||||
self.voice_states = {}
|
||||
@@ -18,6 +20,8 @@ class Chatbot(commands.Cog):
|
||||
self.START_OF_MESSAGE = "<SOM>"
|
||||
self.pmLast = datetime(2018, 1, 1, 1, 1, 1)
|
||||
self.pmCount = 0
|
||||
self.nosLast = datetime(2018, 1, 1, 1, 1, 1)
|
||||
self.nosPosts = []
|
||||
try:
|
||||
np.load('markov_dict.npy', allow_pickle=True)
|
||||
except FileNotFoundError:
|
||||
@@ -26,14 +30,19 @@ class Chatbot(commands.Cog):
|
||||
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.forward_dict = self.wordPairDict
|
||||
self.reverse_dict = self.create_reverse_dict(self.forward_dict)
|
||||
self.rijmwoordenboek = self.create_rijmwoordenboek(self.reverse_dict)
|
||||
|
||||
|
||||
#Do stuff when a message comes in:
|
||||
@self.bot.event
|
||||
async def on_message(message):
|
||||
if message.author.bot:
|
||||
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")
|
||||
@@ -49,7 +58,7 @@ class Chatbot(commands.Cog):
|
||||
self.getResponseForMessageLocal("stroopwafel")
|
||||
]
|
||||
try:
|
||||
MENTIONED_RESPONSES.append("Wat mot je, " + random.choice(self.bot.get_cog("Shitpost").insult) + "?")
|
||||
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))
|
||||
@@ -71,16 +80,16 @@ class Chatbot(commands.Cog):
|
||||
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
|
||||
elif a < 10: #all other channels
|
||||
await self.respondToMessage(message)
|
||||
|
||||
#process commands:
|
||||
await self.bot.process_commands(message)
|
||||
|
||||
|
||||
def __check(self, ctx):
|
||||
return True
|
||||
|
||||
|
||||
|
||||
|
||||
#The "Guus filter"
|
||||
#Don't allow to learn from very large personal messages
|
||||
#Only learn from 10 personal messages per hour at most
|
||||
@@ -94,29 +103,29 @@ class Chatbot(commands.Cog):
|
||||
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):
|
||||
@@ -133,7 +142,7 @@ class Chatbot(commands.Cog):
|
||||
else:
|
||||
newPairDict[word_1][word_2] = 1
|
||||
else:
|
||||
newPairDict[word_1] = {word_2 : 1}
|
||||
newPairDict[word_1] = {word_2 : 1}
|
||||
#Add wordcounts to trair dict
|
||||
for word_1, word_3 in trairs:
|
||||
if word_1 in newTrairDict.keys():
|
||||
@@ -143,18 +152,18 @@ class Chatbot(commands.Cog):
|
||||
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",
|
||||
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 = []
|
||||
@@ -164,7 +173,7 @@ class Chatbot(commands.Cog):
|
||||
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:
|
||||
@@ -174,11 +183,11 @@ class Chatbot(commands.Cog):
|
||||
else:
|
||||
newRespPairDict[word_1][word_2] = 1
|
||||
else:
|
||||
newRespPairDict[word_1] = {word_2 : 1}
|
||||
newRespPairDict[word_1] = {word_2 : 1}
|
||||
|
||||
return newRespPairDict
|
||||
|
||||
|
||||
|
||||
|
||||
@commands.command(pass_context=True, hidden=True)
|
||||
async def trainmarkovchat(self, ctx, channelId=409751773595566081, nrOfMessages=50):
|
||||
@@ -186,26 +195,26 @@ class Chatbot(commands.Cog):
|
||||
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
|
||||
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:
|
||||
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)
|
||||
|
||||
|
||||
i = 0
|
||||
nextMessageIndex = -10
|
||||
#Note: the loop goes from new to old
|
||||
@@ -221,41 +230,46 @@ class Chatbot(commands.Cog):
|
||||
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 messageContent[0:7] == "http://" or messageContent[0:8] == "https://":
|
||||
pass # Een link. Negeer. TODO: post af en toe een random link die geen repost is
|
||||
else:
|
||||
# Usable message!
|
||||
wordDict['pairs'], wordDict['trairs'] = self.learnFrom(wordDict['pairs'], wordDict['trairs'], messageContent)
|
||||
|
||||
|
||||
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
|
||||
wordDict['responsePairs'] = self.learnResponse(wordDict['responsePairs'], messageContent, nextMessageContent)
|
||||
|
||||
|
||||
#save for next iteration:
|
||||
nextMessage = msg
|
||||
nextMessageContent = messageContent
|
||||
nextMessageIndex = i
|
||||
i += 1
|
||||
|
||||
|
||||
np.save("markov_dict.npy", wordDict)
|
||||
|
||||
|
||||
|
||||
|
||||
@commands.command(pass_context=True, hidden=False)
|
||||
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] == '!':
|
||||
if messageToRespondTo.content.strip()[0] == '!':
|
||||
wordsToRespondTo = []
|
||||
else:
|
||||
wordsToRespondTo = messageToRespondTo.content.strip().split()
|
||||
@@ -266,29 +280,29 @@ class Chatbot(commands.Cog):
|
||||
await ctx.message.delete()
|
||||
except:
|
||||
pass
|
||||
|
||||
|
||||
response = await self.getResponseForMessage(wordsToRespondTo)
|
||||
await ctx.channel.send(response)
|
||||
|
||||
|
||||
# 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):
|
||||
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 = await self.getResponseForMessage(wordsToRespondTo)
|
||||
await message.channel.send(response)
|
||||
|
||||
|
||||
#Gets a response
|
||||
async def getResponseForMessage(self, wordsToRespondTo):
|
||||
if random.random() > 0.9:
|
||||
async def getResponseForMessage(self, wordsToRespondTo, gptChance=0.1):
|
||||
if random.random() < 1-gptChance:
|
||||
try:
|
||||
# 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)
|
||||
@@ -315,28 +329,28 @@ class Chatbot(commands.Cog):
|
||||
return self.translateTo("nl", respons)
|
||||
|
||||
def getResponseForMessageLocal(self, wordsToRespondTo):
|
||||
|
||||
|
||||
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>
|
||||
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 = wordPairDict[chain[-1]].copy()
|
||||
|
||||
|
||||
#Increase score if it would be a good response:
|
||||
for userWord in wordsToRespondTo:
|
||||
if userWord in responsePairDict:
|
||||
@@ -354,75 +368,75 @@ class Chatbot(commands.Cog):
|
||||
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"
|
||||
|
||||
|
||||
#print(' '.join(chain))
|
||||
#await ctx.channel.send(' '.join(chain))
|
||||
return ' '.join(chain)
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
#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):
|
||||
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
|
||||
|
||||
#Make a nice Haiku
|
||||
def getHaiku(self):
|
||||
MAX_N_TRIES = 50
|
||||
|
||||
|
||||
#Get dictionary/Markov chain
|
||||
wordDict = np.load('markov_dict.npy', allow_pickle=True).item()
|
||||
wordPairDict = wordDict['pairs']
|
||||
@@ -430,7 +444,7 @@ class Chatbot(commands.Cog):
|
||||
#try:
|
||||
for i in range(1, MAX_N_TRIES):
|
||||
chain = [self.START_OF_MESSAGE]
|
||||
|
||||
|
||||
chain = self.appendMessageWithNrOfSyllables(5, chain, wordPairDict)
|
||||
if chain is not False:
|
||||
chain.append("\n")
|
||||
@@ -440,18 +454,261 @@ class Chatbot(commands.Cog):
|
||||
chain = self.appendMessageWithNrOfSyllables(5, chain, wordPairDict)
|
||||
if chain is not False:
|
||||
break
|
||||
|
||||
|
||||
chain = chain[1:] #remove <SOM>
|
||||
return ' '.join(chain)
|
||||
|
||||
|
||||
@commands.command(pass_context=True, hidden=False)
|
||||
async def haiku(self, ctx):
|
||||
"""Stroop is een poëet. Laat hem een Haiku maken.
|
||||
"""
|
||||
|
||||
|
||||
response = self.getHaiku()
|
||||
await ctx.channel.send(response)
|
||||
|
||||
# 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 word[-1] #niks rijmt op: brrr, zzz, pssjt. indexeren op laatste letter.
|
||||
|
||||
# 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
|
||||
def normalize(self, word):
|
||||
return re.sub(r"^[^\w]+|[^\w]+$", "", word).lower()
|
||||
|
||||
# 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, wordPairDict):
|
||||
return word_2 in wordPairDict.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_sylls(random.randint(line_spec["min_end_syls"], line_spec["max_end_syls"]))
|
||||
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.")
|
||||
|
||||
@commands.command(pass_context=True, hidden=False)
|
||||
async def uitspraak(self, ctx, numPosts=1):
|
||||
"""Random uitspraak uit de hall of fame.
|
||||
@@ -473,3 +730,49 @@ class Chatbot(commands.Cog):
|
||||
await ctx.channel.send(message)
|
||||
except:
|
||||
pass
|
||||
|
||||
@commands.command(pass_context=True)
|
||||
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)
|
||||
#print(json.dumps(artikel, indent=4))
|
||||
nosId = re.findall(r'\d+', artikel.id)[0]
|
||||
if nosId not in self.nosPosts:
|
||||
self.nosPosts.append(nosId)
|
||||
response = await self.getResponseForMessage(artikel.title, gptChance=0.5)
|
||||
elif tries > 100:
|
||||
print("Oneindige loop voorkomen. Damn.")
|
||||
else:
|
||||
artikel = None
|
||||
await ctx.channel.send(response + '\n' + artikel.link)
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
FROM python:3.11
|
||||
FROM python:3.13
|
||||
|
||||
WORKDIR /opt/stroopwafel
|
||||
|
||||
|
||||
+23
-28
@@ -5,7 +5,7 @@ import random
|
||||
import re
|
||||
import json, requests
|
||||
import warnings
|
||||
from datetime import date, timedelta
|
||||
from datetime import timedelta, datetime, timezone
|
||||
from discord.ext import commands
|
||||
|
||||
class General(commands.Cog):
|
||||
@@ -13,7 +13,7 @@ class General(commands.Cog):
|
||||
|
||||
def __init__(self, bot):
|
||||
self.bot = bot
|
||||
self.muzak_url = 'https://muzak.hoekveen.net'
|
||||
self.muzak_url = 'http://muzak.hoekveen.net:8001'
|
||||
self.r = praw.Reddit(
|
||||
user_agent='StroopwafelBot',
|
||||
client_secret=os.getenv("STROOP_REDDIT_SECRET"),
|
||||
@@ -23,7 +23,7 @@ class General(commands.Cog):
|
||||
warnings.simplefilter("ignore")
|
||||
|
||||
def get_emoji_embed(self, tag: str):
|
||||
emoji = re.search(".*\<\:([A-z]*)\:(\d*)\>.*", tag)
|
||||
emoji = re.search(r'.*\<\:([A-z]*)\:(\d*)\>.*', tag)
|
||||
embed = discord.Embed(title=emoji.group(1), type='photo')
|
||||
hugemoji = 'https://cdn.discordapp.com/emojis/' + emoji.group(2) + '.png'
|
||||
embed.set_image(url=hugemoji)
|
||||
@@ -59,19 +59,25 @@ class General(commands.Cog):
|
||||
|
||||
def get_kopieerpasta(self):
|
||||
rkopieerpasta = self.r.subreddit('kopieerpasta')
|
||||
post = rkopieerpasta.random()
|
||||
try:
|
||||
post = rkopieerpasta.random()
|
||||
|
||||
# Subreddits kunnen de random functie uitzetten, dus dit is de fallback:
|
||||
if post == None:
|
||||
listing = list(rkopieerpasta.top('month', limit=250))
|
||||
post = random.choice(listing)
|
||||
# Subreddits kunnen de random functie uitzetten, dus dit is de fallback:
|
||||
if post == None:
|
||||
listing = list(rkopieerpasta.top(time_filter='month', limit=250))
|
||||
post = random.choice(listing)
|
||||
|
||||
return post
|
||||
return post
|
||||
except:
|
||||
return None
|
||||
|
||||
@commands.command(pass_context=True)
|
||||
async def kopieerpasta(self, ctx):
|
||||
"""Een willekeurige shitpost"""
|
||||
post = self.get_kopieerpasta()
|
||||
if not post:
|
||||
await ctx.channel.send("Geen kopieerpasta voor jou vandaag.")
|
||||
return
|
||||
print(post.url)
|
||||
ATTEMPTS = 10
|
||||
a = 0
|
||||
@@ -88,7 +94,7 @@ class General(commands.Cog):
|
||||
await ctx.channel.send('**'+post.title+'**```'+post.selftext+'```')
|
||||
else:
|
||||
await ctx.channel.send("Geen kopieerpasta voor jou vandaag.")
|
||||
|
||||
|
||||
def get_playlist_json(self):
|
||||
return requests.get(self.muzak_url + '/stroopwafel')
|
||||
|
||||
@@ -97,25 +103,15 @@ class General(commands.Cog):
|
||||
"""HD muzak playlist"""
|
||||
data = json.loads(self.get_playlist_json().content)
|
||||
msg = ""
|
||||
open = date.fromisoformat(data['openDate'])
|
||||
nom = date.fromisoformat(data['deadlineNominations'])
|
||||
vote = date.fromisoformat(data['deadlineVoting'])
|
||||
today = date.today()
|
||||
open = datetime.fromisoformat(data['openDate'])
|
||||
nom = datetime.fromisoformat(data['deadlineNominations'])
|
||||
vote = datetime.fromisoformat(data['deadlineVoting'])
|
||||
today = datetime.now(tz=timezone(timedelta(hours=2)))
|
||||
if open > today:
|
||||
msg += "Het stemmen is nog niet geopend voor dit jaar.\n"
|
||||
msg += f"Nog even geduld; Vanaf {open} is de muzak open en kun je naar hartelust stemmen en nomineren.\n"
|
||||
elif today > nom and today > vote and (today - vote) < timedelta(days=8):
|
||||
msg += "Het nomineren en stemmen is alweer voorbij.\n"
|
||||
msg += "Je zult nog even geduld moeten hebben tot de lijst klaar is.\n"
|
||||
elif today > nom and today > vote:
|
||||
msg += "De lijst is al helemaal klaar. Goed gedaan jongens. Applausje voor jezelf."
|
||||
msg = "Muwat?"
|
||||
else:
|
||||
if open == today:
|
||||
msg += "Jawel mensen! Vanaf vandaag mag het stemmen beginnen!\n"
|
||||
msg += f"Stemmen en nomineren kan hier: {self.muzak_url}\n"
|
||||
msg += f"Stemmen en nomineren kan hier: https://muzak.hoekveen.net/ \n"
|
||||
msg += f"*Er zijn al {data['stemCount']} nummers genomineerd!*\n"
|
||||
msg += f"Nomineren kan tot {nom}, stemmen kan tot {vote}.\n"
|
||||
msg += "\nIk hoop dat jullie allemaal je beste nummers insturen!"
|
||||
await ctx.channel.send(msg)
|
||||
|
||||
@commands.command(pass_context=True)
|
||||
@@ -125,7 +121,7 @@ class General(commands.Cog):
|
||||
response = requests.get(poll)
|
||||
if response:
|
||||
# one-liner want eet stront
|
||||
cijfer = float(re.findall(r";\d\.?\d?;", json.loads([x for x in response.text.splitlines() if "var options =" in x][0].partition("=")[2].strip(";, "))["data"]["csv"])[-1].strip(";"))
|
||||
cijfer = float(re.findall(r";\d\.?\d?\n", json.loads([x for x in response.text.splitlines() if "var options =" in x][0].partition("=")[2].strip(";, "))["data"]["csv"])[-1].strip(";\n"))
|
||||
msg = ""
|
||||
if cijfer < 3:
|
||||
msg = f"Nou, het lijkt goed te gaan. Recentelijk gaven mensen hun klachten maar een {cijfer}. Lekker!"
|
||||
@@ -138,4 +134,3 @@ class General(commands.Cog):
|
||||
await ctx.channel.send(ctx.author.mention + ' ' + msg)
|
||||
else:
|
||||
await ctx.channel.send(ctx.author.mention + ' Er lijkt even geen klachtencijfer beschikbaar te zijn. Probeer het later nog eens')
|
||||
|
||||
@@ -1,284 +1,317 @@
|
||||
import discord
|
||||
from discord.ext import commands
|
||||
from pprint import pprint
|
||||
import time
|
||||
import numpy as np
|
||||
import random
|
||||
import os
|
||||
from datetime import datetime
|
||||
|
||||
|
||||
class Points(commands.Cog):
|
||||
"""Geef elkaar punten!"""
|
||||
|
||||
def __init__(self, bot):
|
||||
self.bot = bot
|
||||
self.voice_states = {}
|
||||
|
||||
self.BANK_ID = 42
|
||||
self.init()
|
||||
|
||||
self.pointsCount = {}
|
||||
self.reloadPointsCount()
|
||||
|
||||
def __check(self, ctx):
|
||||
return True
|
||||
|
||||
@commands.command(pass_context=True, hidden=False)
|
||||
async def geefpunten(self, ctx, user, points: int):
|
||||
"""Wees eens lief. Geef iemand wat punten.
|
||||
Bijvoorbeeld:
|
||||
!geefpunten @ikbenjp 42
|
||||
Let op: je moet iemand taggen om punten uit te delen
|
||||
De eerste 10 punten zijn on the house. (Als er genoeg in de bank zit.)
|
||||
"""
|
||||
|
||||
self.reloadPointsCount()
|
||||
|
||||
if points == 0:
|
||||
await ctx.channel.send("0 punten? Gul hoor.")
|
||||
return
|
||||
if points < 0:
|
||||
await self.sendErrorDm(ctx, "Daar hebben we de !neempunten functie voor. Voor meer info typ: ```!help neempunten```")
|
||||
return
|
||||
|
||||
if user[0:2] != "<@":
|
||||
await self.sendErrorDm(ctx, "Je moet iemand taggen om punten te geven. :)")
|
||||
#TODO ook userId oid toestaan?
|
||||
return
|
||||
"""Geef elkaar punten!"""
|
||||
|
||||
userObj = ctx.message.mentions[0]
|
||||
|
||||
if userObj.id == ctx.author.id:
|
||||
await ctx.channel.send("Nee. Je mag niet jezelf punten geven.")
|
||||
time.sleep(0.6)
|
||||
await ctx.channel.send("Gekkie.")
|
||||
return
|
||||
if not self.isUserOnList(userObj):
|
||||
await ctx.channel.send("Nee. Die krijgt geen punten.")
|
||||
return
|
||||
if self.getUserBalance(ctx.author) < points:
|
||||
await ctx.channel.send("Daar heb jij niet genoeg puntjes voor. :bell:")
|
||||
return
|
||||
|
||||
# Execute the transaction:
|
||||
self.execute_geefpunten(ctx.author.id, userObj.id, points)
|
||||
|
||||
self.savePointsCount()
|
||||
def __init__(self, bot):
|
||||
self.bot = bot
|
||||
self.voice_states = {}
|
||||
|
||||
message = self.getMessageForAwardingPoints(ctx.author.name, userObj.name, points)
|
||||
await ctx.channel.send(message)
|
||||
|
||||
def execute_geefpunten(self, giverId, recieverId, points):
|
||||
# First, try to give away (at most 10) bankpoints
|
||||
areBeingGivenFromBank = min(points, self.getUsersRemainingBankPointsToGiveAwayToday(giverId))
|
||||
areBeingGivenFromBank = min(areBeingGivenFromBank, self.getBankBalance())
|
||||
if areBeingGivenFromBank > 0:
|
||||
self.transferPoints(self.BANK_ID, recieverId, areBeingGivenFromBank)
|
||||
self.increaseUsersBankPointGivenAwayToday(giverId, areBeingGivenFromBank)
|
||||
remainingPointsToGive = points - areBeingGivenFromBank
|
||||
else:
|
||||
remainingPointsToGive = points
|
||||
# The remaining points come out of your own pocket
|
||||
if remainingPointsToGive > 0:
|
||||
self.transferPoints(giverId, recieverId, remainingPointsToGive)
|
||||
|
||||
|
||||
@commands.command(pass_context=True, hidden=False)
|
||||
async def neempunten(self, ctx, user, points: int):
|
||||
"""Tijd om iemand the shamen. Haal wat punten weg.
|
||||
Bijvoorbeeld:
|
||||
!neempunten @mark 5
|
||||
Punten gaan naar de bank. Je mag niet meer dan 10 punten per dag afnemen.
|
||||
Let op: je moet iemand taggen om punten weg te nemen.
|
||||
"""
|
||||
|
||||
self.reloadPointsCount()
|
||||
|
||||
if points < 1:
|
||||
await ctx.channel.send("Volgens mij snap je het niet.")
|
||||
return
|
||||
if points > 10:
|
||||
await self.sendErrorDm(ctx, "Je mag niet meer dan 10 punten afnemen.")
|
||||
return
|
||||
remainingToTakeAway = self.getUsersRemainingPointsToTakeToday(ctx.author.id)
|
||||
if points > remainingToTakeAway: # The limit per day is 10
|
||||
await self.sendErrorDm(ctx, "Je mag vandaag nog maar " + str(remainingToTakeAway) + " punten wegnemen.")
|
||||
return
|
||||
|
||||
if user[0:2] != "<@":
|
||||
await self.sendErrorDm(ctx, "Je moet iemand taggen. :)")
|
||||
return
|
||||
|
||||
userObj = ctx.message.mentions[0]
|
||||
|
||||
if not self.isUserOnList(userObj):
|
||||
await ctx.channel.send("Nee.")
|
||||
return
|
||||
if self.getUserBalance(userObj) < points:
|
||||
await ctx.channel.send(userObj.name + " mag niet rood staan.")
|
||||
return
|
||||
|
||||
# Execute the transaction:
|
||||
self.execute_neempunten(ctx.author.id, userObj.id, points);
|
||||
|
||||
self.savePointsCount()
|
||||
self.BANK_ID = 42
|
||||
self.init()
|
||||
|
||||
message = self.getMessageForTakingPoints(userObj.name, ctx.author.name, points)
|
||||
await ctx.channel.send(message)
|
||||
|
||||
def execute_neempunten(self, takerId, victimId, points):
|
||||
self.increaseUsersPointTakenOnDate(takerId, points)
|
||||
self.transferPoints(victimId, self.BANK_ID, points)
|
||||
|
||||
|
||||
@commands.command(pass_context=True, hidden=False)
|
||||
async def puntentelling(self, ctx):
|
||||
"""Hoeveel punten heeft iedereen?
|
||||
"""
|
||||
|
||||
self.reloadPointsCount()
|
||||
|
||||
message = "**De puntentelling:** \n```"
|
||||
pointsCountSorted = sorted(self.pointsCount.items(), key=lambda i: i[1]['points'], reverse=True)
|
||||
for user in pointsCountSorted:
|
||||
if user[0] != self.BANK_ID:
|
||||
message += str(user[1]["points"]).rjust(4) + " " + user[1]["name"] + "\n"
|
||||
message += str(self.pointsCount[self.BANK_ID]["points"]).rjust(4) + " " + self.pointsCount[self.BANK_ID]["name"] + "```"
|
||||
await ctx.channel.send(message)
|
||||
|
||||
|
||||
# No public shaming. Send somebody a direct correction message.
|
||||
async def sendErrorDm(self, ctx, message):
|
||||
try:
|
||||
await ctx.message.delete()
|
||||
except:
|
||||
print("No permission to delete message")
|
||||
try:
|
||||
await ctx.message.author.send(message)
|
||||
except:
|
||||
print("No permission to send DM")
|
||||
|
||||
|
||||
# Get the points count object from the file
|
||||
def reloadPointsCount(self):
|
||||
self.pointsCount = np.load('pointscount.npy', allow_pickle=True).item()
|
||||
|
||||
# Save the points count to the file
|
||||
def savePointsCount(self):
|
||||
np.save("pointscount.npy", self.pointsCount)
|
||||
|
||||
# Transfer points form one user to another
|
||||
def transferPoints(self, fromUserId, toUserId, points):
|
||||
self.pointsCount[fromUserId]["points"] -= points
|
||||
self.pointsCount[toUserId]["points"] += points
|
||||
|
||||
# Do we know this user?
|
||||
def isUserOnList(self, user):
|
||||
return user.id in self.pointsCount.keys()
|
||||
|
||||
# Get a user's point balance
|
||||
def getUserBalance(self, user):
|
||||
return self.pointsCount[user.id]["points"]
|
||||
|
||||
# Get the balance of the bank
|
||||
def getBankBalance(self):
|
||||
return self.pointsCount[self.BANK_ID]["points"]
|
||||
|
||||
# To keep track if a user used some points today, we look at when the last time was he/she used them
|
||||
# If this was in the past: reset
|
||||
# Also, return the updated object. Why not.
|
||||
def refreshDateVarsAndReturnUserVars(self, userId):
|
||||
currentDateStr = datetime.now().strftime("%Y%m%d")
|
||||
if self.pointsCount[userId]["theDate"] != currentDateStr:
|
||||
self.pointsCount[userId]["theDate"] = currentDateStr
|
||||
self.pointsCount[userId]["pointTakenOnDate"] = 0
|
||||
self.pointsCount[userId]["bankPointsGivenOnDate"] = 0
|
||||
return self.pointsCount[userId]
|
||||
|
||||
# How many points can this user still take away today?
|
||||
def getUsersRemainingPointsToTakeToday(self, userId):
|
||||
userInfo = self.refreshDateVarsAndReturnUserVars(userId)
|
||||
return 10 - userInfo["pointTakenOnDate"]
|
||||
|
||||
# How many bank points can this user still give away?
|
||||
def getUsersRemainingBankPointsToGiveAwayToday(self, userId):
|
||||
userInfo = self.refreshDateVarsAndReturnUserVars(userId)
|
||||
return 10 - userInfo["bankPointsGivenOnDate"]
|
||||
|
||||
# Increase the number of points this user has taken away today.
|
||||
# Warning: assumes you executed refreshDateVarsAndReturnUserVars()
|
||||
def increaseUsersPointTakenOnDate(self, userId, points):
|
||||
self.pointsCount[userId]["pointTakenOnDate"] += points
|
||||
|
||||
# Increase the number of bank points this user has given today
|
||||
# Warning: assumes you executed refreshDateVarsAndReturnUserVars()
|
||||
def increaseUsersBankPointGivenAwayToday(self, userId, points):
|
||||
self.pointsCount[userId]["bankPointsGivenOnDate"] += points
|
||||
self.pointsCount = {}
|
||||
self.reloadPointsCount()
|
||||
|
||||
|
||||
# Generate a semi-random text to tell somebody they got some shiny new points
|
||||
def getMessageForAwardingPoints(self, userNameFrom: str, userNameTo: str, points: int):
|
||||
p = str(points)
|
||||
|
||||
if points == 1:
|
||||
grammarFixer = {"suffixGb":"", "suffixNl":"", "zijnOfIs": "is"}
|
||||
else:
|
||||
grammarFixer = {"suffixGb":"s", "suffixNl":"en", "zijnOfIs": "zijn"}
|
||||
|
||||
messages = [
|
||||
p + " punt" + grammarFixer["suffixNl"] + " voor " + userNameTo + ".",
|
||||
userNameTo + " krijgt " + p + " punt" + grammarFixer["suffixNl"] + ".",
|
||||
userNameTo + " krijgt " + p + " punt" + grammarFixer["suffixNl"] + " van " + userNameFrom,
|
||||
p + " POINT" + grammarFixer["suffixGb"].upper() + " TO GRYFFINDO.. oh.. " + userNameTo + ".",
|
||||
userNameTo + ", jij krijgt " + p + " puntje" + grammarFixer["suffixGb"] + " van " + userNameFrom + ". Lief he? :heart:",
|
||||
"+" + p + " punt" + grammarFixer["suffixNl"] + " voor " + userNameTo + "! Highscore!",
|
||||
userNameTo + ", alsjeblieft, " + p + " punt" + grammarFixer["suffixNl"] + ".",
|
||||
"Hier " + grammarFixer["zijnOfIs"] + " " + p + " punt" + grammarFixer["suffixNl"] + ", " + userNameTo + ". Don't spend it all in one place...",
|
||||
"Jij kan wel " + p + " punt" + grammarFixer["suffixNl"] + " gebruiken, " + userNameTo + ".",
|
||||
p + " blockchain smartcontract punt" + grammarFixer["suffixNl"] + " voor " + userNameTo + ". :rocket: "
|
||||
]
|
||||
return messages[random.randint(0, len(messages)-1)]
|
||||
|
||||
# Generate a semi-random text to tell somebody they just lost their precious points
|
||||
def getMessageForTakingPoints(self, userNameFrom: str, userNameTaker: str, points: int):
|
||||
p = str(points)
|
||||
|
||||
if points == 1:
|
||||
grammarFixer = {"suffixGb":"", "suffixNl":"", "gaatOfGaan":"gaat"}
|
||||
else:
|
||||
grammarFixer = {"suffixGb":"s", "suffixNl":"en", "gaatOfGaan":"gaan"}
|
||||
|
||||
messages = [
|
||||
userNameFrom + " verliest " + p + " punt" + grammarFixer["suffixNl"] + ".",
|
||||
userNameFrom + " is " + p + " punt" + grammarFixer["suffixNl"] + " kwijt. F.",
|
||||
userNameTaker + " vindt dat jij " + p + " punt" + grammarFixer["suffixNl"] + " moet kwijtraken, " + userNameFrom + ".",
|
||||
p + " POINT" + grammarFixer["suffixGb"].upper() + " FROM HUFFELPU.. oh.. " + userNameFrom + ".",
|
||||
"Je bent " + p + " punt" + grammarFixer["suffixNl"] + " armer geworden, " + userNameFrom + ".",
|
||||
"Je hebt toch genoeg, " + userNameFrom + ". We halen " + p + " punt" + grammarFixer["suffixNl"] + " weg.",
|
||||
userNameTaker + " haalt " + p + " punt" + grammarFixer["suffixNl"] + " weg bij " + userNameFrom + ". Wat een lul.",
|
||||
p + " punt" + grammarFixer["suffixNl"] + " " + grammarFixer["gaatOfGaan"] + " van " + userNameFrom + " naar de bank."
|
||||
]
|
||||
return messages[random.randint(0, len(messages)-1)]
|
||||
|
||||
|
||||
def init(self):
|
||||
# Check if points file exists:
|
||||
try:
|
||||
pointsCount = np.load('pointscount.npy', allow_pickle=True).item()
|
||||
except FileNotFoundError:
|
||||
np.save("pointscount.npy", {})
|
||||
pointsCount = np.load('pointscount.npy', allow_pickle=True).item()
|
||||
|
||||
# Initialise the bank:
|
||||
if self.BANK_ID not in pointsCount.keys():
|
||||
pointsCount[self.BANK_ID] = {"name": '"De Bank"', "points": 300}
|
||||
np.save("pointscount.npy", pointsCount)
|
||||
|
||||
# Add new/unknown members:
|
||||
list_channel = self.bot.get_channel(int(os.getenv('STROOP_CHANNEL_SHITPOST')))
|
||||
memberList = list_channel.members if list_channel else []
|
||||
for member in memberList:
|
||||
# Give new members 100 points
|
||||
if member.id not in pointsCount.keys() and not member.bot:
|
||||
pointsCount[member.id] = {"name": member.name, "points": 100, "pointTakenOnDate":0, "bankPointsGivenOnDate":0, "theDate":"20181231"}
|
||||
np.save("pointscount.npy", pointsCount)
|
||||
def __check(self, ctx):
|
||||
return True
|
||||
|
||||
@commands.command()
|
||||
async def geefpunten(self, ctx, *args):
|
||||
"""Wees eens lief. Geef iemand wat punten.
|
||||
Bijvoorbeeld:
|
||||
!geefpunten @ikbenjp 42 of !geefpunten 42 @ikbenjp
|
||||
Let op: je moet iemand taggen om punten uit te delen
|
||||
De eerste 10 punten zijn on the house. (Als er genoeg in de bank zit.)
|
||||
"""
|
||||
|
||||
if not ctx.message.mentions: #als er uberhaupt geen mention is zijn we snel klaar
|
||||
await ctx.send(f"{ctx.author.mention} je moet iemand taggen om punten te geven. :)")
|
||||
return
|
||||
|
||||
if len(args) == 2:
|
||||
user = None
|
||||
points = None
|
||||
for arg in args[0:2]:
|
||||
if arg[0:2] == "<@":
|
||||
user = arg #doen we verder niks mee, maar zo bepalen we positie van de puntjes
|
||||
else:
|
||||
try:
|
||||
points = int(arg)
|
||||
except ValueError:
|
||||
pass #dealen we hieronder mee
|
||||
|
||||
if user == None or points == None:
|
||||
raise commands.BadArgument("Verkeerd type argumenten")
|
||||
else:
|
||||
raise commands.BadArgument("Verkeerd aantal argumenten")
|
||||
|
||||
self.reloadPointsCount()
|
||||
|
||||
if points == 0:
|
||||
await ctx.channel.send("0 punten? Gul hoor.")
|
||||
return
|
||||
if points < 0:
|
||||
await self.sendErrorDm(ctx, "Daar hebben we de !neempunten functie voor. Voor meer info typ: ```!help neempunten```")
|
||||
return
|
||||
|
||||
userObj = ctx.message.mentions[0]
|
||||
|
||||
if userObj.id == ctx.author.id:
|
||||
await ctx.channel.send("Nee. Je mag niet jezelf punten geven.")
|
||||
time.sleep(0.6)
|
||||
await ctx.channel.send("Gekkie.")
|
||||
return
|
||||
if not self.isUserOnList(userObj):
|
||||
await ctx.channel.send("Nee. Die krijgt geen punten.")
|
||||
return
|
||||
if self.getUserBalance(ctx.author) < points:
|
||||
await ctx.channel.send("Daar heb jij niet genoeg puntjes voor. :bell:")
|
||||
return
|
||||
|
||||
# Execute the transaction:
|
||||
self.execute_geefpunten(ctx.author.id, userObj.id, points)
|
||||
|
||||
self.savePointsCount()
|
||||
|
||||
message = self.getMessageForAwardingPoints(ctx.author.name, userObj.name, points)
|
||||
await ctx.channel.send(message)
|
||||
|
||||
def execute_geefpunten(self, giverId, recieverId, points):
|
||||
# First, try to give away (at most 10) bankpoints
|
||||
areBeingGivenFromBank = min(points, self.getUsersRemainingBankPointsToGiveAwayToday(giverId))
|
||||
areBeingGivenFromBank = min(areBeingGivenFromBank, self.getBankBalance())
|
||||
if areBeingGivenFromBank > 0:
|
||||
self.transferPoints(self.BANK_ID, recieverId, areBeingGivenFromBank)
|
||||
self.increaseUsersBankPointGivenAwayToday(giverId, areBeingGivenFromBank)
|
||||
remainingPointsToGive = points - areBeingGivenFromBank
|
||||
else:
|
||||
remainingPointsToGive = points
|
||||
# The remaining points come out of your own pocket
|
||||
if remainingPointsToGive > 0:
|
||||
self.transferPoints(giverId, recieverId, remainingPointsToGive)
|
||||
|
||||
|
||||
@commands.command()
|
||||
async def neempunten(self, ctx, *args):
|
||||
"""Tijd om iemand the shamen. Haal wat punten weg.
|
||||
Bijvoorbeeld:
|
||||
!neempunten @mark 5 of !neempunten 5 @mark
|
||||
Punten gaan naar de bank. Je mag niet meer dan 10 punten per dag afnemen.
|
||||
Let op: je moet iemand taggen om punten weg te nemen.
|
||||
"""
|
||||
|
||||
if not ctx.message.mentions: #als er uberhaupt geen mention is zijn we snel klaar
|
||||
await ctx.send(f"{ctx.author.mention} je moet iemand taggen om punten af te nemen. :)")
|
||||
return
|
||||
|
||||
if len(args) == 2:
|
||||
user = None
|
||||
points = None
|
||||
for arg in args[0:2]:
|
||||
if arg[0:2] == "<@":
|
||||
user = arg #doen we verder niks mee, maar zo bepalen we positie van de puntjes
|
||||
else:
|
||||
try:
|
||||
points = int(arg)
|
||||
except ValueError:
|
||||
pass #dealen we hieronder mee
|
||||
|
||||
if user == None or points == None:
|
||||
raise commands.BadArgument("Verkeerd type argumenten")
|
||||
else:
|
||||
raise commands.BadArgument("Verkeerd aantal argumenten")
|
||||
|
||||
self.reloadPointsCount()
|
||||
|
||||
if points < 1:
|
||||
await ctx.channel.send("Volgens mij snap je het niet.")
|
||||
return
|
||||
if points > 10:
|
||||
await self.sendErrorDm(ctx, "Je mag niet meer dan 10 punten afnemen.")
|
||||
return
|
||||
remainingToTakeAway = self.getUsersRemainingPointsToTakeToday(ctx.author.id)
|
||||
if points > remainingToTakeAway: # The limit per day is 10
|
||||
await self.sendErrorDm(ctx, "Je mag vandaag nog maar " + str(remainingToTakeAway) + " punten wegnemen.")
|
||||
return
|
||||
|
||||
userObj = ctx.message.mentions[0]
|
||||
|
||||
if not self.isUserOnList(userObj):
|
||||
await ctx.channel.send("Nee.")
|
||||
return
|
||||
if self.getUserBalance(userObj) < points:
|
||||
await ctx.channel.send(userObj.name + " mag niet rood staan.")
|
||||
return
|
||||
|
||||
# Execute the transaction:
|
||||
self.execute_neempunten(ctx.author.id, userObj.id, points);
|
||||
|
||||
self.savePointsCount()
|
||||
|
||||
message = self.getMessageForTakingPoints(userObj.name, ctx.author.name, points)
|
||||
await ctx.channel.send(message)
|
||||
|
||||
def execute_neempunten(self, takerId, victimId, points):
|
||||
self.increaseUsersPointTakenOnDate(takerId, points)
|
||||
self.transferPoints(victimId, self.BANK_ID, points)
|
||||
|
||||
|
||||
@commands.command(pass_context=True, hidden=False)
|
||||
async def puntentelling(self, ctx):
|
||||
"""Hoeveel punten heeft iedereen?
|
||||
"""
|
||||
|
||||
self.reloadPointsCount()
|
||||
|
||||
message = "**De puntentelling:** \n```"
|
||||
pointsCountSorted = sorted(self.pointsCount.items(), key=lambda i: i[1]['points'], reverse=True)
|
||||
for user in pointsCountSorted:
|
||||
if user[0] != self.BANK_ID:
|
||||
message += str(user[1]["points"]).rjust(4) + " " + user[1]["name"] + "\n"
|
||||
message += str(self.pointsCount[self.BANK_ID]["points"]).rjust(4) + " " + self.pointsCount[self.BANK_ID]["name"] + "```"
|
||||
await ctx.channel.send(message)
|
||||
|
||||
|
||||
# No public shaming. Send somebody a direct correction message.
|
||||
async def sendErrorDm(self, ctx, message):
|
||||
try:
|
||||
await ctx.message.delete()
|
||||
except:
|
||||
print("No permission to delete message")
|
||||
try:
|
||||
await ctx.message.author.send(message)
|
||||
except:
|
||||
print("No permission to send DM")
|
||||
|
||||
|
||||
# Get the points count object from the file
|
||||
def reloadPointsCount(self):
|
||||
self.pointsCount = np.load('pointscount.npy', allow_pickle=True).item()
|
||||
|
||||
# Save the points count to the file
|
||||
def savePointsCount(self):
|
||||
np.save("pointscount.npy", self.pointsCount)
|
||||
|
||||
# Transfer points form one user to another
|
||||
def transferPoints(self, fromUserId, toUserId, points):
|
||||
self.pointsCount[fromUserId]["points"] -= points
|
||||
self.pointsCount[toUserId]["points"] += points
|
||||
|
||||
# Do we know this user?
|
||||
def isUserOnList(self, user):
|
||||
return user.id in self.pointsCount.keys()
|
||||
|
||||
# Get a user's point balance
|
||||
def getUserBalance(self, user):
|
||||
return self.pointsCount[user.id]["points"]
|
||||
|
||||
# Get the balance of the bank
|
||||
def getBankBalance(self):
|
||||
return self.pointsCount[self.BANK_ID]["points"]
|
||||
|
||||
# To keep track if a user used some points today, we look at when the last time was he/she used them
|
||||
# If this was in the past: reset
|
||||
# Also, return the updated object. Why not.
|
||||
def refreshDateVarsAndReturnUserVars(self, userId):
|
||||
currentDateStr = datetime.now().strftime("%Y%m%d")
|
||||
if self.pointsCount[userId]["theDate"] != currentDateStr:
|
||||
self.pointsCount[userId]["theDate"] = currentDateStr
|
||||
self.pointsCount[userId]["pointTakenOnDate"] = 0
|
||||
self.pointsCount[userId]["bankPointsGivenOnDate"] = 0
|
||||
return self.pointsCount[userId]
|
||||
|
||||
# How many points can this user still take away today?
|
||||
def getUsersRemainingPointsToTakeToday(self, userId):
|
||||
userInfo = self.refreshDateVarsAndReturnUserVars(userId)
|
||||
return 10 - userInfo["pointTakenOnDate"]
|
||||
|
||||
# How many bank points can this user still give away?
|
||||
def getUsersRemainingBankPointsToGiveAwayToday(self, userId):
|
||||
userInfo = self.refreshDateVarsAndReturnUserVars(userId)
|
||||
return 10 - userInfo["bankPointsGivenOnDate"]
|
||||
|
||||
# Increase the number of points this user has taken away today.
|
||||
# Warning: assumes you executed refreshDateVarsAndReturnUserVars()
|
||||
def increaseUsersPointTakenOnDate(self, userId, points):
|
||||
self.pointsCount[userId]["pointTakenOnDate"] += points
|
||||
|
||||
# Increase the number of bank points this user has given today
|
||||
# Warning: assumes you executed refreshDateVarsAndReturnUserVars()
|
||||
def increaseUsersBankPointGivenAwayToday(self, userId, points):
|
||||
self.pointsCount[userId]["bankPointsGivenOnDate"] += points
|
||||
|
||||
|
||||
# Generate a semi-random text to tell somebody they got some shiny new points
|
||||
def getMessageForAwardingPoints(self, userNameFrom: str, userNameTo: str, points: int):
|
||||
p = str(points)
|
||||
|
||||
if points == 1:
|
||||
grammarFixer = {"suffixGb":"", "suffixNl":"", "zijnOfIs": "is"}
|
||||
else:
|
||||
grammarFixer = {"suffixGb":"s", "suffixNl":"en", "zijnOfIs": "zijn"}
|
||||
|
||||
messages = [
|
||||
p + " punt" + grammarFixer["suffixNl"] + " voor " + userNameTo + ".",
|
||||
userNameTo + " krijgt " + p + " punt" + grammarFixer["suffixNl"] + ".",
|
||||
userNameTo + " krijgt " + p + " punt" + grammarFixer["suffixNl"] + " van " + userNameFrom,
|
||||
p + " POINT" + grammarFixer["suffixGb"].upper() + " TO GRYFFINDO.. oh.. " + userNameTo + ".",
|
||||
userNameTo + ", jij krijgt " + p + " puntje" + grammarFixer["suffixGb"] + " van " + userNameFrom + ". Lief he? :heart:",
|
||||
"+" + p + " punt" + grammarFixer["suffixNl"] + " voor " + userNameTo + "! Highscore!",
|
||||
userNameTo + ", alsjeblieft, " + p + " punt" + grammarFixer["suffixNl"] + ".",
|
||||
"Hier " + grammarFixer["zijnOfIs"] + " " + p + " punt" + grammarFixer["suffixNl"] + ", " + userNameTo + ". Don't spend it all in one place...",
|
||||
"Jij kan wel " + p + " punt" + grammarFixer["suffixNl"] + " gebruiken, " + userNameTo + ".",
|
||||
p + " blockchain smartcontract punt" + grammarFixer["suffixNl"] + " voor " + userNameTo + ". :rocket: "
|
||||
]
|
||||
return messages[random.randint(0, len(messages)-1)]
|
||||
|
||||
# Generate a semi-random text to tell somebody they just lost their precious points
|
||||
def getMessageForTakingPoints(self, userNameFrom: str, userNameTaker: str, points: int):
|
||||
p = str(points)
|
||||
|
||||
if points == 1:
|
||||
grammarFixer = {"suffixGb":"", "suffixNl":"", "gaatOfGaan":"gaat"}
|
||||
else:
|
||||
grammarFixer = {"suffixGb":"s", "suffixNl":"en", "gaatOfGaan":"gaan"}
|
||||
|
||||
messages = [
|
||||
userNameFrom + " verliest " + p + " punt" + grammarFixer["suffixNl"] + ".",
|
||||
userNameFrom + " is " + p + " punt" + grammarFixer["suffixNl"] + " kwijt. F.",
|
||||
userNameTaker + " vindt dat jij " + p + " punt" + grammarFixer["suffixNl"] + " moet kwijtraken, " + userNameFrom + ".",
|
||||
p + " POINT" + grammarFixer["suffixGb"].upper() + " FROM HUFFELPU.. oh.. " + userNameFrom + ".",
|
||||
"Je bent " + p + " punt" + grammarFixer["suffixNl"] + " armer geworden, " + userNameFrom + ".",
|
||||
"Je hebt toch genoeg, " + userNameFrom + ". We halen " + p + " punt" + grammarFixer["suffixNl"] + " weg.",
|
||||
userNameTaker + " haalt " + p + " punt" + grammarFixer["suffixNl"] + " weg bij " + userNameFrom + ". Wat een lul.",
|
||||
p + " punt" + grammarFixer["suffixNl"] + " " + grammarFixer["gaatOfGaan"] + " van " + userNameFrom + " naar de bank."
|
||||
]
|
||||
return messages[random.randint(0, len(messages)-1)]
|
||||
|
||||
|
||||
def init(self):
|
||||
# Check if points file exists:
|
||||
try:
|
||||
pointsCount = np.load('pointscount.npy', allow_pickle=True).item()
|
||||
except FileNotFoundError:
|
||||
np.save("pointscount.npy", {})
|
||||
pointsCount = np.load('pointscount.npy', allow_pickle=True).item()
|
||||
|
||||
# Initialise the bank:
|
||||
if self.BANK_ID not in pointsCount.keys():
|
||||
pointsCount[self.BANK_ID] = {"name": '"De Bank"', "points": 300}
|
||||
np.save("pointscount.npy", pointsCount)
|
||||
|
||||
# Add new/unknown members:
|
||||
list_channel = self.bot.get_channel(int(os.getenv('STROOP_CHANNEL_SHITPOST')))
|
||||
memberList = list_channel.members if list_channel else []
|
||||
for member in memberList:
|
||||
# Give new members 100 points
|
||||
if member.id not in pointsCount.keys() and not member.bot:
|
||||
pointsCount[member.id] = {"name": member.name, "points": 100, "pointTakenOnDate":0, "bankPointsGivenOnDate":0, "theDate":"20181231"}
|
||||
np.save("pointscount.npy", pointsCount)
|
||||
+30
-23
@@ -16,6 +16,7 @@ class Shitpost(commands.Cog):
|
||||
def __init__(self, bot):
|
||||
self.bot = bot
|
||||
self.hdConImpatientEvents = []
|
||||
self.userAgent = 'Mozilla/5.0 (X11; Linux x86_64; rv:136.0) Gecko/20100101 Firefox/136.0'
|
||||
try:
|
||||
with open('black.txt') as zwart:
|
||||
self.zwarte_lijst = [line.rstrip('\n') for line in zwart]
|
||||
@@ -40,33 +41,36 @@ class Shitpost(commands.Cog):
|
||||
'zout': '116231806'
|
||||
}
|
||||
warnings.simplefilter("ignore")
|
||||
datestring = os.getenv('STROOP_HDCON_DATE') or None
|
||||
self.HdConDate = None
|
||||
if datestring:
|
||||
self.HdConDate = datetime.fromisoformat(datestring)
|
||||
|
||||
@commands.command(pass_context=True, hidden=False)
|
||||
async def ishetalhdcon(self, ctx):
|
||||
"""Hoe lang nog tot Hoestende Draken Con 2023?
|
||||
"""Hoe lang nog tot Hoestende Draken Con dit jaar? Of is het pas volgend jaar?
|
||||
Gebruik: !ishetalhdcon
|
||||
"""
|
||||
|
||||
Now = datetime.now()
|
||||
HdConDate = datetime(2023, 10, 20, 4, 0, 1) #om 4 uur lig je toch wel al op bed?
|
||||
Distance = HdConDate - Now
|
||||
Message = Message = "HD Con 2023 is al voorbij. HD Con 2024 zal in 2024 plaatsvinden."
|
||||
if Distance.days == -1:
|
||||
Message = "HD Con 2023 begint vandaag! HYPE!"
|
||||
elif Distance.days < 0 and Distance.days > -4:
|
||||
Message = "HD Con 2023 is nu bezig!!"
|
||||
elif Distance.days == -4:
|
||||
Message = "HD Con 2023 is vandaag alweer afgelopen... F"
|
||||
Message = f"Geen HD Con! >:|"
|
||||
if self.HdConDate:
|
||||
Message = f"HD Con {self.HdConDate.year} "
|
||||
Distance = self.HdConDate - Now
|
||||
if Distance.days == -1:
|
||||
Message += "begint vandaag! HYPE!"
|
||||
elif Distance.days < 0 and Distance.days > -4:
|
||||
Message += "is nu bezig!!"
|
||||
elif Distance.days == -4:
|
||||
Message += "is vandaag afgelopen :(\nWe hebben gelachen, we hebben gehuild. Het was gezellig. Volgend jaar bij mij."
|
||||
else: # distance < -4
|
||||
Message += f"is geweest. HD Con {self.HdConDate.year+1} zal komen."
|
||||
|
||||
if Distance.days < 0:
|
||||
await ctx.channel.send(ctx.author.mention + ' ' + str(Message))
|
||||
return
|
||||
if Distance.days < 0:
|
||||
await ctx.channel.send(ctx.author.mention + ' ' + str(Message))
|
||||
return
|
||||
|
||||
NachtjesSlapen = Distance.days + 1
|
||||
if NachtjesSlapen == 1:
|
||||
Message = "Nog " + str(NachtjesSlapen) + " nachtje slapen..."
|
||||
else:
|
||||
Message = "Nog " + str(NachtjesSlapen) + " nachtjes slapen..."
|
||||
NachtjesSlapen = Distance.days + 1
|
||||
Message = f"Nog {NachtjesSlapen} nachtje{'s' if NachtjesSlapen > 1 else ''} slapen..."
|
||||
|
||||
#Hou bij hoe vaak dit wordt gevraagd:
|
||||
eventsMinutesAgo = 0;
|
||||
@@ -94,14 +98,14 @@ class Shitpost(commands.Cog):
|
||||
return
|
||||
#Hoe vaker er wordt gevraagd, hoe ongeduldiger de antwoorden:
|
||||
if not "DMChannel" in type(ctx.channel).__name__: #ignore personal chats
|
||||
impatientFactor = 10 + eventsMinutesAgo*25 + eventsLastDays*10;
|
||||
impatientFactor = 10 + eventsMinutesAgo*25 + min(10, eventsLastDays)*2;
|
||||
impatientFactor *= random.random()
|
||||
if impatientFactor > 100:
|
||||
await ctx.channel.send("Nee!")
|
||||
return
|
||||
elif impatientFactor > 15 and eventsMinutesAgo > 0:
|
||||
Message = "Dat hebben jullie net gevraagd."
|
||||
elif impatientFactor > 9:
|
||||
elif impatientFactor > 12:
|
||||
Message = "Nee."
|
||||
|
||||
await ctx.channel.send(ctx.author.mention + ' ' + str(Message))
|
||||
@@ -808,7 +812,10 @@ class Shitpost(commands.Cog):
|
||||
|
||||
def get_zaagmans(self):
|
||||
zaagman_url = "http://iszaagmansallangsgeweest.nl/"
|
||||
zreq = requests.get(zaagman_url)
|
||||
headers = {
|
||||
'User-Agent': self.userAgent,
|
||||
}
|
||||
zreq = requests.get(zaagman_url, headers=headers)
|
||||
if zreq:
|
||||
return zreq.text.partition("<h1>")[2].partition("</h1>")[0]
|
||||
else:
|
||||
@@ -823,4 +830,4 @@ class Shitpost(commands.Cog):
|
||||
message += gezaagd
|
||||
else:
|
||||
message += "De waarheid over zaagmans is niet te doorgronden."
|
||||
await ctx.channel.send(message)
|
||||
await ctx.channel.send(message)
|
||||
@@ -29,6 +29,21 @@ intents.members = True
|
||||
|
||||
bot = commands.Bot(command_prefix=commands.when_mentioned_or('!'), description='Stroopwafel. Shitpost bot extraordinaire.', pm_help=True, intents=intents)
|
||||
|
||||
@bot.event
|
||||
async def on_command_error(ctx, error):
|
||||
if isinstance(error, commands.BadArgument):
|
||||
await ctx.send(f"{ctx.author.mention} Onheus gebruik van het commando. Lees de docs nog eens door:")
|
||||
await ctx.send_help(ctx.command)
|
||||
return
|
||||
if isinstance(error, commands.MissingRequiredArgument):
|
||||
await ctx.send(f"{ctx.author.mention} Volgens bij ben je nog iets vergeten toe te voegen aan dit commando. Lees de docs nog eens door:")
|
||||
await ctx.send_help(ctx.command)
|
||||
return
|
||||
if isinstance(error, commands.CommandNotFound):
|
||||
await ctx.send(f"{ctx.author.mention} Vermoedelijk bedoelde je iets anders. Typ !help voor alle opties.")
|
||||
return
|
||||
raise error
|
||||
|
||||
@bot.event
|
||||
async def on_ready():
|
||||
await add_cogs(bot)
|
||||
|
||||
@@ -14,3 +14,4 @@ STROOP_IMGFLIP_PASSWORD=
|
||||
STROOP_RESET_PASSWORD=
|
||||
STROOP_CHANNEL_SHITPOST=
|
||||
STROOP_CHANNEL_BELANGRIJK=
|
||||
STROOP_HDCON_DATE=2025-12-01
|
||||
@@ -3,3 +3,6 @@ discord.py
|
||||
praw
|
||||
numpy
|
||||
python-dotenv
|
||||
feedparser
|
||||
audioop-lts
|
||||
vobject
|
||||
+2
-2
@@ -41,9 +41,9 @@ class TestGeneral(unittest.TestCase):
|
||||
if not isinstance(self.cog.r, praw.Reddit):
|
||||
self.skipTest("PRAW Reddit instance failed to create")
|
||||
post = self.cog.get_kopieerpasta()
|
||||
self.assertIsInstance(post.url, str)
|
||||
if post:
|
||||
self.assertIsInstance(post.url, str)
|
||||
|
||||
def test_huge(self):
|
||||
embed = self.cog.get_emoji_embed("<:test:123456789>")
|
||||
self.assertIsInstance(embed, discord.Embed)
|
||||
|
||||
Reference in new issue
Block a user