55 Commits
Author SHA1 Message Date
mark 2ebde2e4db Merge pull request 'add limerick functionaliteit #5' (#39) from limericks into master
Reviewed-on: #39
Reviewed-by: Mark Hoekveen <mark@hoekveen.net>
2026-10-24 23:14:55 +02:00
guus 65088fc69d fix rijmuitgang regex van iter naar search 2026-10-24 23:12:23 +02:00
guus 002be0b882 fix whitespace en limerick functies achter haiku gezet 2026-10-24 22:55:53 +02:00
guus 8517f544d5 add limerick functionaliteit #5 2026-10-24 19:27:39 +02:00
mark 925e908865 Merge pull request 'geefpunten flexibele parameters - fixes #4' (#38) from points-parameters into master
Reviewed-on: #38
Reviewed-by: Mark Hoekveen <mark@hoekveen.net>
2026-10-11 13:42:12 +02:00
guus ce23527eee fix #4 nu ook voor neempunten 2026-10-10 17:43:57 +02:00
guus 84287234e2 geefpunten flexibele parameters - fixes #4 2026-10-10 00:39:10 +02:00
guus 56f90e7829 Merge pull request 'add better user error handling' (#37) from user-error-handling into master
Reviewed-on: #37
Reviewed-by: Mark Hoekveen <mark@hoekveen.net>
2026-10-08 22:31:10 +02:00
guus 38877451c5 add better user error handling 2026-10-08 18:29:46 +02:00
mark b3efbaa291 Merge pull request 'beleefdheid' (#36) from beleefd into master
continuous-integration/drone/push Build is failing
Reviewed-on: #36
2026-08-03 21:49:26 +02:00
mark 896bc3afd7 belefd
continuous-integration/drone/push Build is failing
2026-08-03 21:49:18 +02:00
mark 99513b16d4 Merge pull request 'De grote kankerhomo update' (#35) from kankerhomo into master
continuous-integration/drone/push Build is failing
Reviewed-on: #35
2026-08-03 21:43:16 +02:00
mark cc7a5f2f28 adds kankerhomo to insult
continuous-integration/drone/push Build is failing
2026-08-03 21:39:20 +02:00
mark c919386fcb muzak
continuous-integration/drone/push Build is failing
2025-08-12 09:56:23 +02:00
mark 9d00b319aa update drone config to 3.13
continuous-integration/drone/push Build is passing
2025-07-13 15:25:09 +02:00
mark 3b9ac14719 fixt hopelijk build issues
continuous-integration/drone/push Build is failing
continuous-integration/drone Build is failing
maar garanties heb je alleen in de hemel. ofzo.
2025-07-13 15:22:42 +02:00
jp d6bc6327a2 iets minder sass in ishetalhdcon
continuous-integration/drone Build is failing
2025-07-13 14:10:43 +02:00
mark 916a45715b adds audioop requirement 2025-04-10 11:03:50 +02:00
mark 3f5fc17833 adds useragent to zaagmans request 2025-04-10 11:03:18 +02:00
mark 29da1d218b fixes muzak date nachtjes slapen
continuous-integration/drone/push Build is passing
continuous-integration/drone Build is failing
hopelijk. wie weet. lmao @ testen
2024-08-02 23:45:10 +02:00
mark 07d22768fe hdcon date fix
continuous-integration/drone/push Build is passing
2024-07-27 10:30:00 +02:00
mark 392e19f4b3 Datetime support and updates for muzak endpoint
continuous-integration/drone/push Build is passing
Now supports ISO date. Hardcoded at UTC+2.
2024-07-26 13:34:02 +02:00
mark 9852f21ef7 Merge branch 'master' of git.hoekveen.net:mark/stroopwafel 2024-02-29 12:27:55 +01:00
mark 41c2dc17d1 Fixes pollen
Welke klapmongool heeft dat parsen in een one-liner gedaan? Man man man.
2024-02-29 12:26:35 +01:00
mark d1a699ee46 vijf minuten NOS timer
continuous-integration/drone/push Build is passing
2023-12-08 20:43:13 +01:00
mark acbe8c6110 adds feedparser to requirements
continuous-integration/drone Build is passing
2023-12-07 09:27:37 +01:00
mark a53598b2c3 Voorkomt nos reposts. fixes #28 2023-12-06 21:51:59 +01:00
mark be6380d6b8 nos 2023-12-03 12:45:08 +01:00
mark 527164a040 nachtjes slapen en url
continuous-integration/drone/push Build is passing
2023-08-16 16:56:40 +02:00
mark f76f7a48c9 Merge pull request 'Nieuw muzak eindpunt.' (#27) from muzak into master
continuous-integration/drone/push Build is passing
Reviewed-on: #27
2023-08-16 16:08:13 +02:00
mark a2319f0fac oeps 2023-08-16 14:54:35 +02:00
mark a4ca645e3e nieuw muzak eindpunt 2023-08-16 14:53:10 +02:00
mark acb9df8616 hdcon2023 bitchesss 2023-08-02 14:25:40 +02:00
mark 1f848861e3 stroop scheldt je niet meer uit als je hem pingt.
want het was eigenlijk al een aardige tijd niet echt heel grappig meer.
2023-07-26 20:02:10 +02:00
jp ecc3ae8853 Merge pull request 'updates crypto module with newer async code' (#25) from crypto-update into master
continuous-integration/drone/push Build is passing
Reviewed-on: #25
2023-06-25 21:24:51 +02:00
mark e904451037 updates crypto module with newer async code
continuous-integration/drone/push Build is passing
2023-06-23 21:56:52 +02:00
mark cde205aad7 pollen klachtencijfer
continuous-integration/drone Build is passing
continuous-integration/drone/push Build is passing
2023-06-13 21:05:22 +02:00
mark 2e91781fad robustness of gpt calls
continuous-integration/drone/push Build is passing
2023-03-19 13:57:51 +01:00
jp 58ce3a8565 Merge pull request '10% kans op nieuwe GPT' (#24) from gpt into master
continuous-integration/drone/push Build is passing
Reviewed-on: #24
2023-03-18 23:42:06 +01:00
mark cf89809c30 fallback to local on error
continuous-integration/drone/push Build is passing
2023-03-18 23:37:42 +01:00
jp 301314bec8 fixes regression for mentions
continuous-integration/drone/push Build is passing
2023-03-18 23:25:17 +01:00
mark a142b299f4 haal channels uit dotenv
continuous-integration/drone/push Build is passing
2023-03-18 23:01:11 +01:00
mark a80ac831f0 fixes regression for reageer
continuous-integration/drone/push Build is passing
2023-03-18 22:48:36 +01:00
mark 4f55dd9dd6 10% kans op nieuwe GPT
continuous-integration/drone/push Build is passing
2023-03-18 17:48:36 +01:00
mark 2baa32055d Merge pull request 'zaagmans' (#23) from zaagmans into master
continuous-integration/drone/push Build is passing
Reviewed-on: #23
2023-03-02 11:56:33 +01:00
mark 08f99b856a whatever gewoon de message van de site overnemen ofzo
continuous-integration/drone/push Build is passing
2023-03-02 11:54:13 +01:00
mark 23e4a30e14 test zaagmans
continuous-integration/drone/push Build is failing
2023-02-16 00:10:51 +01:00
mark 9e2389b9b0 zaagmans functie 2023-02-16 00:10:42 +01:00
mark 2d58948e78 Merge pull request 'Update code om Python 3.11 te ondersteunen' (#22) from python311 into master
continuous-integration/drone/push Build is passing
Reviewed-on: #22
2022-12-28 17:57:24 +01:00
mark 1adc2096a0 fix voor verkeerde url
continuous-integration/drone/push Build is passing
2022-12-27 22:10:17 +01:00
mark 904f1c48ea Fixes untested bug in tegeltje
continuous-integration/drone/push Build is passing
2022-12-18 02:04:58 +01:00
mark f8db215b31 Replaces asyncio coroutines with native async
Replaces @asyncio.coroutine decorator with async
Replaces yield from with await
2022-12-18 02:03:46 +01:00
mark ad2324d53c Fixes random seed required value 2022-12-18 02:03:09 +01:00
mark 1c3318c24c Setup testing environments for python 3.11 2022-12-18 01:59:01 +01:00
jp 9effd126dd Merge pull request 'Testing/CI' (#21) from testing into master
continuous-integration/drone/push Build is passing
Reviewed-on: #21
2022-12-11 16:27:21 +01:00
12 changed files with 630 additions and 219 deletions

No files matched your search

+1 -1
View File
@@ -3,7 +3,7 @@ name: default
steps:
- name: test
image: python:3.10
image: python:3.13
environment:
STROOP_DISCORD_TOKEN:
from_secret: STROOP_DISCORD_TOKEN
+368 -46
View File
@@ -1,8 +1,12 @@
import asyncio
import discord
from discord.ext import commands
import numpy as np
import random
import requests
import asyncio
import os
import feedparser
import json
from datetime import datetime
import re
@@ -16,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:
@@ -24,60 +30,61 @@ 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
@asyncio.coroutine
def on_message(message):
async def on_message(message):
if message.author.bot:
return #ignore your own messages, Stroop
if message.content.strip() == "" or message.content.strip()[0] != '!': #don't respond to a command
if message.content.lower() == "nihao":
yield from message.channel.send("kankerlauw")
await message.channel.send("kankerlauw")
return
if message.content.lower() == "lol":
yield from message.channel.send("laffing aut laut")
await message.channel.send("laffing aut laut")
return
if self.bot.user.mentioned_in(message) and "@everyone" not in message.content:
MENTIONED_RESPONSES = [
"Hoi",
"hmm?",
"JA WAT?",
"Godve...Godver-fucking-domme! Wie de fuck heeft me zojuist gepingt? Wie de fuck heeft de ballen om mij te pingen?! Als ik jou vind hè, ik ram je helemaal de tyfus in. Ik ga je kapot maken. Welke breincel in jouw hoofd dacht dat het grappig was om mij te pingen? Noem jij dat 'grappig'? Ik zal je godverdomme iets laten zien wat grappig is, ja. Ik neuk je moeder zo hard dat ze van me gaat houden, godverdomme. Dat krijg je er van als je me pingt, vuile teringleijer. Jouw soort mag wat mij betreft uitsterven. Weet je, ik ga je helemaal geen aandacht meer geven. Je mag de tering krijgen, en daar blijft het bij. Kutjong.",
self.getResponseForMessage("stroopwafel")
self.getResponseForMessageLocal("stroopwafel")
]
try:
MENTIONED_RESPONSES.append("Wat mot je, " + random.choice(self.bot.get_cog("Shitpost").insult) + "?")
except:
print("ERROR! - Could not import insults")
yield from message.channel.send(random.choice(MENTIONED_RESPONSES))
await message.channel.send(random.choice(MENTIONED_RESPONSES))
return
if re.match("^[0-9]+([,.]?[0-9]+)*?$", message.content.strip()) and random.randint(0,9) == 0:
yield from message.channel.send("That's Numberwang!") # https://www.youtube.com/watch?v=0obMRztklqU
await message.channel.send("That's Numberwang!") # https://www.youtube.com/watch?v=0obMRztklqU
return
if "DMChannel" in type(message.channel).__name__: #respond to messages in PM channels
if (self.isAllowedToLearnFromPm(message)): #avoid spam-learning
self.pmCount += 1
self.pmLast = datetime.now()
yield from self.learnFromMessagesInChannel(message.channel, 1)
yield from self.respondToMessage(message)
elif message.channel.id == self.bot.hdChannels["belangrijk"]: #don't abuse the "belangrijk" channel
pass
await self.learnFromMessagesInChannel(message.channel, 1)
await self.respondToMessage(message)
else:
a = random.randint(0,999) # probablity
if a < 40:
yield from self.learnFromMessagesInChannel(message.channel, 10)
await self.learnFromMessagesInChannel(message.channel, 10)
if "stroop" in message.content.lower():
a = a / 20 # significantly increase the chance of responding if somebody talks about him.
if message.channel.id == self.bot.hdChannels["shitpost"] and a < 40: #shitpost channel
yield from self.respondToMessage(message)
if message.channel.id == os.getenv('STROOP_CHANNEL_SHITPOST') and a < 40: #shitpost channel
await self.respondToMessage(message)
elif a < 10: #all other channels
yield from self.respondToMessage(message)
await self.respondToMessage(message)
#process commands:
yield from self.bot.process_commands(message)
await self.bot.process_commands(message)
def __check(self, ctx):
return True
@@ -183,22 +190,20 @@ class Chatbot(commands.Cog):
@commands.command(pass_context=True, hidden=True)
@asyncio.coroutine
def trainmarkovchat(self, ctx, channelId=409751773595566081, nrOfMessages=50):
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)
yield from self.learnFromMessagesInChannel(channel, nrOfMessages)
await self.learnFromMessagesInChannel(channel, nrOfMessages)
yield from ctx.channel.send("Ik heb weer wat nieuwe woordjes geleerd. :slight_smile:")
await ctx.channel.send("Ik heb weer wat nieuwe woordjes geleerd. :slight_smile:")
#Learns from an x number of messages from a certain channel
@asyncio.coroutine
def learnFromMessagesInChannel(self, channel, nrOfMessages):
async def learnFromMessagesInChannel(self, channel, nrOfMessages):
#Open current chain:
wordDict = np.load('markov_dict.npy', allow_pickle=True).item()
@@ -207,7 +212,7 @@ class Chatbot(commands.Cog):
messageIterator = channel.history(limit=nrOfMessages, before=None, after=None, oldest_first=False, around=None)
allMessages = []
for i in range(nrOfMessages):
msg = yield from anext(messageIterator)
msg = await anext(messageIterator)
allMessages.append(msg)
i = 0
@@ -225,6 +230,11 @@ 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:
@@ -248,18 +258,17 @@ class Chatbot(commands.Cog):
@commands.command(pass_context=True, hidden=False)
@asyncio.coroutine
def reageer(self, ctx):
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 = yield from anext(messageIterator) #this will be the !reageer command. skip
messageToRespondTo = yield from anext(messageIterator)
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 = yield from anext(messageIterator) #but it's not a huge problem if he responds to himself
messageToRespondTo = await anext(messageIterator) #but it's not a huge problem if he responds to himself
if messageToRespondTo.content.strip()[0] == '!':
wordsToRespondTo = []
else:
@@ -268,12 +277,12 @@ class Chatbot(commands.Cog):
#Delete command
try:
yield from ctx.message.delete()
await ctx.message.delete()
except:
pass
response = self.getResponseForMessage(wordsToRespondTo)
yield from ctx.channel.send(response)
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
@@ -285,15 +294,41 @@ class Chatbot(commands.Cog):
#Respond to a message.
#Assumes the message isn't a command
@asyncio.coroutine
def respondToMessage(self, message):
async def respondToMessage(self, message):
wordsToRespondTo = message.content.strip().split()
response = self.getResponseForMessage(wordsToRespondTo)
yield from message.channel.send(response)
response = await self.getResponseForMessage(wordsToRespondTo)
await message.channel.send(response)
#Gets a response
def getResponseForMessage(self, wordsToRespondTo):
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)
if response:
return response # Anders door naar local
except:
pass # Door naar local call
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):
MAX_N_WORDS = 100 #Don't use more words than this
@@ -351,7 +386,7 @@ class Chatbot(commands.Cog):
chain[n] = "@jemoeder"
#print(' '.join(chain))
#yield from ctx.channel.send(' '.join(chain))
#await ctx.channel.send(' '.join(chain))
return ' '.join(chain)
@@ -424,22 +459,263 @@ class Chatbot(commands.Cog):
return ' '.join(chain)
@commands.command(pass_context=True, hidden=False)
@asyncio.coroutine
def haiku(self, ctx):
async def haiku(self, ctx):
"""Stroop is een poëet. Laat hem een Haiku maken.
"""
response = self.getHaiku()
yield from ctx.channel.send(response)
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)
@asyncio.coroutine
def uitspraak(self, ctx, numPosts=1):
async def uitspraak(self, ctx, numPosts=1):
"""Random uitspraak uit de hall of fame.
Optioneel kan je een nummer meegeven voor meerdere uitspraken
0 voor alle uitspraken."""
try:
yield from ctx.message.delete()
await ctx.message.delete()
except:
pass
try:
@@ -451,6 +727,52 @@ class Chatbot(commands.Cog):
numPosts = len(uitspraken)
for i in range(numPosts):
message += uitspraken[i]
yield from ctx.channel.send(message)
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)
+8 -10
View File
@@ -197,8 +197,7 @@ class Cryptocoin(commands.Cog):
#user functions below
@commands.command(pass_context=True)
@asyncio.coroutine
def coinprice(self, ctx, coinId: str, currencyId: str="USD"):
async def coinprice(self, ctx, coinId: str, currencyId: str="USD"):
"""Geeft de huidige prijs van de desbetreffende crypto currency
Bijv:
!coinprice BTC
@@ -211,20 +210,19 @@ class Cryptocoin(commands.Cog):
currencyId = currencyId.upper()
if (currencyId not in allowedCurrencies):
yield from ctx.channel.send("Valuta " + currencyId + " ken ik niet. :disappointed: ")
await ctx.channel.send("Valuta " + currencyId + " ken ik niet. :disappointed: ")
return
price = self.getCoinPrice(coinId, currencyId)
if (price == -1):
yield from ctx.channel.send("Die cryptocoin ken ik niet... :frowning2: ")
await ctx.channel.send("Die cryptocoin ken ik niet... :frowning2: ")
return
yield from ctx.channel.send(coinId + " is nu " + str(price) + " " + currencyId + " waard.")
await ctx.channel.send(coinId + " is nu " + str(price) + " " + currencyId + " waard.")
@commands.command(pass_context=True)
@asyncio.coroutine
def coinadvice(self, ctx, coinId: str=""):
async def coinadvice(self, ctx, coinId: str=""):
"""Voor al uw adviezen in monopolygeld
Vraag Stroop's mening over een specifieke coin:
!coinadvice NLG
@@ -237,7 +235,7 @@ class Cryptocoin(commands.Cog):
#Geen specieke coin? Doe random.
if(coinId == ""):
yield from ctx.channel.send( self.getRandomCoinAdvice() )
await ctx.channel.send( self.getRandomCoinAdvice() )
return
coinId = coinId.upper()
@@ -245,7 +243,7 @@ class Cryptocoin(commands.Cog):
growPercentage, coinStability, dummy = self.analyseCoin(coinId)
if (growPercentage == 0 and coinStability == 1.0): #aanname. anders moet je weer een extra call doen.
yield from ctx.channel.send("Die cryptocoin ken ik niet... :frowning2: ")
await ctx.channel.send("Die cryptocoin ken ik niet... :frowning2: ")
return
time.sleep(0.1) #don't overload the API
@@ -302,5 +300,5 @@ class Cryptocoin(commands.Cog):
if (coinStability < 0.3):
message += "Denk ik?"
yield from ctx.channel.send(message)
await ctx.channel.send(message)
+1 -1
View File
@@ -1,4 +1,4 @@
FROM python:3.10
FROM python:3.13
WORKDIR /opt/stroopwafel
+54 -23
View File
@@ -1,4 +1,3 @@
import asyncio
import discord
import os
import praw
@@ -6,6 +5,7 @@ import random
import re
import json, requests
import warnings
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://hdcon-muzak.herokuapp.com'
self.muzak_url = 'http://muzak.hoekveen.net:8001'
self.r = praw.Reddit(
user_agent='StroopwafelBot',
client_secret=os.getenv("STROOP_REDDIT_SECRET"),
@@ -23,25 +23,24 @@ 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)
return embed
@commands.command()
@asyncio.coroutine
def huge(self, ctx, *, arg):
async def huge(self, ctx, *, arg):
"""YUGE. Geeft een grote versie van de gegeven emoji terug. Werkt alleen voor custom emoji.
Bijvoorbeeld:
!huge :ancilla:
"""
em = self.get_emoji_embed(arg)
try:
yield from ctx.message.delete()
await ctx.message.delete()
except:
print("No permission to delete message")
yield from ctx.channel.send(ctx.author.mention, embed=em)
await ctx.channel.send(ctx.author.mention, embed=em)
def get_aww_post(self):
raww = self.r.subreddit('aww+catloaf+tuckedinkitties+babyelephantgifs+babybigcatgifs+blep+holdmynip+gingerkitty+cathighfive+catsstandingup+catsareassholes+eyebleach')
@@ -49,32 +48,36 @@ class General(commands.Cog):
return random.choice(listing)
@commands.command(pass_context=True)
@asyncio.coroutine
def aww(self, ctx):
async def aww(self, ctx):
""" iets schattigs... """
post = self.get_aww_post()
try:
yield from ctx.message.delete()
await ctx.message.delete()
except:
print("No permission to delete message")
yield from ctx.channel.send(ctx.author.mention + ' ' + post.url)
await ctx.channel.send(ctx.author.mention + ' ' + post.url)
def get_kopieerpasta(self):
rkopieerpasta = self.r.subreddit('kopieerpasta')
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))
listing = list(rkopieerpasta.top(time_filter='month', limit=250))
post = random.choice(listing)
return post
except:
return None
@commands.command(pass_context=True)
@asyncio.coroutine
def kopieerpasta(self, ctx):
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
@@ -83,23 +86,51 @@ class General(commands.Cog):
print(post.url)
a += 1
try:
yield from ctx.message.delete()
await ctx.message.delete()
except:
print("No permission to delete message")
if len(post.selftext + post.title) < 1990:
yield from ctx.channel.send('**'+post.title+'**```'+post.selftext+'```')
await ctx.channel.send('**'+post.title+'**```'+post.selftext+'```')
else:
yield from ctx.channel.send("Geen kopieerpasta voor jou vandaag.")
await ctx.channel.send("Geen kopieerpasta voor jou vandaag.")
def get_playlist_json(self):
return requests.get(self.muzak_url + '/stroopwafel')
@commands.command(pass_context=True)
@asyncio.coroutine
def playlist(self, ctx):
"""HDcon2021 playlist"""
async def muzak(self, ctx):
"""HD muzak playlist"""
data = json.loads(self.get_playlist_json().content)
msg = 'Stemmen en nomineren kan hier: {}\n'.format(self.muzak_url)
msg += '*Er zijn al {} nummers genomineerd*\n'.format(data['stemCount'])
yield from ctx.channel.send(msg)
msg = ""
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 = "Muwat?"
else:
msg += f"Stemmen en nomineren kan hier: https://muzak.hoekveen.net/ \n"
msg += f"*Er zijn al {data['stemCount']} nummers genomineerd!*\n"
await ctx.channel.send(msg)
@commands.command(pass_context=True)
async def pollen(self, ctx):
"Hoe veel last van pollen kun je verwachten?"
poll = 'https://app.everviz.com/embed/apyvera/' # Thanks hooikoortsradar
response = requests.get(poll)
if response:
# one-liner want eet stront
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!"
elif cijfer < 6:
msg = f"Het lijkt allemaal mee te vallen. Men gaf hun klachten een {cijfer} deze week. Moet te doen zijn."
elif cijfer < 7.5:
msg = f"Ai. Het gaat lekker met de pollen, maar het ergste moet nog komen of is al geweest. Klachtencijfer van {cijfer}; Sterkte alvast."
else:
msg = f"Balen dit. Klachtencijfer van {cijfer}, dus bekijk het maar. Joe."
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')
+67 -39
View File
@@ -1,13 +1,12 @@
import asyncio
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!"""
@@ -24,42 +23,57 @@ class Points(commands.Cog):
def __check(self, ctx):
return True
@commands.command(pass_context=True, hidden=False)
@asyncio.coroutine
def geefpunten(self, ctx, user, points: int):
@commands.command()
async def geefpunten(self, ctx, *args):
"""Wees eens lief. Geef iemand wat punten.
Bijvoorbeeld:
!geefpunten @ikbenjp 42
!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:
yield from ctx.channel.send("0 punten? Gul hoor.")
await ctx.channel.send("0 punten? Gul hoor.")
return
if points < 0:
yield from self.sendErrorDm(ctx, "Daar hebben we de !neempunten functie voor. Voor meer info typ: ```!help neempunten```")
return
if user[0:2] != "<@":
yield from self.sendErrorDm(ctx, "Je moet iemand taggen om punten te geven. :)")
#TODO ook userId oid toestaan?
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:
yield from ctx.channel.send("Nee. Je mag niet jezelf punten geven.")
await ctx.channel.send("Nee. Je mag niet jezelf punten geven.")
time.sleep(0.6)
yield from ctx.channel.send("Gekkie.")
await ctx.channel.send("Gekkie.")
return
if not self.isUserOnList(userObj):
yield from ctx.channel.send("Nee. Die krijgt geen punten.")
await ctx.channel.send("Nee. Die krijgt geen punten.")
return
if self.getUserBalance(ctx.author) < points:
yield from ctx.channel.send("Daar heb jij niet genoeg puntjes voor. :bell:")
await ctx.channel.send("Daar heb jij niet genoeg puntjes voor. :bell:")
return
# Execute the transaction:
@@ -68,7 +82,7 @@ class Points(commands.Cog):
self.savePointsCount()
message = self.getMessageForAwardingPoints(ctx.author.name, userObj.name, points)
yield from ctx.channel.send(message)
await ctx.channel.send(message)
def execute_geefpunten(self, giverId, recieverId, points):
# First, try to give away (at most 10) bankpoints
@@ -85,40 +99,56 @@ class Points(commands.Cog):
self.transferPoints(giverId, recieverId, remainingPointsToGive)
@commands.command(pass_context=True, hidden=False)
@asyncio.coroutine
def neempunten(self, ctx, user, points: int):
@commands.command()
async def neempunten(self, ctx, *args):
"""Tijd om iemand the shamen. Haal wat punten weg.
Bijvoorbeeld:
!neempunten @mark 5
!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:
yield from ctx.channel.send("Volgens mij snap je het niet.")
await ctx.channel.send("Volgens mij snap je het niet.")
return
if points > 10:
yield from self.sendErrorDm(ctx, "Je mag niet meer dan 10 punten afnemen.")
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
yield from self.sendErrorDm(ctx, "Je mag vandaag nog maar " + str(remainingToTakeAway) + " punten wegnemen.")
return
if user[0:2] != "<@":
yield from self.sendErrorDm(ctx, "Je moet iemand taggen. :)")
await self.sendErrorDm(ctx, "Je mag vandaag nog maar " + str(remainingToTakeAway) + " punten wegnemen.")
return
userObj = ctx.message.mentions[0]
if not self.isUserOnList(userObj):
yield from ctx.channel.send("Nee.")
await ctx.channel.send("Nee.")
return
if self.getUserBalance(userObj) < points:
yield from ctx.channel.send(userObj.name + " mag niet rood staan.")
await ctx.channel.send(userObj.name + " mag niet rood staan.")
return
# Execute the transaction:
@@ -127,7 +157,7 @@ class Points(commands.Cog):
self.savePointsCount()
message = self.getMessageForTakingPoints(userObj.name, ctx.author.name, points)
yield from ctx.channel.send(message)
await ctx.channel.send(message)
def execute_neempunten(self, takerId, victimId, points):
self.increaseUsersPointTakenOnDate(takerId, points)
@@ -135,8 +165,7 @@ class Points(commands.Cog):
@commands.command(pass_context=True, hidden=False)
@asyncio.coroutine
def puntentelling(self, ctx):
async def puntentelling(self, ctx):
"""Hoeveel punten heeft iedereen?
"""
@@ -148,18 +177,17 @@ class Points(commands.Cog):
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"] + "```"
yield from ctx.channel.send(message)
await ctx.channel.send(message)
# No public shaming. Send somebody a direct correction message.
@asyncio.coroutine
def sendErrorDm(self, ctx, message):
async def sendErrorDm(self, ctx, message):
try:
yield from ctx.message.delete()
await ctx.message.delete()
except:
print("No permission to delete message")
try:
yield from ctx.message.author.send(message)
await ctx.message.author.send(message)
except:
print("No permission to send DM")
+102 -97
View File
@@ -1,4 +1,3 @@
import asyncio
import discord
from discord.ext import commands
from urllib import request
@@ -17,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]
@@ -41,34 +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)
@asyncio.coroutine
def ishetalhdcon(self, ctx):
"""Hoe lang nog tot Hoestende Draken Con 2022?
async def ishetalhdcon(self, ctx):
"""Hoe lang nog tot Hoestende Draken Con dit jaar? Of is het pas volgend jaar?
Gebruik: !ishetalhdcon
"""
Now = datetime.now()
HdConDate = datetime(2022, 10, 14, 4, 0, 1) #om 4 uur lig je toch wel al op bed?
Distance = HdConDate - Now
Message = Message = "HD Con 2022 is al voorbij. HD Con 2023 zal in 2023 plaatsvinden."
Message = f"Geen HD Con! >:|"
if self.HdConDate:
Message = f"HD Con {self.HdConDate.year} "
Distance = self.HdConDate - Now
if Distance.days == -1:
Message = "HD Con 2022 begint vandaag! HYPE!"
Message += "begint vandaag! HYPE!"
elif Distance.days < 0 and Distance.days > -4:
Message = "HD Con 2022 is nu bezig!!"
Message += "is nu bezig!!"
elif Distance.days == -4:
Message = "HD Con 2022 is vandaag alweer afgelopen... F"
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:
yield from ctx.channel.send(ctx.author.mention + ' ' + str(Message))
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..."
Message = f"Nog {NachtjesSlapen} nachtje{'s' if NachtjesSlapen > 1 else ''} slapen..."
#Hou bij hoe vaak dit wordt gevraagd:
eventsMinutesAgo = 0;
@@ -90,23 +92,23 @@ class Shitpost(commands.Cog):
return #fuck it.
if eventsMinutesAgoSameAuthor > 0:
if eventsMinutesAgoSameAuthor > 2:
yield from ctx.channel.send("...")
await ctx.channel.send("...")
return
yield from ctx.channel.send("Dat vroeg je net ook al, " + ctx.author.mention + "!")
await ctx.channel.send("Dat vroeg je net ook al, " + ctx.author.mention + "!")
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:
yield from ctx.channel.send("Nee!")
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."
yield from ctx.channel.send(ctx.author.mention + ' ' + str(Message))
await ctx.channel.send(ctx.author.mention + ' ' + str(Message))
def zalgofy(self, sentence, factor = 4):
random.seed(datetime.now().timestamp())
@@ -119,8 +121,7 @@ class Shitpost(commands.Cog):
return message
@commands.command(pass_context=True, hidden=False)
@asyncio.coroutine
def zalgo(self, ctx, *, arg):
async def zalgo(self, ctx, *, arg):
"""z̴̬̘͇̗͇̦̤̩̜͜ą̷̟̯̪̩̣̭̭͇̹l̴̗͓̟̠̤̳̗͉̠ͅg̵̜͎̪̞̫͎͈͉͉͍o̵̧̧͇̱̱̜̮͉͉̳ ̴̨̡͖̘̪̭̖͖̘̝h̸̭̰̫̲̺̹̻̜͕ͅe̴̢̘̪̱̱̩̠̣̘̱ ̴̡̢̲̞̙̝̮̻̻͇c̶̡̢̺͙̮̗̲̹̱̱o̷̢̡̺̘͈͎̫̬͔̤m̷͕͍͍̥͖̻̲̞̝ͅe̷̱̟͕̥͕̞̜̫̳̙s̷̨͍̼̝̙̩̥̰̠ͅ
h̷̦̰̣̗̭͕̩͓͈̠i̶̗̰̹̤̖͙̰̹͙̹j̸̧̜̬̬̜̹͔̰̫͜ ̶̧͉͔̠̻͈̜̳̥̭k̸̯̳̠̼̙̗̘̳͜ͅǫ̵̝̱̩͎̫͈̣̪̦m̶̺̙̟̫͔͈̭̖̱ͅt̶̜̠̟͙̞̠̗̗̥ͅ ̸̢̹̜͉͙̩̬̖ͅͅh̷̯̮̘̭͈̜̺͎̳̯i̴̩̯̼̱͇̟̫̻̘̖j̵̪̤̦͖̮̜̦̼̺̮ ̶̧͇̭̞̮̩̼͚̮ͅḵ̴̢̨̢͉͉͖̹̬̺o̵̢̪̥̻͙͕̫̥̗͜m̶̧̡͔̠̺͖̝̳̪ͅt̷̢̮̭̜̥̠̼̫͍̯
d̷̢̪͍͓̭̣̼̠͎̠e̴̡̢̩̱͙̻̥̯͎͜ ̵̲̪͖̖͖͍͈͎̮̼ļ̴̯̗̝̦͍͍͖̰͜i̶̡̘̟̳̖͙͕͔̺͜ȩ̸̤͎̣͖͔̭͔̫̯v̷͔̺͖̖̞̙̘̖̠͓e̶̲͍̮̳͎̗̳̞̹͔ ̸̡̬̫͎͎̝͍̤̯ͅg̴̨̞̻͙̠̰͖͖̝ͅǫ̴̘̥͇̙̖͈͍̹̥e̵̥͇̫̱̬̝̥̲̞̜d̷͈͙̝͍͔̘͕̼̜̦e̴̡̯̦͉͙̪̭͕̻̝
@@ -130,10 +131,10 @@ class Shitpost(commands.Cog):
"""
message = self.zalgofy(arg)
try:
yield from ctx.message.delete()
await ctx.message.delete()
except:
print("No permission to delete message")
yield from ctx.channel.send(str(message))
await ctx.channel.send(str(message))
def get_corona_message(self):
response = requests.get('https://covid.ourworldindata.org/data/latest/owid-covid-latest.json')
@@ -151,18 +152,16 @@ class Shitpost(commands.Cog):
return None
@commands.command(pass_context=True, hidden=False)
@asyncio.coroutine
def corona(self, ctx):
async def corona(self, ctx):
try:
yield from ctx.message.delete()
await ctx.message.delete()
except:
print("No permission to delete message")
message = self.get_corona_message()
yield from ctx.channel.send(ctx.author.mention + ' ' + str(message))
await ctx.channel.send(ctx.author.mention + ' ' + str(message))
@commands.command(pass_context=True, hidden=False)
@asyncio.coroutine
def viertwintig(self, ctx):
async def viertwintig(self, ctx):
"""Hoe lang nog tot 420?
Gebruik: !viertwintig
"""
@@ -188,11 +187,10 @@ class Shitpost(commands.Cog):
seconds = secondsLeft - minutes * 60
Message += "Nog " + str(days) + " dagen, " + str(hours) + " uur, " + str(minutes) + " minuten en " + str(seconds) + " seconden tot 420!!"
yield from ctx.channel.send(ctx.author.mention + ' ' + str(Message))
await ctx.channel.send(ctx.author.mention + ' ' + str(Message))
@commands.command(pass_context=True, hidden=False)
@asyncio.coroutine
def iselderscrolls6aluit(self, ctx):
async def iselderscrolls6aluit(self, ctx):
"""Hoe lang nog tot Elder Scrolls 6? 11-11-11? 20-20-20?
Gebruik: !iselderscrolls6aluit
"""
@@ -203,15 +201,14 @@ class Shitpost(commands.Cog):
else:
Message = "Nee. :frowning2: Nog even geduld..."
yield from ctx.channel.send(ctx.author.mention + ' ' + str(Message))
await ctx.channel.send(ctx.author.mention + ' ' + str(Message))
def get_giet_het_oan(self):
# Alsof we ooit nog een elfstedentocht gaan krijgen.
return "nee"
@commands.command(pass_context=True, hidden=False)
@asyncio.coroutine
def giethetaloan(self, ctx):
async def giethetaloan(self, ctx):
"""Giet het al oan?
Ja of Nee.. kom op nou.
"""
@@ -225,7 +222,7 @@ class Shitpost(commands.Cog):
else:
if 'nee' in answer:
reactie += 'Nee helaas..'
yield from ctx.channel.send(ctx.author.mention + ' ' + reactie)
await ctx.channel.send(ctx.author.mention + ' ' + reactie)
def get_inspiration(self):
inspiration = requests.get(url='http://inspirobot.me/api?generate=true')
@@ -235,8 +232,7 @@ class Shitpost(commands.Cog):
@commands.command(pass_context=True, hidden=False)
@asyncio.coroutine
def inspire(self, ctx):
async def inspire(self, ctx):
"""Laat je inspireren
Bijvoorbeeld:
!inspire
@@ -246,12 +242,12 @@ class Shitpost(commands.Cog):
em = discord.Embed(title='Uw wijze woorden:', type='photo')
em.set_image(url=inspo)
try:
yield from ctx.message.delete()
await ctx.message.delete()
except:
print("No permission to delete message")
yield from ctx.channel.send(ctx.author.mention, embed=em)
await ctx.channel.send(ctx.author.mention, embed=em)
else:
yield from ctx.channel.send(ctx.author.mention + ' helaas, geen quote gevonden.')
await ctx.channel.send(ctx.author.mention + ' helaas, geen quote gevonden.')
def get_imgflip_embed(self, template: str, boven: str, onder: str, extra_options: dict = None):
params = dict(
@@ -273,49 +269,46 @@ class Shitpost(commands.Cog):
@commands.command(pass_context=True, hidden=True)
@asyncio.coroutine
def tering(self, ctx, boven: str, onder: str):
async def tering(self, ctx, boven: str, onder: str):
"""Vanavond gaan we helemaal naar de tering
Bijvoorbeeld:
!tering \"Vanavond\" \"gaan we helemaal naar de tering\"
"""
em = self.get_imgflip_embed(self.imgflips['tering'], boven, onder)
try:
yield from ctx.message.delete()
await ctx.message.delete()
except:
print("No permission to delete message")
if em:
yield from ctx.channel.send(ctx.author.mention, embed=em)
await ctx.channel.send(ctx.author.mention, embed=em)
@commands.command(pass_context=True, hidden=True)
@asyncio.coroutine
def mark(self, ctx, boven: str, onder: str):
async def mark(self, ctx, boven: str, onder: str):
"""Maakt een mark meem.
Bijvoorbeeld:
!mark \"je moeder\" \"is een hoer\"
"""
em = self.get_imgflip_embed(self.imgflips['mark'], boven, onder)
try:
yield from ctx.message.delete()
await ctx.message.delete()
except:
print("No permission to delete message")
if em:
yield from ctx.channel.send(ctx.author.mention, embed=em)
await ctx.channel.send(ctx.author.mention, embed=em)
@commands.command(pass_context=True, hidden=True)
@asyncio.coroutine
def eriku(self, ctx, boven: str, onder: str):
async def eriku(self, ctx, boven: str, onder: str):
"""Maakt een erik meem.
Bijvoorbeeld:
!eriku \"je moeder\" \"is een hoer\"
"""
em = self.get_imgflip_embed(self.imgflips['eriku'], boven, onder)
try:
yield from ctx.message.delete()
await ctx.message.delete()
except:
print("No permission to delete message")
if em:
yield from ctx.channel.send(ctx.author.mention, embed=em)
await ctx.channel.send(ctx.author.mention, embed=em)
def get_tegeltje(self, tekst, auteur):
params = {
@@ -341,43 +334,39 @@ class Shitpost(commands.Cog):
return self.get_imgflip_embed(self.imgflips['tegeltje'], "", "", params)
@commands.command(pass_context=True, hidden=True)
@asyncio.coroutine
def tegeltje(self, ctx, tekst: str, auteur: str=" "):
async def tegeltje(self, ctx, tekst: str, auteur: str=" "):
"""Maak een mooi tegeltje met volkswijsheid
Bijvoorbeeld:
!tegeltje \"Oost west, 420 best\" \"Lourens\"
"""
em = get_tegeltje(tekst, auteur)
em = self.get_tegeltje(tekst, auteur)
try:
yield from ctx.message.delete()
await ctx.message.delete()
except:
print("No permission to delete message")
if em:
yield from ctx.channel.send(ctx.author.mention, embed=em)
await ctx.channel.send(ctx.author.mention, embed=em)
@commands.command(pass_context=True, hidden=True)
@asyncio.coroutine
def zout(self, ctx, boven: str, onder: str):
async def zout(self, ctx, boven: str, onder: str):
"""Maakt een martijn-zout meem.
Bijvoorbeeld:
!zout \"je moeder\" \"is een hoer\"
"""
em = self.get_imgflip_embed(self.imgflips['zout'], boven, onder)
try:
yield from ctx.message.delete()
await ctx.message.delete()
except:
print("No permission to delete message")
if em:
yield from ctx.channel.send(ctx.author.mention, embed=em)
await ctx.channel.send(ctx.author.mention, embed=em)
@commands.command(pass_context=True, hidden=True)
@asyncio.coroutine
def nihao(self,ctx):
yield from ctx.channel.send("kankerlauw")
async def nihao(self,ctx):
await ctx.channel.send("kankerlauw")
@commands.command(pass_context=True)
@asyncio.coroutine
def tijd(self, ctx, *args):
async def tijd(self, ctx, *args):
"""Vertelt je hoe laat het is..
Misschien geeft het ook wel een leuke meem terug.
Wie weet.
@@ -398,20 +387,20 @@ class Shitpost(commands.Cog):
elif os.path.isfile(filepng):
filepath = filepng
try:
yield from ctx.message.delete()
await ctx.message.delete()
except:
print("No permission to delete message")
if filepath != '':
yield from ctx.channel.send(ctx.author.mention + ' Het is nu ' + datetime.now().strftime('%H:%M'), file=discord.File(filepath, 'tijd.png'))
await ctx.channel.send(ctx.author.mention + ' Het is nu ' + datetime.now().strftime('%H:%M'), file=discord.File(filepath, 'tijd.png'))
else:
yield from ctx.channel.send(ctx.author.mention + ' Het is nu ' + datetime.now().strftime('%H:%M'))
await ctx.channel.send(ctx.author.mention + ' Het is nu ' + datetime.now().strftime('%H:%M'))
def get_dice_roll(self, nrOfDice, dieType, modifier=None):
if nrOfDice > 99 or dieType > 9999 or dieType < 2 or (modifier and abs(modifier) > 9999):
return None
# Do the rolling
random.seed(datetime.now())
random.seed(datetime.now().timestamp())
total = 0
rolls = []
for x in range(0, nrOfDice):
@@ -447,8 +436,7 @@ class Shitpost(commands.Cog):
return (numDice, die, modifier)
@commands.command(pass_context=True)
@asyncio.coroutine
def roll(self, ctx, *, dice):
async def roll(self, ctx, *, dice):
"""Roll een dobbelsteen. Of een paar. Bijvoorbeeld:
!roll 4d20
!roll 1d6 + 5
@@ -456,9 +444,9 @@ class Shitpost(commands.Cog):
(nrOfDice, dieType, modifier) = self.get_dice_parameters(dice)
message = self.get_dice_roll(nrOfDice, dieType, modifier)
if message:
yield from ctx.channel.send(message)
await ctx.channel.send(message)
else:
yield from ctx.channel.send("Die roll vind ik echt een beetje te mal..")
await ctx.channel.send("Die roll vind ik echt een beetje te mal..")
def get_weerbericht(self, wData, verbose=None):
if not wData:
@@ -519,8 +507,7 @@ class Shitpost(commands.Cog):
return None
@commands.command(pass_context=True)
@asyncio.coroutine
def weer(self, ctx, location="Leiden", verbose=None):
async def weer(self, ctx, location="Leiden", verbose=None):
"""Vertelt je het weer.
Omdat je te lui bent om naar buiten te kijken.
Oant Moarn!
@@ -530,7 +517,7 @@ class Shitpost(commands.Cog):
message = self.get_weerbericht(wData, verbose)
if not wData or not message:
message = "Weer ophalen niet gelukt. Probeer het later nogmaals.."
yield from ctx.channel.send(message)
await ctx.channel.send(message)
#returns a nice weather icon. Sometimes the API uses non-documented icons, so we return something else
def getWeatherIconTranslation(self, iconKey):
@@ -610,27 +597,25 @@ class Shitpost(commands.Cog):
return zwarte_kaart.replace("___", "**{}**").format(*wit)
@commands.command(pass_context=True)
@asyncio.coroutine
def ktdm(self, ctx, *args):
async def ktdm(self, ctx, *args):
'''Speel Kaarten Tegen De Mensheid! Genereer een kaart of geef zelf opties.
Bijvoorbeeld: !ktdm <"1"><"2"><"3"> (aanbevolen 1 of 2, max 3)'''
try:
yield from ctx.message.delete()
await ctx.message.delete()
except:
print("No permission to delete message")
resultaat = self.get_ktdm(args)
if resultaat:
yield from ctx.channel.send(f"{ctx.author.mention}\n{resultaat}")
await ctx.channel.send(f"{ctx.author.mention}\n{resultaat}")
else:
yield from ctx.channel.send(f"{ctx.author.mention}\nIets ging niet helemaal lekker")
await ctx.channel.send(f"{ctx.author.mention}\nIets ging niet helemaal lekker")
@commands.command(pass_context=True)
@asyncio.coroutine
def beledig(self, ctx, member:discord.User):
async def beledig(self, ctx, member:discord.User):
'''Je vindt iemand stom maar je hebt geen inspiratie? Beledig al je vriendjes met deze handige beledig-i-fier!
Bijvoorbeeld: !beledig @jemoeder'''
yield from ctx.channel.send(member.mention+ ", " + ctx.author.mention + " vindt jou een " + random.choice(self.insult) + "! :angry:")
yield from ctx.message.delete()
await ctx.channel.send(member.mention+ ", " + ctx.author.mention + " vindt jou een " + random.choice(self.insult) + "! :angry:")
await ctx.message.delete()
def get_watspelenwe_cal(self):
"""Geeft een paar terug, met de titel en omschrijving van het eerstvolgende event uit de kalender"""
@@ -749,8 +734,7 @@ class Shitpost(commands.Cog):
return message
@commands.command(pass_context=True)
@asyncio.coroutine
def watspelenwe(self, ctx):
async def watspelenwe(self, ctx):
"""Stroop weet wat we spelen op vrijdag.
Geeft elke week een pseudo-random antwoord.
Geseed op weeknummer + jaar.
@@ -764,10 +748,10 @@ class Shitpost(commands.Cog):
message += ". En wilt iemand even aan Mark vragen of hij de kalender bijhoudt?"
try:
yield from ctx.message.delete()
await ctx.message.delete()
except:
print("No permission to delete message")
yield from ctx.channel.send(message)
await ctx.channel.send(message)
def get_review_string(self, topic = ""):
if topic == "":
@@ -819,10 +803,31 @@ class Shitpost(commands.Cog):
return message
@commands.command(pass_context=True)
@asyncio.coroutine
def review(self, ctx, *args):
async def review(self, ctx, *args):
"""Stroop heeft (bijna) overal een mening over. Vraag het hem!
"""
topic = " ".join(args)
message = self.get_review_string(topic)
yield from ctx.channel.send(message)
await ctx.channel.send(message)
def get_zaagmans(self):
zaagman_url = "http://iszaagmansallangsgeweest.nl/"
headers = {
'User-Agent': self.userAgent,
}
zreq = requests.get(zaagman_url, headers=headers)
if zreq:
return zreq.text.partition("<h1>")[2].partition("</h1>")[0]
else:
return None
@commands.command(pass_context=True)
async def zaagmans(self, ctx):
"""Is zaagmans al langsgeweest? Is de week al doormidden. Wie weet."""
gezaagd = self.get_zaagmans()
message = ctx.author.mention + ": "
if gezaagd:
message += gezaagd
else:
message += "De waarheid over zaagmans is niet te doorgronden."
await ctx.channel.send(message)
+15
View File
@@ -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)
+1
View File
@@ -14,3 +14,4 @@ STROOP_IMGFLIP_PASSWORD=
STROOP_RESET_PASSWORD=
STROOP_CHANNEL_SHITPOST=
STROOP_CHANNEL_BELANGRIJK=
STROOP_HDCON_DATE=2025-12-01
+3
View File
@@ -3,3 +3,6 @@ discord.py
praw
numpy
python-dotenv
feedparser
audioop-lts
vobject
+1 -1
View File
@@ -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()
if post:
self.assertIsInstance(post.url, str)
def test_huge(self):
embed = self.cog.get_emoji_embed("<:test:123456789>")
self.assertIsInstance(embed, discord.Embed)
+9 -1
View File
@@ -3,6 +3,7 @@ import dotenv
import os
import discord
import requests
from datetime import datetime
from discord.ext import commands
import Shitpost
@@ -39,7 +40,7 @@ class TestShitpost(unittest.TestCase):
def test_watspelenwe_cal(self):
data = requests.get(os.getenv('STROOP_CALDAV_CAL'))
if not data:
self.skipTest(f"Server at {self.cog.muzak_url} has an error, or is unavailable")
self.skipTest(f"Server at {os.getenv('STROOP_CALDAV_HOST')} has an error, or is unavailable")
(activiteit, reden) = self.cog.get_watspelenwe_cal()
with self.subTest(msg="Watspelenwe activiteit does not return a string"):
@@ -169,3 +170,10 @@ class TestShitpost(unittest.TestCase):
message = self.cog.zalgofy(inmsg)
self.assertIsInstance(message, str)
self.assertEqual(len(message), len(inmsg)*5)
def test_zaagmans(self):
zaag = self.cog.get_zaagmans()
if zaag is None:
self.skipTest(f"Server at iszaagmansallangsgeweest.nl has an error, or is unavailable")
else:
self.assertIsInstance(zaag, str)