Compare commits
58
Commits
testing
...
e184267eca
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e184267eca | ||
|
|
53fde8c8c5 | ||
|
|
16cf8c673b | ||
|
|
2ebde2e4db | ||
|
|
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 | ||
|
|
a2319f0fac | ||
|
|
a4ca645e3e | ||
|
|
acb9df8616 | ||
|
|
1f848861e3 | ||
|
|
ecc3ae8853 | ||
|
|
e904451037 | ||
|
|
cde205aad7 | ||
|
|
2e91781fad | ||
|
|
58ce3a8565 | ||
|
|
cf89809c30 | ||
|
|
301314bec8 | ||
|
|
a142b299f4 | ||
|
|
a80ac831f0 | ||
|
|
4f55dd9dd6 | ||
|
|
2baa32055d | ||
|
|
08f99b856a | ||
|
|
23e4a30e14 | ||
|
|
9e2389b9b0 | ||
|
|
2d58948e78 | ||
|
|
1adc2096a0 | ||
|
|
904f1c48ea | ||
|
|
f8db215b31 | ||
|
|
ad2324d53c | ||
|
|
1c3318c24c | ||
|
|
9effd126dd |
No files matched your search
+28
-28
@@ -2,34 +2,34 @@ kind: pipeline
|
|||||||
name: default
|
name: default
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: test
|
- name: test
|
||||||
image: python:3.10
|
image: python:3.13
|
||||||
environment:
|
environment:
|
||||||
STROOP_DISCORD_TOKEN:
|
STROOP_DISCORD_TOKEN:
|
||||||
from_secret: STROOP_DISCORD_TOKEN
|
from_secret: STROOP_DISCORD_TOKEN
|
||||||
STROOP_TWITTER_KEY:
|
STROOP_TWITTER_KEY:
|
||||||
from_secret: STROOP_TWITTER_KEY
|
from_secret: STROOP_TWITTER_KEY
|
||||||
STROOP_TWITTER_SECRET:
|
STROOP_TWITTER_SECRET:
|
||||||
from_secret: STROOP_TWITTER_SECRET
|
from_secret: STROOP_TWITTER_SECRET
|
||||||
STROOP_REDDIT_ID:
|
STROOP_REDDIT_ID:
|
||||||
from_secret: STROOP_REDDIT_ID
|
from_secret: STROOP_REDDIT_ID
|
||||||
STROOP_REDDIT_SECRET:
|
STROOP_REDDIT_SECRET:
|
||||||
from_secret: STROOP_REDDIT_SECRET
|
from_secret: STROOP_REDDIT_SECRET
|
||||||
STROOP_WEERLIVE:
|
STROOP_WEERLIVE:
|
||||||
from_secret: STROOP_WEERLIVE
|
from_secret: STROOP_WEERLIVE
|
||||||
STROOP_CALDAV_HOST:
|
STROOP_CALDAV_HOST:
|
||||||
from_secret: STROOP_CALDAV_HOST
|
from_secret: STROOP_CALDAV_HOST
|
||||||
STROOP_CALDAV_CAL:
|
STROOP_CALDAV_CAL:
|
||||||
from_secret: STROOP_CALDAV_CAL
|
from_secret: STROOP_CALDAV_CAL
|
||||||
STROOP_IMGFLIP_PASSWORD:
|
STROOP_IMGFLIP_PASSWORD:
|
||||||
from_secret: STROOP_IMGFLIP_PASSWORD
|
from_secret: STROOP_IMGFLIP_PASSWORD
|
||||||
STROOP_RESET_PASSWORD:
|
STROOP_RESET_PASSWORD:
|
||||||
from_secret: STROOP_RESET_PASSWORD
|
from_secret: STROOP_RESET_PASSWORD
|
||||||
STROOP_CHANNEL_SHITPOST:
|
STROOP_CHANNEL_SHITPOST:
|
||||||
from_secret: STROOP_CHANNEL_SHITPOST
|
from_secret: STROOP_CHANNEL_SHITPOST
|
||||||
commands:
|
commands:
|
||||||
- pip install -r requirements.txt
|
- pip install -r requirements.txt
|
||||||
- python -m unittest tests
|
- python -m unittest tests
|
||||||
trigger:
|
trigger:
|
||||||
event:
|
event:
|
||||||
exclude:
|
exclude:
|
||||||
|
|||||||
+447
-125
@@ -1,14 +1,18 @@
|
|||||||
import asyncio
|
|
||||||
import discord
|
import discord
|
||||||
from discord.ext import commands
|
from discord.ext import commands
|
||||||
import numpy as np
|
import numpy as np
|
||||||
import random
|
import random
|
||||||
|
import requests
|
||||||
|
import asyncio
|
||||||
|
import os
|
||||||
|
import feedparser
|
||||||
|
import json
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
import re
|
import re
|
||||||
|
|
||||||
class Chatbot(commands.Cog):
|
class Chatbot(commands.Cog):
|
||||||
"""Een heuse chatbot. Under construction..."""
|
"""Een heuse chatbot. Under construction..."""
|
||||||
|
|
||||||
def __init__(self, bot):
|
def __init__(self, bot):
|
||||||
self.bot = bot
|
self.bot = bot
|
||||||
self.voice_states = {}
|
self.voice_states = {}
|
||||||
@@ -16,6 +20,8 @@ class Chatbot(commands.Cog):
|
|||||||
self.START_OF_MESSAGE = "<SOM>"
|
self.START_OF_MESSAGE = "<SOM>"
|
||||||
self.pmLast = datetime(2018, 1, 1, 1, 1, 1)
|
self.pmLast = datetime(2018, 1, 1, 1, 1, 1)
|
||||||
self.pmCount = 0
|
self.pmCount = 0
|
||||||
|
self.nosLast = datetime(2018, 1, 1, 1, 1, 1)
|
||||||
|
self.nosPosts = []
|
||||||
try:
|
try:
|
||||||
np.load('markov_dict.npy', allow_pickle=True)
|
np.load('markov_dict.npy', allow_pickle=True)
|
||||||
except FileNotFoundError:
|
except FileNotFoundError:
|
||||||
@@ -24,65 +30,66 @@ class Chatbot(commands.Cog):
|
|||||||
np.save("markov_dict.npy", initFile)
|
np.save("markov_dict.npy", initFile)
|
||||||
except:
|
except:
|
||||||
print("ERROR! - Could not open or create Markov chat file")
|
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:
|
#Do stuff when a message comes in:
|
||||||
@self.bot.event
|
@self.bot.event
|
||||||
@asyncio.coroutine
|
async def on_message(message):
|
||||||
def on_message(message):
|
if message.author.bot:
|
||||||
if message.author.bot:
|
|
||||||
return #ignore your own messages, Stroop
|
return #ignore your own messages, Stroop
|
||||||
|
|
||||||
if message.content.strip() == "" or message.content.strip()[0] != '!': #don't respond to a command
|
if message.content.strip() == "" or message.content.strip()[0] != '!': #don't respond to a command
|
||||||
if message.content.lower() == "nihao":
|
if message.content.lower() == "nihao":
|
||||||
yield from message.channel.send("kankerlauw")
|
await message.channel.send("kankerlauw")
|
||||||
return
|
return
|
||||||
if message.content.lower() == "lol":
|
if message.content.lower() == "lol":
|
||||||
yield from message.channel.send("laffing aut laut")
|
await message.channel.send("laffing aut laut")
|
||||||
return
|
return
|
||||||
if self.bot.user.mentioned_in(message) and "@everyone" not in message.content:
|
if self.bot.user.mentioned_in(message) and "@everyone" not in message.content:
|
||||||
MENTIONED_RESPONSES = [
|
MENTIONED_RESPONSES = [
|
||||||
"Hoi",
|
"Hoi",
|
||||||
"hmm?",
|
"hmm?",
|
||||||
"JA WAT?",
|
"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.getResponseForMessageLocal("stroopwafel")
|
||||||
self.getResponseForMessage("stroopwafel")
|
|
||||||
]
|
]
|
||||||
try:
|
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:
|
except:
|
||||||
print("ERROR! - Could not import insults")
|
print("ERROR! - Could not import insults")
|
||||||
yield from message.channel.send(random.choice(MENTIONED_RESPONSES))
|
await message.channel.send(random.choice(MENTIONED_RESPONSES))
|
||||||
return
|
return
|
||||||
if re.match("^[0-9]+([,.]?[0-9]+)*?$", message.content.strip()) and random.randint(0,9) == 0:
|
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
|
return
|
||||||
if "DMChannel" in type(message.channel).__name__: #respond to messages in PM channels
|
if "DMChannel" in type(message.channel).__name__: #respond to messages in PM channels
|
||||||
if (self.isAllowedToLearnFromPm(message)): #avoid spam-learning
|
if (self.isAllowedToLearnFromPm(message)): #avoid spam-learning
|
||||||
self.pmCount += 1
|
self.pmCount += 1
|
||||||
self.pmLast = datetime.now()
|
self.pmLast = datetime.now()
|
||||||
yield from self.learnFromMessagesInChannel(message.channel, 1)
|
await self.learnFromMessagesInChannel(message.channel, 1)
|
||||||
yield from self.respondToMessage(message)
|
await self.respondToMessage(message)
|
||||||
elif message.channel.id == self.bot.hdChannels["belangrijk"]: #don't abuse the "belangrijk" channel
|
|
||||||
pass
|
|
||||||
else:
|
else:
|
||||||
a = random.randint(0,999) # probablity
|
a = random.randint(0,999) # probablity
|
||||||
if a < 40:
|
if a < 40:
|
||||||
yield from self.learnFromMessagesInChannel(message.channel, 10)
|
await self.learnFromMessagesInChannel(message.channel, 10)
|
||||||
if "stroop" in message.content.lower():
|
if "stroop" in message.content.lower():
|
||||||
a = a / 20 # significantly increase the chance of responding if somebody talks about him.
|
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
|
if message.channel.id == os.getenv('STROOP_CHANNEL_SHITPOST') and a < 40: #shitpost channel
|
||||||
yield from self.respondToMessage(message)
|
await self.respondToMessage(message)
|
||||||
elif a < 10: #all other channels
|
elif a < 10: #all other channels
|
||||||
yield from self.respondToMessage(message)
|
await self.respondToMessage(message)
|
||||||
|
|
||||||
#process commands:
|
#process commands:
|
||||||
yield from self.bot.process_commands(message)
|
await self.bot.process_commands(message)
|
||||||
|
|
||||||
def __check(self, ctx):
|
def __check(self, ctx):
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
|
||||||
#The "Guus filter"
|
#The "Guus filter"
|
||||||
#Don't allow to learn from very large personal messages
|
#Don't allow to learn from very large personal messages
|
||||||
#Only learn from 10 personal messages per hour at most
|
#Only learn from 10 personal messages per hour at most
|
||||||
@@ -96,29 +103,29 @@ class Chatbot(commands.Cog):
|
|||||||
if self.pmCount > 10:
|
if self.pmCount > 10:
|
||||||
return False
|
return False
|
||||||
return True
|
return True
|
||||||
|
|
||||||
#Make word pairs:
|
#Make word pairs:
|
||||||
def makePairs(self, corpus):
|
def makePairs(self, corpus):
|
||||||
for i in range(len(corpus)-1):
|
for i in range(len(corpus)-1):
|
||||||
yield (corpus[i], corpus[i+1])
|
yield (corpus[i], corpus[i+1])
|
||||||
|
|
||||||
#Make word trairs. Yes, I completely made up "trair"
|
#Make word trairs. Yes, I completely made up "trair"
|
||||||
#It's like pairs, but with three, but not really, because there are two. OK?
|
#It's like pairs, but with three, but not really, because there are two. OK?
|
||||||
#[1 0 1]
|
#[1 0 1]
|
||||||
def makeTrairs(self, corpus):
|
def makeTrairs(self, corpus):
|
||||||
for i in range(1, len(corpus)-1):
|
for i in range(1, len(corpus)-1):
|
||||||
yield (corpus[i-1], corpus[i+1])
|
yield (corpus[i-1], corpus[i+1])
|
||||||
|
|
||||||
#Learn from a human message
|
#Learn from a human message
|
||||||
#Returns an updated dict
|
#Returns an updated dict
|
||||||
def learnFrom(self, wordDictPairs, wordDictTrairs, message: str):
|
def learnFrom(self, wordDictPairs, wordDictTrairs, message: str):
|
||||||
newPairDict = wordDictPairs
|
newPairDict = wordDictPairs
|
||||||
newTrairDict = wordDictTrairs
|
newTrairDict = wordDictTrairs
|
||||||
|
|
||||||
#If the message is only a tag, don't learn from it. return
|
#If the message is only a tag, don't learn from it. return
|
||||||
if message.count(' ') == 0 and message[0:2] == "<@":
|
if message.count(' ') == 0 and message[0:2] == "<@":
|
||||||
return newPairDict, newTrairDict;
|
return newPairDict, newTrairDict;
|
||||||
|
|
||||||
message = self.START_OF_MESSAGE + " " + message + " " + self.END_OF_MESSAGE
|
message = self.START_OF_MESSAGE + " " + message + " " + self.END_OF_MESSAGE
|
||||||
corpus = message.split()
|
corpus = message.split()
|
||||||
for n, word in enumerate(corpus):
|
for n, word in enumerate(corpus):
|
||||||
@@ -135,7 +142,7 @@ class Chatbot(commands.Cog):
|
|||||||
else:
|
else:
|
||||||
newPairDict[word_1][word_2] = 1
|
newPairDict[word_1][word_2] = 1
|
||||||
else:
|
else:
|
||||||
newPairDict[word_1] = {word_2 : 1}
|
newPairDict[word_1] = {word_2 : 1}
|
||||||
#Add wordcounts to trair dict
|
#Add wordcounts to trair dict
|
||||||
for word_1, word_3 in trairs:
|
for word_1, word_3 in trairs:
|
||||||
if word_1 in newTrairDict.keys():
|
if word_1 in newTrairDict.keys():
|
||||||
@@ -145,18 +152,18 @@ class Chatbot(commands.Cog):
|
|||||||
newTrairDict[word_1][word_3] = 1
|
newTrairDict[word_1][word_3] = 1
|
||||||
else:
|
else:
|
||||||
newTrairDict[word_1] = {word_3 : 1}
|
newTrairDict[word_1] = {word_3 : 1}
|
||||||
|
|
||||||
return newPairDict, newTrairDict;
|
return newPairDict, newTrairDict;
|
||||||
|
|
||||||
#Learn to respond to messages
|
#Learn to respond to messages
|
||||||
#Returns a new dict with response pairs
|
#Returns a new dict with response pairs
|
||||||
def learnResponse(self, wordDictResp, message1: str, message2: str):
|
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",
|
STOP_WORDS = ["aan", "achter", "al", "ben", "dan", "dat", "de", "die", "dit", "een", "en", "er", "gehad", "had", "heb",
|
||||||
"hen", "het", "hun", "in", "is", "kon", "met", "na", "of", "om", "ook", "op", "tot", "van", "was", "wat", "zo",
|
"hen", "het", "hun", "in", "is", "kon", "met", "na", "of", "om", "ook", "op", "tot", "van", "was", "wat", "zo",
|
||||||
"a", "an", "the", "am", "was", "were", "be", "not", "at"]
|
"a", "an", "the", "am", "was", "were", "be", "not", "at"]
|
||||||
|
|
||||||
newRespPairDict = wordDictResp
|
newRespPairDict = wordDictResp
|
||||||
|
|
||||||
#Split messages into words and remove stopwords:
|
#Split messages into words and remove stopwords:
|
||||||
message1List = []
|
message1List = []
|
||||||
message2List = []
|
message2List = []
|
||||||
@@ -166,7 +173,7 @@ class Chatbot(commands.Cog):
|
|||||||
for word in message2.split():
|
for word in message2.split():
|
||||||
if word not in STOP_WORDS:
|
if word not in STOP_WORDS:
|
||||||
message2List.append(word)
|
message2List.append(word)
|
||||||
|
|
||||||
#link words of response to words of initial message
|
#link words of response to words of initial message
|
||||||
for word_1 in message1List:
|
for word_1 in message1List:
|
||||||
for word_2 in message2List:
|
for word_2 in message2List:
|
||||||
@@ -176,40 +183,38 @@ class Chatbot(commands.Cog):
|
|||||||
else:
|
else:
|
||||||
newRespPairDict[word_1][word_2] = 1
|
newRespPairDict[word_1][word_2] = 1
|
||||||
else:
|
else:
|
||||||
newRespPairDict[word_1] = {word_2 : 1}
|
newRespPairDict[word_1] = {word_2 : 1}
|
||||||
|
|
||||||
return newRespPairDict
|
return newRespPairDict
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@commands.command(pass_context=True, hidden=True)
|
@commands.command(pass_context=True, hidden=True)
|
||||||
@asyncio.coroutine
|
async def trainmarkovchat(self, ctx, channelId=409751773595566081, nrOfMessages=50):
|
||||||
def trainmarkovchat(self, ctx, channelId=409751773595566081, nrOfMessages=50):
|
|
||||||
"""Train that chain, jermaine
|
"""Train that chain, jermaine
|
||||||
param channelId: use this channel to train
|
param channelId: use this channel to train
|
||||||
param nrOfMessages: use the x most recent messages
|
param nrOfMessages: use the x most recent messages
|
||||||
"""
|
"""
|
||||||
|
|
||||||
channel=self.bot.get_channel(channelId)
|
|
||||||
yield from self.learnFromMessagesInChannel(channel, nrOfMessages)
|
|
||||||
|
|
||||||
yield from ctx.channel.send("Ik heb weer wat nieuwe woordjes geleerd. :slight_smile:")
|
|
||||||
|
|
||||||
|
channel=self.bot.get_channel(channelId)
|
||||||
|
await self.learnFromMessagesInChannel(channel, nrOfMessages)
|
||||||
|
|
||||||
|
await ctx.channel.send("Ik heb weer wat nieuwe woordjes geleerd. :slight_smile:")
|
||||||
|
|
||||||
|
|
||||||
#Learns from an x number of messages from a certain channel
|
#Learns from an x number of messages from a certain channel
|
||||||
@asyncio.coroutine
|
async def learnFromMessagesInChannel(self, channel, nrOfMessages):
|
||||||
def learnFromMessagesInChannel(self, channel, nrOfMessages):
|
|
||||||
|
|
||||||
#Open current chain:
|
#Open current chain:
|
||||||
wordDict = np.load('markov_dict.npy', allow_pickle=True).item()
|
wordDict = np.load('markov_dict.npy', allow_pickle=True).item()
|
||||||
|
|
||||||
#Iterate through the last x messages from the channel:
|
#Iterate through the last x messages from the channel:
|
||||||
messageIterator = channel.history(limit=nrOfMessages, before=None, after=None, oldest_first=False, around=None)
|
messageIterator = channel.history(limit=nrOfMessages, before=None, after=None, oldest_first=False, around=None)
|
||||||
allMessages = []
|
allMessages = []
|
||||||
for i in range(nrOfMessages):
|
for i in range(nrOfMessages):
|
||||||
msg = yield from anext(messageIterator)
|
msg = await anext(messageIterator)
|
||||||
allMessages.append(msg)
|
allMessages.append(msg)
|
||||||
|
|
||||||
i = 0
|
i = 0
|
||||||
nextMessageIndex = -10
|
nextMessageIndex = -10
|
||||||
#Note: the loop goes from new to old
|
#Note: the loop goes from new to old
|
||||||
@@ -225,42 +230,46 @@ class Chatbot(commands.Cog):
|
|||||||
pass # Dit is een commando. Negeer.
|
pass # Dit is een commando. Negeer.
|
||||||
elif "```" in messageContent:
|
elif "```" in messageContent:
|
||||||
pass # Daar zit een codeblok in. Negeer.
|
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://":
|
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
|
pass # Een link. Negeer. TODO: post af en toe een random link die geen repost is
|
||||||
else:
|
else:
|
||||||
# Usable message!
|
# Usable message!
|
||||||
wordDict['pairs'], wordDict['trairs'] = self.learnFrom(wordDict['pairs'], wordDict['trairs'], messageContent)
|
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
|
if (i-nextMessageIndex) == 1 and msg.author != nextMessage.author: #the previous usable messages was the one right after this one and was not from the same author
|
||||||
timeDelta = nextMessage.created_at - msg.created_at
|
timeDelta = nextMessage.created_at - msg.created_at
|
||||||
#TODO check for different author
|
#TODO check for different author
|
||||||
if timeDelta.days == 0 and timeDelta.seconds < 3600: #less than an hour difference
|
if timeDelta.days == 0 and timeDelta.seconds < 3600: #less than an hour difference
|
||||||
#this is counted as a response. learn from it
|
#this is counted as a response. learn from it
|
||||||
wordDict['responsePairs'] = self.learnResponse(wordDict['responsePairs'], messageContent, nextMessageContent)
|
wordDict['responsePairs'] = self.learnResponse(wordDict['responsePairs'], messageContent, nextMessageContent)
|
||||||
|
|
||||||
#save for next iteration:
|
#save for next iteration:
|
||||||
nextMessage = msg
|
nextMessage = msg
|
||||||
nextMessageContent = messageContent
|
nextMessageContent = messageContent
|
||||||
nextMessageIndex = i
|
nextMessageIndex = i
|
||||||
i += 1
|
i += 1
|
||||||
|
|
||||||
np.save("markov_dict.npy", wordDict)
|
np.save("markov_dict.npy", wordDict)
|
||||||
|
|
||||||
|
|
||||||
@commands.command(pass_context=True, hidden=False)
|
@commands.command(pass_context=True, hidden=False)
|
||||||
@asyncio.coroutine
|
async def reageer(self, ctx):
|
||||||
def reageer(self, ctx):
|
|
||||||
"""Laat Stroop ergens op reageren.
|
"""Laat Stroop ergens op reageren.
|
||||||
Stroop leert van onze gesprekken. Hij kan zich nu voordoen als een van ons. Soort van.
|
Stroop leert van onze gesprekken. Hij kan zich nu voordoen als een van ons. Soort van.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
#Get previous message to respond to
|
#Get previous message to respond to
|
||||||
messageIterator = ctx.channel.history(limit=3, before=None, after=None, oldest_first=False, around=None)
|
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 = await anext(messageIterator) #this will be the !reageer command. skip
|
||||||
messageToRespondTo = yield from anext(messageIterator)
|
messageToRespondTo = await anext(messageIterator)
|
||||||
if messageToRespondTo.content.strip()[0] == '!' or messageToRespondTo.author.bot: #another chance
|
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] == '!':
|
if messageToRespondTo.content.strip()[0] == '!':
|
||||||
wordsToRespondTo = []
|
wordsToRespondTo = []
|
||||||
else:
|
else:
|
||||||
wordsToRespondTo = messageToRespondTo.content.strip().split()
|
wordsToRespondTo = messageToRespondTo.content.strip().split()
|
||||||
@@ -268,54 +277,80 @@ class Chatbot(commands.Cog):
|
|||||||
|
|
||||||
#Delete command
|
#Delete command
|
||||||
try:
|
try:
|
||||||
yield from ctx.message.delete()
|
await ctx.message.delete()
|
||||||
except:
|
except:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
response = self.getResponseForMessage(wordsToRespondTo)
|
response = await self.getResponseForMessage(wordsToRespondTo)
|
||||||
yield from ctx.channel.send(response)
|
await ctx.channel.send(response)
|
||||||
|
|
||||||
# Calculate probabilities and pick a next word from a word pair dict:
|
# Calculate probabilities and pick a next word from a word pair dict:
|
||||||
# https://stackoverflow.com/questions/835092/python-dictionary-are-keys-and-values-always-the-same-order
|
# https://stackoverflow.com/questions/835092/python-dictionary-are-keys-and-values-always-the-same-order
|
||||||
def pickNextWord(self, pairPossibilities):
|
def pickNextWord(self, pairPossibilities):
|
||||||
possible_words = list(pairPossibilities.keys())
|
possible_words = list(pairPossibilities.keys())
|
||||||
weights = np.array(list(pairPossibilities.values()))
|
weights = np.array(list(pairPossibilities.values()))
|
||||||
probs = weights / weights.sum()
|
probs = weights / weights.sum()
|
||||||
return np.random.choice(possible_words, p=probs)
|
return np.random.choice(possible_words, p=probs)
|
||||||
|
|
||||||
#Respond to a message.
|
#Respond to a message.
|
||||||
#Assumes the message isn't a command
|
#Assumes the message isn't a command
|
||||||
@asyncio.coroutine
|
async def respondToMessage(self, message):
|
||||||
def respondToMessage(self, message):
|
|
||||||
wordsToRespondTo = message.content.strip().split()
|
wordsToRespondTo = message.content.strip().split()
|
||||||
|
|
||||||
response = self.getResponseForMessage(wordsToRespondTo)
|
response = await self.getResponseForMessage(wordsToRespondTo)
|
||||||
yield from message.channel.send(response)
|
await message.channel.send(response)
|
||||||
|
|
||||||
#Gets a 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
|
MAX_N_WORDS = 100 #Don't use more words than this
|
||||||
|
|
||||||
#Get dictionary/Markov chain
|
#Get dictionary/Markov chain
|
||||||
wordDict = np.load('markov_dict.npy', allow_pickle=True).item()
|
wordDict = np.load('markov_dict.npy', allow_pickle=True).item()
|
||||||
wordPairDict = wordDict['pairs']
|
wordPairDict = wordDict['pairs']
|
||||||
wordTrairDict = wordDict['trairs']
|
wordTrairDict = wordDict['trairs']
|
||||||
responsePairDict = wordDict['responsePairs']
|
responsePairDict = wordDict['responsePairs']
|
||||||
#TODO store in global variable to minimise IO?
|
#TODO store in global variable to minimise IO?
|
||||||
|
|
||||||
#Start with <SOM>
|
#Start with <SOM>
|
||||||
chain = [self.START_OF_MESSAGE]
|
chain = [self.START_OF_MESSAGE]
|
||||||
|
|
||||||
#Go through the chain:
|
#Go through the chain:
|
||||||
for i in range(1, MAX_N_WORDS):
|
for i in range(1, MAX_N_WORDS):
|
||||||
|
|
||||||
if chain[-1] == self.END_OF_MESSAGE:
|
if chain[-1] == self.END_OF_MESSAGE:
|
||||||
break
|
break
|
||||||
|
|
||||||
#Find the possibilities:
|
#Find the possibilities:
|
||||||
pairPossibilities = wordPairDict[chain[-1]].copy()
|
pairPossibilities = wordPairDict[chain[-1]].copy()
|
||||||
|
|
||||||
#Increase score if it would be a good response:
|
#Increase score if it would be a good response:
|
||||||
for userWord in wordsToRespondTo:
|
for userWord in wordsToRespondTo:
|
||||||
if userWord in responsePairDict:
|
if userWord in responsePairDict:
|
||||||
@@ -333,75 +368,75 @@ class Chatbot(commands.Cog):
|
|||||||
for word2 in pairPossibilities.keys():
|
for word2 in pairPossibilities.keys():
|
||||||
if word2 in trairPossibilities.keys():
|
if word2 in trairPossibilities.keys():
|
||||||
pairPossibilities[word2] += trairPossibilities[word2]
|
pairPossibilities[word2] += trairPossibilities[word2]
|
||||||
|
|
||||||
#Pick a next word:
|
#Pick a next word:
|
||||||
chain.append(self.pickNextWord(pairPossibilities))
|
chain.append(self.pickNextWord(pairPossibilities))
|
||||||
|
|
||||||
|
|
||||||
if chain[0] == self.START_OF_MESSAGE:
|
if chain[0] == self.START_OF_MESSAGE:
|
||||||
chain = chain[1:-1] #remove <SOM> and <EOM>
|
chain = chain[1:-1] #remove <SOM> and <EOM>
|
||||||
else:
|
else:
|
||||||
chain = chain[:-1] #remove <EOM>
|
chain = chain[:-1] #remove <EOM>
|
||||||
|
|
||||||
#remove 90% of tags:
|
#remove 90% of tags:
|
||||||
for n, word in enumerate(chain):
|
for n, word in enumerate(chain):
|
||||||
if word[0:2] == "<@":
|
if word[0:2] == "<@":
|
||||||
a = random.randint(1,10)
|
a = random.randint(1,10)
|
||||||
if a != 1:
|
if a != 1:
|
||||||
chain[n] = "@jemoeder"
|
chain[n] = "@jemoeder"
|
||||||
|
|
||||||
#print(' '.join(chain))
|
#print(' '.join(chain))
|
||||||
#yield from ctx.channel.send(' '.join(chain))
|
#await ctx.channel.send(' '.join(chain))
|
||||||
return ' '.join(chain)
|
return ' '.join(chain)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
#Try to count the number of syllables in a word
|
#Try to count the number of syllables in a word
|
||||||
#Used to make Haikus
|
#Used to make Haikus
|
||||||
def countSyllables(self, word: str):
|
def countSyllables(self, word: str):
|
||||||
KNOWN_ACRONYMS = ["aub", "svp", "ivm", "nr", "zsm", "mbt", "tmi", "fyi", "afk", "omg", "idk", "coc"]
|
KNOWN_ACRONYMS = ["aub", "svp", "ivm", "nr", "zsm", "mbt", "tmi", "fyi", "afk", "omg", "idk", "coc"]
|
||||||
word = word.lower().strip()
|
word = word.lower().strip()
|
||||||
|
|
||||||
#for acryonyms, just count the letters:
|
#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):
|
if word in KNOWN_ACRONYMS or re.match("^([a-z]{1}[.]{1}){2,}$", word) or re.match("^([bcdfghjklmnpqrstvwxz]){2,}$", word):
|
||||||
return len(word.replace(".", ""))
|
return len(word.replace(".", ""))
|
||||||
|
|
||||||
#count vowels surrounded by consonants
|
#count vowels surrounded by consonants
|
||||||
count = len(re.findall("[bcdfghjklmnpqrstvwxyz]{1}[aeiouyëäïöüéèáà]{1,2}[bcdfghjklmnpqrstvwxz]{0,1}|[aeiouyëäïöüéèáà]{1,2}[bcdfghjklmnpqrstvwxz]{1}", word))
|
count = len(re.findall("[bcdfghjklmnpqrstvwxyz]{1}[aeiouyëäïöüéèáà]{1,2}[bcdfghjklmnpqrstvwxz]{0,1}|[aeiouyëäïöüéèáà]{1,2}[bcdfghjklmnpqrstvwxz]{1}", word))
|
||||||
count += len(re.findall("[ëäï]", word)) #ideeën etc
|
count += len(re.findall("[ëäï]", word)) #ideeën etc
|
||||||
|
|
||||||
return max(1, count)
|
return max(1, count)
|
||||||
|
|
||||||
#Append a message change with a numer of syllables
|
#Append a message change with a numer of syllables
|
||||||
#If it returns False, it couldn't find anything
|
#If it returns False, it couldn't find anything
|
||||||
#It's recursive, yo
|
#It's recursive, yo
|
||||||
def appendMessageWithNrOfSyllables(self, nrOfSyl: int, chain, wordPairDict):
|
def appendMessageWithNrOfSyllables(self, nrOfSyl: int, chain, wordPairDict):
|
||||||
#Find the possibilities:
|
#Find the possibilities:
|
||||||
if chain[-1] == "\n":
|
if chain[-1] == "\n":
|
||||||
pairPossibilities = wordPairDict[chain[-2]].copy()
|
pairPossibilities = wordPairDict[chain[-2]].copy()
|
||||||
else:
|
else:
|
||||||
pairPossibilities = wordPairDict[chain[-1]].copy()
|
pairPossibilities = wordPairDict[chain[-1]].copy()
|
||||||
|
|
||||||
for poss in list(pairPossibilities.keys()):
|
for poss in list(pairPossibilities.keys()):
|
||||||
if self.countSyllables(poss) > nrOfSyl or poss == self.END_OF_MESSAGE: #TODO change to constant
|
if self.countSyllables(poss) > nrOfSyl or poss == self.END_OF_MESSAGE: #TODO change to constant
|
||||||
del pairPossibilities[poss]
|
del pairPossibilities[poss]
|
||||||
|
|
||||||
if len(pairPossibilities) == 0:
|
if len(pairPossibilities) == 0:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
#Pick a next word:
|
#Pick a next word:
|
||||||
chain.append(self.pickNextWord(pairPossibilities))
|
chain.append(self.pickNextWord(pairPossibilities))
|
||||||
|
|
||||||
if self.countSyllables(chain[-1]) == nrOfSyl:
|
if self.countSyllables(chain[-1]) == nrOfSyl:
|
||||||
return chain
|
return chain
|
||||||
#RECURSION!
|
#RECURSION!
|
||||||
return self.appendMessageWithNrOfSyllables( (nrOfSyl-self.countSyllables(chain[-1])) , chain, wordPairDict)
|
return self.appendMessageWithNrOfSyllables( (nrOfSyl-self.countSyllables(chain[-1])) , chain, wordPairDict)
|
||||||
|
|
||||||
#Make a nice Haiku
|
#Make a nice Haiku
|
||||||
def getHaiku(self):
|
def getHaiku(self):
|
||||||
MAX_N_TRIES = 50
|
MAX_N_TRIES = 50
|
||||||
|
|
||||||
#Get dictionary/Markov chain
|
#Get dictionary/Markov chain
|
||||||
wordDict = np.load('markov_dict.npy', allow_pickle=True).item()
|
wordDict = np.load('markov_dict.npy', allow_pickle=True).item()
|
||||||
wordPairDict = wordDict['pairs']
|
wordPairDict = wordDict['pairs']
|
||||||
@@ -409,7 +444,7 @@ class Chatbot(commands.Cog):
|
|||||||
#try:
|
#try:
|
||||||
for i in range(1, MAX_N_TRIES):
|
for i in range(1, MAX_N_TRIES):
|
||||||
chain = [self.START_OF_MESSAGE]
|
chain = [self.START_OF_MESSAGE]
|
||||||
|
|
||||||
chain = self.appendMessageWithNrOfSyllables(5, chain, wordPairDict)
|
chain = self.appendMessageWithNrOfSyllables(5, chain, wordPairDict)
|
||||||
if chain is not False:
|
if chain is not False:
|
||||||
chain.append("\n")
|
chain.append("\n")
|
||||||
@@ -419,27 +454,268 @@ class Chatbot(commands.Cog):
|
|||||||
chain = self.appendMessageWithNrOfSyllables(5, chain, wordPairDict)
|
chain = self.appendMessageWithNrOfSyllables(5, chain, wordPairDict)
|
||||||
if chain is not False:
|
if chain is not False:
|
||||||
break
|
break
|
||||||
|
|
||||||
chain = chain[1:] #remove <SOM>
|
chain = chain[1:] #remove <SOM>
|
||||||
return ' '.join(chain)
|
return ' '.join(chain)
|
||||||
|
|
||||||
@commands.command(pass_context=True, hidden=False)
|
|
||||||
@asyncio.coroutine
|
|
||||||
def haiku(self, ctx):
|
|
||||||
"""Stroop is een poëet. Laat hem een Haiku maken.
|
|
||||||
"""
|
|
||||||
|
|
||||||
response = self.getHaiku()
|
|
||||||
yield from ctx.channel.send(response)
|
|
||||||
|
|
||||||
@commands.command(pass_context=True, hidden=False)
|
@commands.command(pass_context=True, hidden=False)
|
||||||
@asyncio.coroutine
|
async def haiku(self, ctx):
|
||||||
def uitspraak(self, ctx, numPosts=1):
|
"""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.
|
"""Random uitspraak uit de hall of fame.
|
||||||
Optioneel kan je een nummer meegeven voor meerdere uitspraken
|
Optioneel kan je een nummer meegeven voor meerdere uitspraken
|
||||||
0 voor alle uitspraken."""
|
0 voor alle uitspraken."""
|
||||||
try:
|
try:
|
||||||
yield from ctx.message.delete()
|
await ctx.message.delete()
|
||||||
except:
|
except:
|
||||||
pass
|
pass
|
||||||
try:
|
try:
|
||||||
@@ -451,6 +727,52 @@ class Chatbot(commands.Cog):
|
|||||||
numPosts = len(uitspraken)
|
numPosts = len(uitspraken)
|
||||||
for i in range(numPosts):
|
for i in range(numPosts):
|
||||||
message += uitspraken[i]
|
message += uitspraken[i]
|
||||||
yield from ctx.channel.send(message)
|
await ctx.channel.send(message)
|
||||||
except:
|
except:
|
||||||
pass
|
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
@@ -197,8 +197,7 @@ class Cryptocoin(commands.Cog):
|
|||||||
#user functions below
|
#user functions below
|
||||||
|
|
||||||
@commands.command(pass_context=True)
|
@commands.command(pass_context=True)
|
||||||
@asyncio.coroutine
|
async def coinprice(self, ctx, coinId: str, currencyId: str="USD"):
|
||||||
def coinprice(self, ctx, coinId: str, currencyId: str="USD"):
|
|
||||||
"""Geeft de huidige prijs van de desbetreffende crypto currency
|
"""Geeft de huidige prijs van de desbetreffende crypto currency
|
||||||
Bijv:
|
Bijv:
|
||||||
!coinprice BTC
|
!coinprice BTC
|
||||||
@@ -211,20 +210,19 @@ class Cryptocoin(commands.Cog):
|
|||||||
currencyId = currencyId.upper()
|
currencyId = currencyId.upper()
|
||||||
|
|
||||||
if (currencyId not in allowedCurrencies):
|
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
|
return
|
||||||
|
|
||||||
price = self.getCoinPrice(coinId, currencyId)
|
price = self.getCoinPrice(coinId, currencyId)
|
||||||
|
|
||||||
if (price == -1):
|
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
|
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)
|
@commands.command(pass_context=True)
|
||||||
@asyncio.coroutine
|
async def coinadvice(self, ctx, coinId: str=""):
|
||||||
def coinadvice(self, ctx, coinId: str=""):
|
|
||||||
"""Voor al uw adviezen in monopolygeld
|
"""Voor al uw adviezen in monopolygeld
|
||||||
Vraag Stroop's mening over een specifieke coin:
|
Vraag Stroop's mening over een specifieke coin:
|
||||||
!coinadvice NLG
|
!coinadvice NLG
|
||||||
@@ -237,7 +235,7 @@ class Cryptocoin(commands.Cog):
|
|||||||
|
|
||||||
#Geen specieke coin? Doe random.
|
#Geen specieke coin? Doe random.
|
||||||
if(coinId == ""):
|
if(coinId == ""):
|
||||||
yield from ctx.channel.send( self.getRandomCoinAdvice() )
|
await ctx.channel.send( self.getRandomCoinAdvice() )
|
||||||
return
|
return
|
||||||
|
|
||||||
coinId = coinId.upper()
|
coinId = coinId.upper()
|
||||||
@@ -245,7 +243,7 @@ class Cryptocoin(commands.Cog):
|
|||||||
growPercentage, coinStability, dummy = self.analyseCoin(coinId)
|
growPercentage, coinStability, dummy = self.analyseCoin(coinId)
|
||||||
|
|
||||||
if (growPercentage == 0 and coinStability == 1.0): #aanname. anders moet je weer een extra call doen.
|
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
|
return
|
||||||
|
|
||||||
time.sleep(0.1) #don't overload the API
|
time.sleep(0.1) #don't overload the API
|
||||||
@@ -302,5 +300,5 @@ class Cryptocoin(commands.Cog):
|
|||||||
if (coinStability < 0.3):
|
if (coinStability < 0.3):
|
||||||
message += "Denk ik?"
|
message += "Denk ik?"
|
||||||
|
|
||||||
yield from ctx.channel.send(message)
|
await ctx.channel.send(message)
|
||||||
|
|
||||||
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
FROM python:3.10
|
FROM python:3.13
|
||||||
|
|
||||||
WORKDIR /opt/stroopwafel
|
WORKDIR /opt/stroopwafel
|
||||||
|
|
||||||
|
|||||||
+60
-29
@@ -1,4 +1,3 @@
|
|||||||
import asyncio
|
|
||||||
import discord
|
import discord
|
||||||
import os
|
import os
|
||||||
import praw
|
import praw
|
||||||
@@ -6,6 +5,7 @@ import random
|
|||||||
import re
|
import re
|
||||||
import json, requests
|
import json, requests
|
||||||
import warnings
|
import warnings
|
||||||
|
from datetime import timedelta, datetime, timezone
|
||||||
from discord.ext import commands
|
from discord.ext import commands
|
||||||
|
|
||||||
class General(commands.Cog):
|
class General(commands.Cog):
|
||||||
@@ -13,7 +13,7 @@ class General(commands.Cog):
|
|||||||
|
|
||||||
def __init__(self, bot):
|
def __init__(self, bot):
|
||||||
self.bot = bot
|
self.bot = bot
|
||||||
self.muzak_url = 'https://hdcon-muzak.herokuapp.com'
|
self.muzak_url = 'http://muzak.hoekveen.net:8001'
|
||||||
self.r = praw.Reddit(
|
self.r = praw.Reddit(
|
||||||
user_agent='StroopwafelBot',
|
user_agent='StroopwafelBot',
|
||||||
client_secret=os.getenv("STROOP_REDDIT_SECRET"),
|
client_secret=os.getenv("STROOP_REDDIT_SECRET"),
|
||||||
@@ -23,25 +23,24 @@ class General(commands.Cog):
|
|||||||
warnings.simplefilter("ignore")
|
warnings.simplefilter("ignore")
|
||||||
|
|
||||||
def get_emoji_embed(self, tag: str):
|
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')
|
embed = discord.Embed(title=emoji.group(1), type='photo')
|
||||||
hugemoji = 'https://cdn.discordapp.com/emojis/' + emoji.group(2) + '.png'
|
hugemoji = 'https://cdn.discordapp.com/emojis/' + emoji.group(2) + '.png'
|
||||||
embed.set_image(url=hugemoji)
|
embed.set_image(url=hugemoji)
|
||||||
return embed
|
return embed
|
||||||
|
|
||||||
@commands.command()
|
@commands.command()
|
||||||
@asyncio.coroutine
|
async def huge(self, ctx, *, arg):
|
||||||
def huge(self, ctx, *, arg):
|
|
||||||
"""YUGE. Geeft een grote versie van de gegeven emoji terug. Werkt alleen voor custom emoji.
|
"""YUGE. Geeft een grote versie van de gegeven emoji terug. Werkt alleen voor custom emoji.
|
||||||
Bijvoorbeeld:
|
Bijvoorbeeld:
|
||||||
!huge :ancilla:
|
!huge :ancilla:
|
||||||
"""
|
"""
|
||||||
em = self.get_emoji_embed(arg)
|
em = self.get_emoji_embed(arg)
|
||||||
try:
|
try:
|
||||||
yield from ctx.message.delete()
|
await ctx.message.delete()
|
||||||
except:
|
except:
|
||||||
print("No permission to delete message")
|
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):
|
def get_aww_post(self):
|
||||||
raww = self.r.subreddit('aww+catloaf+tuckedinkitties+babyelephantgifs+babybigcatgifs+blep+holdmynip+gingerkitty+cathighfive+catsstandingup+catsareassholes+eyebleach')
|
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)
|
return random.choice(listing)
|
||||||
|
|
||||||
@commands.command(pass_context=True)
|
@commands.command(pass_context=True)
|
||||||
@asyncio.coroutine
|
async def aww(self, ctx):
|
||||||
def aww(self, ctx):
|
|
||||||
""" iets schattigs... """
|
""" iets schattigs... """
|
||||||
post = self.get_aww_post()
|
post = self.get_aww_post()
|
||||||
try:
|
try:
|
||||||
yield from ctx.message.delete()
|
await ctx.message.delete()
|
||||||
except:
|
except:
|
||||||
print("No permission to delete message")
|
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):
|
def get_kopieerpasta(self):
|
||||||
rkopieerpasta = self.r.subreddit('kopieerpasta')
|
rkopieerpasta = self.r.subreddit('kopieerpasta')
|
||||||
post = rkopieerpasta.random()
|
try:
|
||||||
|
post = rkopieerpasta.random()
|
||||||
|
|
||||||
# Subreddits kunnen de random functie uitzetten, dus dit is de fallback:
|
# Subreddits kunnen de random functie uitzetten, dus dit is de fallback:
|
||||||
if post == None:
|
if post == None:
|
||||||
listing = list(rkopieerpasta.top('month', limit=250))
|
listing = list(rkopieerpasta.top(time_filter='month', limit=250))
|
||||||
post = random.choice(listing)
|
post = random.choice(listing)
|
||||||
|
|
||||||
return post
|
return post
|
||||||
|
except:
|
||||||
|
return None
|
||||||
|
|
||||||
@commands.command(pass_context=True)
|
@commands.command(pass_context=True)
|
||||||
@asyncio.coroutine
|
async def kopieerpasta(self, ctx):
|
||||||
def kopieerpasta(self, ctx):
|
|
||||||
"""Een willekeurige shitpost"""
|
"""Een willekeurige shitpost"""
|
||||||
post = self.get_kopieerpasta()
|
post = self.get_kopieerpasta()
|
||||||
|
if not post:
|
||||||
|
await ctx.channel.send("Geen kopieerpasta voor jou vandaag.")
|
||||||
|
return
|
||||||
print(post.url)
|
print(post.url)
|
||||||
ATTEMPTS = 10
|
ATTEMPTS = 10
|
||||||
a = 0
|
a = 0
|
||||||
@@ -83,23 +86,51 @@ class General(commands.Cog):
|
|||||||
print(post.url)
|
print(post.url)
|
||||||
a += 1
|
a += 1
|
||||||
try:
|
try:
|
||||||
yield from ctx.message.delete()
|
await ctx.message.delete()
|
||||||
except:
|
except:
|
||||||
print("No permission to delete message")
|
print("No permission to delete message")
|
||||||
|
|
||||||
if len(post.selftext + post.title) < 1990:
|
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:
|
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):
|
def get_playlist_json(self):
|
||||||
return requests.get(self.muzak_url + '/stroopwafel')
|
return requests.get(self.muzak_url + '/stroopwafel')
|
||||||
|
|
||||||
@commands.command(pass_context=True)
|
@commands.command(pass_context=True)
|
||||||
@asyncio.coroutine
|
async def muzak(self, ctx):
|
||||||
def playlist(self, ctx):
|
"""HD muzak playlist"""
|
||||||
"""HDcon2021 playlist"""
|
|
||||||
data = json.loads(self.get_playlist_json().content)
|
data = json.loads(self.get_playlist_json().content)
|
||||||
msg = 'Stemmen en nomineren kan hier: {}\n'.format(self.muzak_url)
|
msg = ""
|
||||||
msg += '*Er zijn al {} nummers genomineerd*\n'.format(data['stemCount'])
|
open = datetime.fromisoformat(data['openDate'])
|
||||||
yield from ctx.channel.send(msg)
|
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')
|
||||||
@@ -1,289 +1,317 @@
|
|||||||
import asyncio
|
|
||||||
import discord
|
import discord
|
||||||
from discord.ext import commands
|
from discord.ext import commands
|
||||||
from pprint import pprint
|
|
||||||
import time
|
import time
|
||||||
import numpy as np
|
import numpy as np
|
||||||
import random
|
import random
|
||||||
import os
|
import os
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
|
||||||
|
|
||||||
class Points(commands.Cog):
|
class Points(commands.Cog):
|
||||||
"""Geef elkaar punten!"""
|
"""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)
|
|
||||||
@asyncio.coroutine
|
|
||||||
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:
|
|
||||||
yield from 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?
|
|
||||||
return
|
|
||||||
|
|
||||||
userObj = ctx.message.mentions[0]
|
def __init__(self, bot):
|
||||||
|
self.bot = bot
|
||||||
if userObj.id == ctx.author.id:
|
self.voice_states = {}
|
||||||
yield from ctx.channel.send("Nee. Je mag niet jezelf punten geven.")
|
|
||||||
time.sleep(0.6)
|
|
||||||
yield from ctx.channel.send("Gekkie.")
|
|
||||||
return
|
|
||||||
if not self.isUserOnList(userObj):
|
|
||||||
yield from 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:")
|
|
||||||
return
|
|
||||||
|
|
||||||
# Execute the transaction:
|
|
||||||
self.execute_geefpunten(ctx.author.id, userObj.id, points)
|
|
||||||
|
|
||||||
self.savePointsCount()
|
|
||||||
|
|
||||||
message = self.getMessageForAwardingPoints(ctx.author.name, userObj.name, points)
|
self.BANK_ID = 42
|
||||||
yield from ctx.channel.send(message)
|
self.init()
|
||||||
|
|
||||||
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)
|
|
||||||
@asyncio.coroutine
|
|
||||||
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:
|
|
||||||
yield from 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.")
|
|
||||||
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. :)")
|
|
||||||
return
|
|
||||||
|
|
||||||
userObj = ctx.message.mentions[0]
|
|
||||||
|
|
||||||
if not self.isUserOnList(userObj):
|
|
||||||
yield from ctx.channel.send("Nee.")
|
|
||||||
return
|
|
||||||
if self.getUserBalance(userObj) < points:
|
|
||||||
yield from 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)
|
self.pointsCount = {}
|
||||||
yield from ctx.channel.send(message)
|
self.reloadPointsCount()
|
||||||
|
|
||||||
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)
|
|
||||||
@asyncio.coroutine
|
|
||||||
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"] + "```"
|
|
||||||
yield from ctx.channel.send(message)
|
|
||||||
|
|
||||||
|
|
||||||
# No public shaming. Send somebody a direct correction message.
|
|
||||||
@asyncio.coroutine
|
|
||||||
def sendErrorDm(self, ctx, message):
|
|
||||||
try:
|
|
||||||
yield from ctx.message.delete()
|
|
||||||
except:
|
|
||||||
print("No permission to delete message")
|
|
||||||
try:
|
|
||||||
yield from 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
|
|
||||||
|
|
||||||
|
def __check(self, ctx):
|
||||||
# Generate a semi-random text to tell somebody they got some shiny new points
|
return True
|
||||||
def getMessageForAwardingPoints(self, userNameFrom: str, userNameTo: str, points: int):
|
|
||||||
p = str(points)
|
@commands.command()
|
||||||
|
async def geefpunten(self, ctx, *args):
|
||||||
if points == 1:
|
"""Wees eens lief. Geef iemand wat punten.
|
||||||
grammarFixer = {"suffixGb":"", "suffixNl":"", "zijnOfIs": "is"}
|
Bijvoorbeeld:
|
||||||
else:
|
!geefpunten @ikbenjp 42 of !geefpunten 42 @ikbenjp
|
||||||
grammarFixer = {"suffixGb":"s", "suffixNl":"en", "zijnOfIs": "zijn"}
|
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.)
|
||||||
messages = [
|
"""
|
||||||
p + " punt" + grammarFixer["suffixNl"] + " voor " + userNameTo + ".",
|
|
||||||
userNameTo + " krijgt " + p + " punt" + grammarFixer["suffixNl"] + ".",
|
if not ctx.message.mentions: #als er uberhaupt geen mention is zijn we snel klaar
|
||||||
userNameTo + " krijgt " + p + " punt" + grammarFixer["suffixNl"] + " van " + userNameFrom,
|
await ctx.send(f"{ctx.author.mention} je moet iemand taggen om punten te geven. :)")
|
||||||
p + " POINT" + grammarFixer["suffixGb"].upper() + " TO GRYFFINDO.. oh.. " + userNameTo + ".",
|
return
|
||||||
userNameTo + ", jij krijgt " + p + " puntje" + grammarFixer["suffixGb"] + " van " + userNameFrom + ". Lief he? :heart:",
|
|
||||||
"+" + p + " punt" + grammarFixer["suffixNl"] + " voor " + userNameTo + "! Highscore!",
|
if len(args) == 2:
|
||||||
userNameTo + ", alsjeblieft, " + p + " punt" + grammarFixer["suffixNl"] + ".",
|
user = None
|
||||||
"Hier " + grammarFixer["zijnOfIs"] + " " + p + " punt" + grammarFixer["suffixNl"] + ", " + userNameTo + ". Don't spend it all in one place...",
|
points = None
|
||||||
"Jij kan wel " + p + " punt" + grammarFixer["suffixNl"] + " gebruiken, " + userNameTo + ".",
|
for arg in args[0:2]:
|
||||||
p + " blockchain smartcontract punt" + grammarFixer["suffixNl"] + " voor " + userNameTo + ". :rocket: "
|
if arg[0:2] == "<@":
|
||||||
]
|
user = arg #doen we verder niks mee, maar zo bepalen we positie van de puntjes
|
||||||
return messages[random.randint(0, len(messages)-1)]
|
else:
|
||||||
|
try:
|
||||||
# Generate a semi-random text to tell somebody they just lost their precious points
|
points = int(arg)
|
||||||
def getMessageForTakingPoints(self, userNameFrom: str, userNameTaker: str, points: int):
|
except ValueError:
|
||||||
p = str(points)
|
pass #dealen we hieronder mee
|
||||||
|
|
||||||
if points == 1:
|
if user == None or points == None:
|
||||||
grammarFixer = {"suffixGb":"", "suffixNl":"", "gaatOfGaan":"gaat"}
|
raise commands.BadArgument("Verkeerd type argumenten")
|
||||||
else:
|
else:
|
||||||
grammarFixer = {"suffixGb":"s", "suffixNl":"en", "gaatOfGaan":"gaan"}
|
raise commands.BadArgument("Verkeerd aantal argumenten")
|
||||||
|
|
||||||
messages = [
|
self.reloadPointsCount()
|
||||||
userNameFrom + " verliest " + p + " punt" + grammarFixer["suffixNl"] + ".",
|
|
||||||
userNameFrom + " is " + p + " punt" + grammarFixer["suffixNl"] + " kwijt. F.",
|
if points == 0:
|
||||||
userNameTaker + " vindt dat jij " + p + " punt" + grammarFixer["suffixNl"] + " moet kwijtraken, " + userNameFrom + ".",
|
await ctx.channel.send("0 punten? Gul hoor.")
|
||||||
p + " POINT" + grammarFixer["suffixGb"].upper() + " FROM HUFFELPU.. oh.. " + userNameFrom + ".",
|
return
|
||||||
"Je bent " + p + " punt" + grammarFixer["suffixNl"] + " armer geworden, " + userNameFrom + ".",
|
if points < 0:
|
||||||
"Je hebt toch genoeg, " + userNameFrom + ". We halen " + p + " punt" + grammarFixer["suffixNl"] + " weg.",
|
await self.sendErrorDm(ctx, "Daar hebben we de !neempunten functie voor. Voor meer info typ: ```!help neempunten```")
|
||||||
userNameTaker + " haalt " + p + " punt" + grammarFixer["suffixNl"] + " weg bij " + userNameFrom + ". Wat een lul.",
|
return
|
||||||
p + " punt" + grammarFixer["suffixNl"] + " " + grammarFixer["gaatOfGaan"] + " van " + userNameFrom + " naar de bank."
|
|
||||||
]
|
userObj = ctx.message.mentions[0]
|
||||||
return messages[random.randint(0, len(messages)-1)]
|
|
||||||
|
if userObj.id == ctx.author.id:
|
||||||
|
await ctx.channel.send("Nee. Je mag niet jezelf punten geven.")
|
||||||
def init(self):
|
time.sleep(0.6)
|
||||||
# Check if points file exists:
|
await ctx.channel.send("Gekkie.")
|
||||||
try:
|
return
|
||||||
pointsCount = np.load('pointscount.npy', allow_pickle=True).item()
|
if not self.isUserOnList(userObj):
|
||||||
except FileNotFoundError:
|
await ctx.channel.send("Nee. Die krijgt geen punten.")
|
||||||
np.save("pointscount.npy", {})
|
return
|
||||||
pointsCount = np.load('pointscount.npy', allow_pickle=True).item()
|
if self.getUserBalance(ctx.author) < points:
|
||||||
|
await ctx.channel.send("Daar heb jij niet genoeg puntjes voor. :bell:")
|
||||||
# Initialise the bank:
|
return
|
||||||
if self.BANK_ID not in pointsCount.keys():
|
|
||||||
pointsCount[self.BANK_ID] = {"name": '"De Bank"', "points": 300}
|
# Execute the transaction:
|
||||||
np.save("pointscount.npy", pointsCount)
|
self.execute_geefpunten(ctx.author.id, userObj.id, points)
|
||||||
|
|
||||||
# Add new/unknown members:
|
self.savePointsCount()
|
||||||
list_channel = self.bot.get_channel(int(os.getenv('STROOP_CHANNEL_SHITPOST')))
|
|
||||||
memberList = list_channel.members if list_channel else []
|
message = self.getMessageForAwardingPoints(ctx.author.name, userObj.name, points)
|
||||||
for member in memberList:
|
await ctx.channel.send(message)
|
||||||
# Give new members 100 points
|
|
||||||
if member.id not in pointsCount.keys() and not member.bot:
|
def execute_geefpunten(self, giverId, recieverId, points):
|
||||||
pointsCount[member.id] = {"name": member.name, "points": 100, "pointTakenOnDate":0, "bankPointsGivenOnDate":0, "theDate":"20181231"}
|
# First, try to give away (at most 10) bankpoints
|
||||||
np.save("pointscount.npy", pointsCount)
|
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)
|
||||||
+180
-153
@@ -1,9 +1,9 @@
|
|||||||
import asyncio
|
|
||||||
import discord
|
import discord
|
||||||
from discord.ext import commands
|
from discord.ext import commands
|
||||||
from urllib import request
|
from urllib import request
|
||||||
import json, requests
|
import json, requests
|
||||||
import math
|
import math
|
||||||
|
from zoneinfo import ZoneInfo
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, timedelta
|
||||||
import os
|
import os
|
||||||
import random
|
import random
|
||||||
@@ -13,10 +13,12 @@ import re
|
|||||||
|
|
||||||
class Shitpost(commands.Cog):
|
class Shitpost(commands.Cog):
|
||||||
"""Schijtpaal commando's. Alleen bruikbaar in de daarvoor toegewezen schijtpaal kanalen."""
|
"""Schijtpaal commando's. Alleen bruikbaar in de daarvoor toegewezen schijtpaal kanalen."""
|
||||||
|
|
||||||
def __init__(self, bot):
|
def __init__(self, bot):
|
||||||
self.bot = bot
|
self.bot = bot
|
||||||
self.hdConImpatientEvents = []
|
self.hdConImpatientEvents = []
|
||||||
|
self.userAgent = 'Mozilla/5.0 (X11; Linux x86_64; rv:136.0) Gecko/20100101 Firefox/136.0'
|
||||||
|
self.TIME_ZONE = ZoneInfo("Europe/Amsterdam")
|
||||||
try:
|
try:
|
||||||
with open('black.txt') as zwart:
|
with open('black.txt') as zwart:
|
||||||
self.zwarte_lijst = [line.rstrip('\n') for line in zwart]
|
self.zwarte_lijst = [line.rstrip('\n') for line in zwart]
|
||||||
@@ -41,35 +43,37 @@ class Shitpost(commands.Cog):
|
|||||||
'zout': '116231806'
|
'zout': '116231806'
|
||||||
}
|
}
|
||||||
warnings.simplefilter("ignore")
|
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)
|
@commands.command(pass_context=True, hidden=False)
|
||||||
@asyncio.coroutine
|
async def ishetalhdcon(self, ctx):
|
||||||
def ishetalhdcon(self, ctx):
|
"""Hoe lang nog tot Hoestende Draken Con dit jaar? Of is het pas volgend jaar?
|
||||||
"""Hoe lang nog tot Hoestende Draken Con 2022?
|
|
||||||
Gebruik: !ishetalhdcon
|
Gebruik: !ishetalhdcon
|
||||||
"""
|
"""
|
||||||
|
|
||||||
Now = datetime.now()
|
Now = datetime.now()
|
||||||
HdConDate = datetime(2022, 10, 14, 4, 0, 1) #om 4 uur lig je toch wel al op bed?
|
Message = f"Geen HD Con! >:|"
|
||||||
Distance = HdConDate - Now
|
if self.HdConDate:
|
||||||
Message = Message = "HD Con 2022 is al voorbij. HD Con 2023 zal in 2023 plaatsvinden."
|
Message = f"HD Con {self.HdConDate.year} "
|
||||||
if Distance.days == -1:
|
Distance = self.HdConDate - Now
|
||||||
Message = "HD Con 2022 begint vandaag! HYPE!"
|
if Distance.days == -1:
|
||||||
elif Distance.days < 0 and Distance.days > -4:
|
Message += "begint vandaag! HYPE!"
|
||||||
Message = "HD Con 2022 is nu bezig!!"
|
elif Distance.days < 0 and Distance.days > -4:
|
||||||
elif Distance.days == -4:
|
Message += "is nu bezig!!"
|
||||||
Message = "HD Con 2022 is vandaag alweer afgelopen... F"
|
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:
|
if Distance.days < 0:
|
||||||
yield from ctx.channel.send(ctx.author.mention + ' ' + str(Message))
|
await ctx.channel.send(ctx.author.mention + ' ' + str(Message))
|
||||||
return
|
return
|
||||||
|
|
||||||
|
NachtjesSlapen = Distance.days + 1
|
||||||
|
Message = f"Nog {NachtjesSlapen} nachtje{'s' if NachtjesSlapen > 1 else ''} slapen..."
|
||||||
|
|
||||||
NachtjesSlapen = Distance.days + 1
|
|
||||||
if NachtjesSlapen == 1:
|
|
||||||
Message = "Nog " + str(NachtjesSlapen) + " nachtje slapen..."
|
|
||||||
else:
|
|
||||||
Message = "Nog " + str(NachtjesSlapen) + " nachtjes slapen..."
|
|
||||||
|
|
||||||
#Hou bij hoe vaak dit wordt gevraagd:
|
#Hou bij hoe vaak dit wordt gevraagd:
|
||||||
eventsMinutesAgo = 0;
|
eventsMinutesAgo = 0;
|
||||||
eventsMinutesAgoSameAuthor = 0;
|
eventsMinutesAgoSameAuthor = 0;
|
||||||
@@ -84,29 +88,29 @@ class Shitpost(commands.Cog):
|
|||||||
eventsLastDays += 1
|
eventsLastDays += 1
|
||||||
if not "DMChannel" in type(ctx.channel).__name__: #ignore personal chats
|
if not "DMChannel" in type(ctx.channel).__name__: #ignore personal chats
|
||||||
self.hdConImpatientEvents.append([ctx.author.id, Now])
|
self.hdConImpatientEvents.append([ctx.author.id, Now])
|
||||||
|
|
||||||
#Als dezelfde persoon het blijft vragen pikken we het niet:
|
#Als dezelfde persoon het blijft vragen pikken we het niet:
|
||||||
if eventsMinutesAgoSameAuthor > 3:
|
if eventsMinutesAgoSameAuthor > 3:
|
||||||
return #fuck it.
|
return #fuck it.
|
||||||
if eventsMinutesAgoSameAuthor > 0:
|
if eventsMinutesAgoSameAuthor > 0:
|
||||||
if eventsMinutesAgoSameAuthor > 2:
|
if eventsMinutesAgoSameAuthor > 2:
|
||||||
yield from ctx.channel.send("...")
|
await ctx.channel.send("...")
|
||||||
return
|
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
|
return
|
||||||
#Hoe vaker er wordt gevraagd, hoe ongeduldiger de antwoorden:
|
#Hoe vaker er wordt gevraagd, hoe ongeduldiger de antwoorden:
|
||||||
if not "DMChannel" in type(ctx.channel).__name__: #ignore personal chats
|
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()
|
impatientFactor *= random.random()
|
||||||
if impatientFactor > 100:
|
if impatientFactor > 100:
|
||||||
yield from ctx.channel.send("Nee!")
|
await ctx.channel.send("Nee!")
|
||||||
return
|
return
|
||||||
elif impatientFactor > 15 and eventsMinutesAgo > 0:
|
elif impatientFactor > 15 and eventsMinutesAgo > 0:
|
||||||
Message = "Dat hebben jullie net gevraagd."
|
Message = "Dat hebben jullie net gevraagd."
|
||||||
elif impatientFactor > 9:
|
elif impatientFactor > 12:
|
||||||
Message = "Nee."
|
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):
|
def zalgofy(self, sentence, factor = 4):
|
||||||
random.seed(datetime.now().timestamp())
|
random.seed(datetime.now().timestamp())
|
||||||
@@ -119,8 +123,7 @@ class Shitpost(commands.Cog):
|
|||||||
return message
|
return message
|
||||||
|
|
||||||
@commands.command(pass_context=True, hidden=False)
|
@commands.command(pass_context=True, hidden=False)
|
||||||
@asyncio.coroutine
|
async def zalgo(self, ctx, *, arg):
|
||||||
def zalgo(self, ctx, *, arg):
|
|
||||||
"""z̴̬̘͇̗͇̦̤̩̜͜ą̷̟̯̪̩̣̭̭͇̹l̴̗͓̟̠̤̳̗͉̠ͅg̵̜͎̪̞̫͎͈͉͉͍o̵̧̧͇̱̱̜̮͉͉̳ ̴̨̡͖̘̪̭̖͖̘̝h̸̭̰̫̲̺̹̻̜͕ͅe̴̢̘̪̱̱̩̠̣̘̱ ̴̡̢̲̞̙̝̮̻̻͇c̶̡̢̺͙̮̗̲̹̱̱o̷̢̡̺̘͈͎̫̬͔̤m̷͕͍͍̥͖̻̲̞̝ͅe̷̱̟͕̥͕̞̜̫̳̙s̷̨͍̼̝̙̩̥̰̠ͅ
|
"""z̴̬̘͇̗͇̦̤̩̜͜ą̷̟̯̪̩̣̭̭͇̹l̴̗͓̟̠̤̳̗͉̠ͅg̵̜͎̪̞̫͎͈͉͉͍o̵̧̧͇̱̱̜̮͉͉̳ ̴̨̡͖̘̪̭̖͖̘̝h̸̭̰̫̲̺̹̻̜͕ͅe̴̢̘̪̱̱̩̠̣̘̱ ̴̡̢̲̞̙̝̮̻̻͇c̶̡̢̺͙̮̗̲̹̱̱o̷̢̡̺̘͈͎̫̬͔̤m̷͕͍͍̥͖̻̲̞̝ͅe̷̱̟͕̥͕̞̜̫̳̙s̷̨͍̼̝̙̩̥̰̠ͅ
|
||||||
h̷̦̰̣̗̭͕̩͓͈̠i̶̗̰̹̤̖͙̰̹͙̹j̸̧̜̬̬̜̹͔̰̫͜ ̶̧͉͔̠̻͈̜̳̥̭k̸̯̳̠̼̙̗̘̳͜ͅǫ̵̝̱̩͎̫͈̣̪̦m̶̺̙̟̫͔͈̭̖̱ͅt̶̜̠̟͙̞̠̗̗̥ͅ ̸̢̹̜͉͙̩̬̖ͅͅh̷̯̮̘̭͈̜̺͎̳̯i̴̩̯̼̱͇̟̫̻̘̖j̵̪̤̦͖̮̜̦̼̺̮ ̶̧͇̭̞̮̩̼͚̮ͅḵ̴̢̨̢͉͉͖̹̬̺o̵̢̪̥̻͙͕̫̥̗͜m̶̧̡͔̠̺͖̝̳̪ͅt̷̢̮̭̜̥̠̼̫͍̯
|
h̷̦̰̣̗̭͕̩͓͈̠i̶̗̰̹̤̖͙̰̹͙̹j̸̧̜̬̬̜̹͔̰̫͜ ̶̧͉͔̠̻͈̜̳̥̭k̸̯̳̠̼̙̗̘̳͜ͅǫ̵̝̱̩͎̫͈̣̪̦m̶̺̙̟̫͔͈̭̖̱ͅt̶̜̠̟͙̞̠̗̗̥ͅ ̸̢̹̜͉͙̩̬̖ͅͅh̷̯̮̘̭͈̜̺͎̳̯i̴̩̯̼̱͇̟̫̻̘̖j̵̪̤̦͖̮̜̦̼̺̮ ̶̧͇̭̞̮̩̼͚̮ͅḵ̴̢̨̢͉͉͖̹̬̺o̵̢̪̥̻͙͕̫̥̗͜m̶̧̡͔̠̺͖̝̳̪ͅt̷̢̮̭̜̥̠̼̫͍̯
|
||||||
d̷̢̪͍͓̭̣̼̠͎̠e̴̡̢̩̱͙̻̥̯͎͜ ̵̲̪͖̖͖͍͈͎̮̼ļ̴̯̗̝̦͍͍͖̰͜i̶̡̘̟̳̖͙͕͔̺͜ȩ̸̤͎̣͖͔̭͔̫̯v̷͔̺͖̖̞̙̘̖̠͓e̶̲͍̮̳͎̗̳̞̹͔ ̸̡̬̫͎͎̝͍̤̯ͅg̴̨̞̻͙̠̰͖͖̝ͅǫ̴̘̥͇̙̖͈͍̹̥e̵̥͇̫̱̬̝̥̲̞̜d̷͈͙̝͍͔̘͕̼̜̦e̴̡̯̦͉͙̪̭͕̻̝
|
d̷̢̪͍͓̭̣̼̠͎̠e̴̡̢̩̱͙̻̥̯͎͜ ̵̲̪͖̖͖͍͈͎̮̼ļ̴̯̗̝̦͍͍͖̰͜i̶̡̘̟̳̖͙͕͔̺͜ȩ̸̤͎̣͖͔̭͔̫̯v̷͔̺͖̖̞̙̘̖̠͓e̶̲͍̮̳͎̗̳̞̹͔ ̸̡̬̫͎͎̝͍̤̯ͅg̴̨̞̻͙̠̰͖͖̝ͅǫ̴̘̥͇̙̖͈͍̹̥e̵̥͇̫̱̬̝̥̲̞̜d̷͈͙̝͍͔̘͕̼̜̦e̴̡̯̦͉͙̪̭͕̻̝
|
||||||
@@ -130,10 +133,10 @@ class Shitpost(commands.Cog):
|
|||||||
"""
|
"""
|
||||||
message = self.zalgofy(arg)
|
message = self.zalgofy(arg)
|
||||||
try:
|
try:
|
||||||
yield from ctx.message.delete()
|
await ctx.message.delete()
|
||||||
except:
|
except:
|
||||||
print("No permission to delete message")
|
print("No permission to delete message")
|
||||||
yield from ctx.channel.send(str(message))
|
await ctx.channel.send(str(message))
|
||||||
|
|
||||||
def get_corona_message(self):
|
def get_corona_message(self):
|
||||||
response = requests.get('https://covid.ourworldindata.org/data/latest/owid-covid-latest.json')
|
response = requests.get('https://covid.ourworldindata.org/data/latest/owid-covid-latest.json')
|
||||||
@@ -151,18 +154,16 @@ class Shitpost(commands.Cog):
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
@commands.command(pass_context=True, hidden=False)
|
@commands.command(pass_context=True, hidden=False)
|
||||||
@asyncio.coroutine
|
async def corona(self, ctx):
|
||||||
def corona(self, ctx):
|
|
||||||
try:
|
try:
|
||||||
yield from ctx.message.delete()
|
await ctx.message.delete()
|
||||||
except:
|
except:
|
||||||
print("No permission to delete message")
|
print("No permission to delete message")
|
||||||
message = self.get_corona_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)
|
@commands.command(pass_context=True, hidden=False)
|
||||||
@asyncio.coroutine
|
async def viertwintig(self, ctx):
|
||||||
def viertwintig(self, ctx):
|
|
||||||
"""Hoe lang nog tot 420?
|
"""Hoe lang nog tot 420?
|
||||||
Gebruik: !viertwintig
|
Gebruik: !viertwintig
|
||||||
"""
|
"""
|
||||||
@@ -187,31 +188,29 @@ class Shitpost(commands.Cog):
|
|||||||
minutes = math.floor(secondsLeft / 60)
|
minutes = math.floor(secondsLeft / 60)
|
||||||
seconds = secondsLeft - minutes * 60
|
seconds = secondsLeft - minutes * 60
|
||||||
Message += "Nog " + str(days) + " dagen, " + str(hours) + " uur, " + str(minutes) + " minuten en " + str(seconds) + " seconden tot 420!!"
|
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)
|
@commands.command(pass_context=True, hidden=False)
|
||||||
@asyncio.coroutine
|
async def iselderscrolls6aluit(self, ctx):
|
||||||
def iselderscrolls6aluit(self, ctx):
|
|
||||||
"""Hoe lang nog tot Elder Scrolls 6? 11-11-11? 20-20-20?
|
"""Hoe lang nog tot Elder Scrolls 6? 11-11-11? 20-20-20?
|
||||||
Gebruik: !iselderscrolls6aluit
|
Gebruik: !iselderscrolls6aluit
|
||||||
"""
|
"""
|
||||||
Now = datetime.now()
|
Now = datetime.now()
|
||||||
|
|
||||||
if Now.month == 4 and Now.day == 1:
|
if Now.month == 4 and Now.day == 1:
|
||||||
Message = "JA! :hushed: " #1 april, motherfucker.
|
Message = "JA! :hushed: " #1 april, motherfucker.
|
||||||
else:
|
else:
|
||||||
Message = "Nee. :frowning2: Nog even geduld..."
|
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):
|
def get_giet_het_oan(self):
|
||||||
# Alsof we ooit nog een elfstedentocht gaan krijgen.
|
# Alsof we ooit nog een elfstedentocht gaan krijgen.
|
||||||
return "nee"
|
return "nee"
|
||||||
|
|
||||||
@commands.command(pass_context=True, hidden=False)
|
@commands.command(pass_context=True, hidden=False)
|
||||||
@asyncio.coroutine
|
async def giethetaloan(self, ctx):
|
||||||
def giethetaloan(self, ctx):
|
|
||||||
"""Giet het al oan?
|
"""Giet het al oan?
|
||||||
Ja of Nee.. kom op nou.
|
Ja of Nee.. kom op nou.
|
||||||
"""
|
"""
|
||||||
@@ -225,7 +224,7 @@ class Shitpost(commands.Cog):
|
|||||||
else:
|
else:
|
||||||
if 'nee' in answer:
|
if 'nee' in answer:
|
||||||
reactie += 'Nee helaas..'
|
reactie += 'Nee helaas..'
|
||||||
yield from ctx.channel.send(ctx.author.mention + ' ' + reactie)
|
await ctx.channel.send(ctx.author.mention + ' ' + reactie)
|
||||||
|
|
||||||
def get_inspiration(self):
|
def get_inspiration(self):
|
||||||
inspiration = requests.get(url='http://inspirobot.me/api?generate=true')
|
inspiration = requests.get(url='http://inspirobot.me/api?generate=true')
|
||||||
@@ -233,10 +232,9 @@ class Shitpost(commands.Cog):
|
|||||||
return inspiration.text
|
return inspiration.text
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
@commands.command(pass_context=True, hidden=False)
|
@commands.command(pass_context=True, hidden=False)
|
||||||
@asyncio.coroutine
|
async def inspire(self, ctx):
|
||||||
def inspire(self, ctx):
|
|
||||||
"""Laat je inspireren
|
"""Laat je inspireren
|
||||||
Bijvoorbeeld:
|
Bijvoorbeeld:
|
||||||
!inspire
|
!inspire
|
||||||
@@ -246,18 +244,18 @@ class Shitpost(commands.Cog):
|
|||||||
em = discord.Embed(title='Uw wijze woorden:', type='photo')
|
em = discord.Embed(title='Uw wijze woorden:', type='photo')
|
||||||
em.set_image(url=inspo)
|
em.set_image(url=inspo)
|
||||||
try:
|
try:
|
||||||
yield from ctx.message.delete()
|
await ctx.message.delete()
|
||||||
except:
|
except:
|
||||||
print("No permission to delete message")
|
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:
|
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):
|
def get_imgflip_embed(self, template: str, boven: str, onder: str, extra_options: dict = None):
|
||||||
params = dict(
|
params = dict(
|
||||||
template_id = template,
|
template_id = template,
|
||||||
username = 'Stroopwafel',
|
username = 'Stroopwafel',
|
||||||
password = os.getenv("STROOP_IMGFLIP_PASSWORD"),
|
password = os.getenv("STROOP_IMGFLIP_PASSWORD"),
|
||||||
text0 = boven,
|
text0 = boven,
|
||||||
text1 = onder
|
text1 = onder
|
||||||
)
|
)
|
||||||
@@ -273,50 +271,47 @@ class Shitpost(commands.Cog):
|
|||||||
|
|
||||||
|
|
||||||
@commands.command(pass_context=True, hidden=True)
|
@commands.command(pass_context=True, hidden=True)
|
||||||
@asyncio.coroutine
|
async def tering(self, ctx, boven: str, onder: str):
|
||||||
def tering(self, ctx, boven: str, onder: str):
|
|
||||||
"""Vanavond gaan we helemaal naar de tering
|
"""Vanavond gaan we helemaal naar de tering
|
||||||
Bijvoorbeeld:
|
Bijvoorbeeld:
|
||||||
!tering \"Vanavond\" \"gaan we helemaal naar de tering\"
|
!tering \"Vanavond\" \"gaan we helemaal naar de tering\"
|
||||||
"""
|
"""
|
||||||
em = self.get_imgflip_embed(self.imgflips['tering'], boven, onder)
|
em = self.get_imgflip_embed(self.imgflips['tering'], boven, onder)
|
||||||
try:
|
try:
|
||||||
yield from ctx.message.delete()
|
await ctx.message.delete()
|
||||||
except:
|
except:
|
||||||
print("No permission to delete message")
|
print("No permission to delete message")
|
||||||
if em:
|
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)
|
@commands.command(pass_context=True, hidden=True)
|
||||||
@asyncio.coroutine
|
async def mark(self, ctx, boven: str, onder: str):
|
||||||
def mark(self, ctx, boven: str, onder: str):
|
|
||||||
"""Maakt een mark meem.
|
"""Maakt een mark meem.
|
||||||
Bijvoorbeeld:
|
Bijvoorbeeld:
|
||||||
!mark \"je moeder\" \"is een hoer\"
|
!mark \"je moeder\" \"is een hoer\"
|
||||||
"""
|
"""
|
||||||
em = self.get_imgflip_embed(self.imgflips['mark'], boven, onder)
|
em = self.get_imgflip_embed(self.imgflips['mark'], boven, onder)
|
||||||
try:
|
try:
|
||||||
yield from ctx.message.delete()
|
await ctx.message.delete()
|
||||||
except:
|
except:
|
||||||
print("No permission to delete message")
|
print("No permission to delete message")
|
||||||
if em:
|
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)
|
@commands.command(pass_context=True, hidden=True)
|
||||||
@asyncio.coroutine
|
async def eriku(self, ctx, boven: str, onder: str):
|
||||||
def eriku(self, ctx, boven: str, onder: str):
|
|
||||||
"""Maakt een erik meem.
|
"""Maakt een erik meem.
|
||||||
Bijvoorbeeld:
|
Bijvoorbeeld:
|
||||||
!eriku \"je moeder\" \"is een hoer\"
|
!eriku \"je moeder\" \"is een hoer\"
|
||||||
"""
|
"""
|
||||||
em = self.get_imgflip_embed(self.imgflips['eriku'], boven, onder)
|
em = self.get_imgflip_embed(self.imgflips['eriku'], boven, onder)
|
||||||
try:
|
try:
|
||||||
yield from ctx.message.delete()
|
await ctx.message.delete()
|
||||||
except:
|
except:
|
||||||
print("No permission to delete message")
|
print("No permission to delete message")
|
||||||
if em:
|
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):
|
def get_tegeltje(self, tekst, auteur):
|
||||||
params = {
|
params = {
|
||||||
'text0': 'dummy0',
|
'text0': 'dummy0',
|
||||||
@@ -341,49 +336,45 @@ class Shitpost(commands.Cog):
|
|||||||
return self.get_imgflip_embed(self.imgflips['tegeltje'], "", "", params)
|
return self.get_imgflip_embed(self.imgflips['tegeltje'], "", "", params)
|
||||||
|
|
||||||
@commands.command(pass_context=True, hidden=True)
|
@commands.command(pass_context=True, hidden=True)
|
||||||
@asyncio.coroutine
|
async def tegeltje(self, ctx, tekst: str, auteur: str=" "):
|
||||||
def tegeltje(self, ctx, tekst: str, auteur: str=" "):
|
|
||||||
"""Maak een mooi tegeltje met volkswijsheid
|
"""Maak een mooi tegeltje met volkswijsheid
|
||||||
Bijvoorbeeld:
|
Bijvoorbeeld:
|
||||||
!tegeltje \"Oost west, 420 best\" \"Lourens\"
|
!tegeltje \"Oost west, 420 best\" \"Lourens\"
|
||||||
"""
|
"""
|
||||||
em = get_tegeltje(tekst, auteur)
|
em = self.get_tegeltje(tekst, auteur)
|
||||||
try:
|
try:
|
||||||
yield from ctx.message.delete()
|
await ctx.message.delete()
|
||||||
except:
|
except:
|
||||||
print("No permission to delete message")
|
print("No permission to delete message")
|
||||||
if em:
|
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)
|
@commands.command(pass_context=True, hidden=True)
|
||||||
@asyncio.coroutine
|
async def zout(self, ctx, boven: str, onder: str):
|
||||||
def zout(self, ctx, boven: str, onder: str):
|
|
||||||
"""Maakt een martijn-zout meem.
|
"""Maakt een martijn-zout meem.
|
||||||
Bijvoorbeeld:
|
Bijvoorbeeld:
|
||||||
!zout \"je moeder\" \"is een hoer\"
|
!zout \"je moeder\" \"is een hoer\"
|
||||||
"""
|
"""
|
||||||
em = self.get_imgflip_embed(self.imgflips['zout'], boven, onder)
|
em = self.get_imgflip_embed(self.imgflips['zout'], boven, onder)
|
||||||
try:
|
try:
|
||||||
yield from ctx.message.delete()
|
await ctx.message.delete()
|
||||||
except:
|
except:
|
||||||
print("No permission to delete message")
|
print("No permission to delete message")
|
||||||
if em:
|
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)
|
@commands.command(pass_context=True, hidden=True)
|
||||||
@asyncio.coroutine
|
async def nihao(self,ctx):
|
||||||
def nihao(self,ctx):
|
await ctx.channel.send("kankerlauw")
|
||||||
yield from ctx.channel.send("kankerlauw")
|
|
||||||
|
|
||||||
@commands.command(pass_context=True)
|
@commands.command(pass_context=True)
|
||||||
@asyncio.coroutine
|
async def tijd(self, ctx, *args):
|
||||||
def tijd(self, ctx, *args):
|
|
||||||
"""Vertelt je hoe laat het is..
|
"""Vertelt je hoe laat het is..
|
||||||
Misschien geeft het ook wel een leuke meem terug.
|
Misschien geeft het ook wel een leuke meem terug.
|
||||||
Wie weet.
|
Wie weet.
|
||||||
Probeer het eens op verschillende tijdstippen.
|
Probeer het eens op verschillende tijdstippen.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
time=datetime.now().strftime('%H%M')
|
time=datetime.now().strftime('%H%M')
|
||||||
for argument in args:
|
for argument in args:
|
||||||
time = argument
|
time = argument
|
||||||
@@ -398,20 +389,20 @@ class Shitpost(commands.Cog):
|
|||||||
elif os.path.isfile(filepng):
|
elif os.path.isfile(filepng):
|
||||||
filepath = filepng
|
filepath = filepng
|
||||||
try:
|
try:
|
||||||
yield from ctx.message.delete()
|
await ctx.message.delete()
|
||||||
except:
|
except:
|
||||||
print("No permission to delete message")
|
print("No permission to delete message")
|
||||||
if filepath != '':
|
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:
|
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):
|
def get_dice_roll(self, nrOfDice, dieType, modifier=None):
|
||||||
if nrOfDice > 99 or dieType > 9999 or dieType < 2 or (modifier and abs(modifier) > 9999):
|
if nrOfDice > 99 or dieType > 9999 or dieType < 2 or (modifier and abs(modifier) > 9999):
|
||||||
return None
|
return None
|
||||||
|
|
||||||
# Do the rolling
|
# Do the rolling
|
||||||
random.seed(datetime.now())
|
random.seed(datetime.now().timestamp())
|
||||||
total = 0
|
total = 0
|
||||||
rolls = []
|
rolls = []
|
||||||
for x in range(0, nrOfDice):
|
for x in range(0, nrOfDice):
|
||||||
@@ -447,8 +438,7 @@ class Shitpost(commands.Cog):
|
|||||||
return (numDice, die, modifier)
|
return (numDice, die, modifier)
|
||||||
|
|
||||||
@commands.command(pass_context=True)
|
@commands.command(pass_context=True)
|
||||||
@asyncio.coroutine
|
async def roll(self, ctx, *, dice):
|
||||||
def roll(self, ctx, *, dice):
|
|
||||||
"""Roll een dobbelsteen. Of een paar. Bijvoorbeeld:
|
"""Roll een dobbelsteen. Of een paar. Bijvoorbeeld:
|
||||||
!roll 4d20
|
!roll 4d20
|
||||||
!roll 1d6 + 5
|
!roll 1d6 + 5
|
||||||
@@ -456,10 +446,10 @@ class Shitpost(commands.Cog):
|
|||||||
(nrOfDice, dieType, modifier) = self.get_dice_parameters(dice)
|
(nrOfDice, dieType, modifier) = self.get_dice_parameters(dice)
|
||||||
message = self.get_dice_roll(nrOfDice, dieType, modifier)
|
message = self.get_dice_roll(nrOfDice, dieType, modifier)
|
||||||
if message:
|
if message:
|
||||||
yield from ctx.channel.send(message)
|
await ctx.channel.send(message)
|
||||||
else:
|
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):
|
def get_weerbericht(self, wData, verbose=None):
|
||||||
if not wData:
|
if not wData:
|
||||||
return None
|
return None
|
||||||
@@ -478,8 +468,8 @@ class Shitpost(commands.Cog):
|
|||||||
message += self.getWeatherIconTranslation( wData["image"] )
|
message += self.getWeatherIconTranslation( wData["image"] )
|
||||||
message += " Het is " + wData["temp"] + " graden "
|
message += " Het is " + wData["temp"] + " graden "
|
||||||
message += "en het weer is: " + wData["samenv"] + ". "
|
message += "en het weer is: " + wData["samenv"] + ". "
|
||||||
message += "De verwachting: " + wData["verw"]
|
message += "De verwachting: " + wData["verw"]
|
||||||
|
|
||||||
if (verbose):
|
if (verbose):
|
||||||
# Only print tomorrow, the day after and the BBQ grade if verbose is on:
|
# Only print tomorrow, the day after and the BBQ grade if verbose is on:
|
||||||
message += "\n\nMorgen: " + self.getWeatherIconTranslation( wData["d1weer"] )
|
message += "\n\nMorgen: " + self.getWeatherIconTranslation( wData["d1weer"] )
|
||||||
@@ -501,13 +491,13 @@ class Shitpost(commands.Cog):
|
|||||||
message += "Kans op neerslag: " + wData["d2neerslag"] + "%. "
|
message += "Kans op neerslag: " + wData["d2neerslag"] + "%. "
|
||||||
if (int(wData["d2windk"]) > 5):
|
if (int(wData["d2windk"]) > 5):
|
||||||
message += "Windkracht " + wData["d2windk"] + ". "
|
message += "Windkracht " + wData["d2windk"] + ". "
|
||||||
|
|
||||||
bbqGrade = self.getBbqGrade(wData)
|
bbqGrade = self.getBbqGrade(wData)
|
||||||
message += "\n\nHet BBQ cijfer voor vandaag is: " + '{0:g}'.format(round(bbqGrade, 1))
|
message += "\n\nHet BBQ cijfer voor vandaag is: " + '{0:g}'.format(round(bbqGrade, 1))
|
||||||
|
|
||||||
message += "\n\nOant Moarn!"
|
message += "\n\nOant Moarn!"
|
||||||
return message
|
return message
|
||||||
|
|
||||||
|
|
||||||
def get_weer_json(self, location=None):
|
def get_weer_json(self, location=None):
|
||||||
if not location:
|
if not location:
|
||||||
@@ -519,8 +509,7 @@ class Shitpost(commands.Cog):
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
@commands.command(pass_context=True)
|
@commands.command(pass_context=True)
|
||||||
@asyncio.coroutine
|
async def weer(self, ctx, location="Leiden", verbose=None):
|
||||||
def weer(self, ctx, location="Leiden", verbose=None):
|
|
||||||
"""Vertelt je het weer.
|
"""Vertelt je het weer.
|
||||||
Omdat je te lui bent om naar buiten te kijken.
|
Omdat je te lui bent om naar buiten te kijken.
|
||||||
Oant Moarn!
|
Oant Moarn!
|
||||||
@@ -530,8 +519,8 @@ class Shitpost(commands.Cog):
|
|||||||
message = self.get_weerbericht(wData, verbose)
|
message = self.get_weerbericht(wData, verbose)
|
||||||
if not wData or not message:
|
if not wData or not message:
|
||||||
message = "Weer ophalen niet gelukt. Probeer het later nogmaals.."
|
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
|
#returns a nice weather icon. Sometimes the API uses non-documented icons, so we return something else
|
||||||
def getWeatherIconTranslation(self, iconKey):
|
def getWeatherIconTranslation(self, iconKey):
|
||||||
WEATHER_ICONS = {
|
WEATHER_ICONS = {
|
||||||
@@ -554,7 +543,7 @@ class Shitpost(commands.Cog):
|
|||||||
return WEATHER_ICONS[iconKey]
|
return WEATHER_ICONS[iconKey]
|
||||||
except KeyError:
|
except KeyError:
|
||||||
return ":park:"
|
return ":park:"
|
||||||
|
|
||||||
def getWeerAlarm(self, weatherObj):
|
def getWeerAlarm(self, weatherObj):
|
||||||
if (weatherObj["alarm"] != "1"):
|
if (weatherObj["alarm"] != "1"):
|
||||||
return None, ""
|
return None, ""
|
||||||
@@ -563,7 +552,7 @@ class Shitpost(commands.Cog):
|
|||||||
if ("code oranje" in weatherObj["alarmtxt"].lower()):
|
if ("code oranje" in weatherObj["alarmtxt"].lower()):
|
||||||
return "oranje", "PAS OP! :large_orange_diamond: Code Oranje :large_orange_diamond: is van kracht! <:willy:505886070668263426> " + weatherObj["alarmtxt"]
|
return "oranje", "PAS OP! :large_orange_diamond: Code Oranje :large_orange_diamond: is van kracht! <:willy:505886070668263426> " + weatherObj["alarmtxt"]
|
||||||
return "geel", ":warning: Kennelijk is er een weeralarm: " + weatherObj["alarmtxt"]
|
return "geel", ":warning: Kennelijk is er een weeralarm: " + weatherObj["alarmtxt"]
|
||||||
|
|
||||||
#determines a BBQ grade based on the current weather
|
#determines a BBQ grade based on the current weather
|
||||||
def getBbqGrade(self, weatherObj):
|
def getBbqGrade(self, weatherObj):
|
||||||
grade = 1.0
|
grade = 1.0
|
||||||
@@ -579,12 +568,12 @@ class Shitpost(commands.Cog):
|
|||||||
if float(weatherObj["d0neerslag"]) < 10:
|
if float(weatherObj["d0neerslag"]) < 10:
|
||||||
if weatherObj["image"] in ["regen", "buien", "bliksem", "hagel", "sneeuw", "halfbewolkt_regen"]:
|
if weatherObj["image"] in ["regen", "buien", "bliksem", "hagel", "sneeuw", "halfbewolkt_regen"]:
|
||||||
grade -= 2.0
|
grade -= 2.0
|
||||||
|
|
||||||
#remove points for very hot weather: (above 30)
|
#remove points for very hot weather: (above 30)
|
||||||
grade -= max(0, (float(weatherObj["d0tmax"]) - 30.0)/10 )
|
grade -= max(0, (float(weatherObj["d0tmax"]) - 30.0)/10 )
|
||||||
except:
|
except:
|
||||||
return -1.0
|
return -1.0
|
||||||
|
|
||||||
return max(1.0, min(10.0, grade))
|
return max(1.0, min(10.0, grade))
|
||||||
|
|
||||||
def get_ktdm(self, wit = []):
|
def get_ktdm(self, wit = []):
|
||||||
@@ -606,31 +595,29 @@ class Shitpost(commands.Cog):
|
|||||||
break
|
break
|
||||||
if not zwarte_kaart:
|
if not zwarte_kaart:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
return zwarte_kaart.replace("___", "**{}**").format(*wit)
|
return zwarte_kaart.replace("___", "**{}**").format(*wit)
|
||||||
|
|
||||||
@commands.command(pass_context=True)
|
@commands.command(pass_context=True)
|
||||||
@asyncio.coroutine
|
async def ktdm(self, ctx, *args):
|
||||||
def ktdm(self, ctx, *args):
|
|
||||||
'''Speel Kaarten Tegen De Mensheid! Genereer een kaart of geef zelf opties.
|
'''Speel Kaarten Tegen De Mensheid! Genereer een kaart of geef zelf opties.
|
||||||
Bijvoorbeeld: !ktdm <"1"><"2"><"3"> (aanbevolen 1 of 2, max 3)'''
|
Bijvoorbeeld: !ktdm <"1"><"2"><"3"> (aanbevolen 1 of 2, max 3)'''
|
||||||
try:
|
try:
|
||||||
yield from ctx.message.delete()
|
await ctx.message.delete()
|
||||||
except:
|
except:
|
||||||
print("No permission to delete message")
|
print("No permission to delete message")
|
||||||
resultaat = self.get_ktdm(args)
|
resultaat = self.get_ktdm(args)
|
||||||
if resultaat:
|
if resultaat:
|
||||||
yield from ctx.channel.send(f"{ctx.author.mention}\n{resultaat}")
|
await ctx.channel.send(f"{ctx.author.mention}\n{resultaat}")
|
||||||
else:
|
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)
|
@commands.command(pass_context=True)
|
||||||
@asyncio.coroutine
|
async def beledig(self, ctx, member:discord.User):
|
||||||
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!
|
'''Je vindt iemand stom maar je hebt geen inspiratie? Beledig al je vriendjes met deze handige beledig-i-fier!
|
||||||
Bijvoorbeeld: !beledig @jemoeder'''
|
Bijvoorbeeld: !beledig @jemoeder'''
|
||||||
yield from ctx.channel.send(member.mention+ ", " + ctx.author.mention + " vindt jou een " + random.choice(self.insult) + "! :angry:")
|
await ctx.channel.send(member.mention+ ", " + ctx.author.mention + " vindt jou een " + random.choice(self.insult) + "! :angry:")
|
||||||
yield from ctx.message.delete()
|
await ctx.message.delete()
|
||||||
|
|
||||||
def get_watspelenwe_cal(self):
|
def get_watspelenwe_cal(self):
|
||||||
"""Geeft een paar terug, met de titel en omschrijving van het eerstvolgende event uit de kalender"""
|
"""Geeft een paar terug, met de titel en omschrijving van het eerstvolgende event uit de kalender"""
|
||||||
@@ -659,23 +646,23 @@ class Shitpost(commands.Cog):
|
|||||||
"een systeem waar Lourens de boeken van online heeft gezet. FYI Mark speelt een dwerg, Guus is er in sessie twee pas bij (speelt ook een dwerg), Martijn iets met een accent en explosieven, Freek speelt Bob de Rooij en JP speelt het enige karakter wat het plot vooruit helpt godzijdank."
|
"een systeem waar Lourens de boeken van online heeft gezet. FYI Mark speelt een dwerg, Guus is er in sessie twee pas bij (speelt ook een dwerg), Martijn iets met een accent en explosieven, Freek speelt Bob de Rooij en JP speelt het enige karakter wat het plot vooruit helpt godzijdank."
|
||||||
]
|
]
|
||||||
SPELLEN = [
|
SPELLEN = [
|
||||||
"DND", "Ars Magica",
|
"DND", "Ars Magica",
|
||||||
"een one-shot", "Kaarten tegen de Mensheid",
|
"een one-shot", "Kaarten tegen de Mensheid",
|
||||||
"Cyberpunk 2020", "Star Wars",
|
"Cyberpunk 2020", "Star Wars",
|
||||||
"Blades in the Dark",
|
"Blades in the Dark",
|
||||||
"Expeditie Acquisitie", "Starfinder"
|
"Expeditie Acquisitie", "Starfinder"
|
||||||
]
|
]
|
||||||
PLAATSEN = [
|
PLAATSEN = [
|
||||||
"bij Mark thuis", "bij Freek thuis",
|
"bij Mark thuis", "bij Freek thuis",
|
||||||
"bij JP thuis", "bij Erik thuis",
|
"bij JP thuis", "bij Erik thuis",
|
||||||
"bij Lourens thuis", "in de Vrouwensteeg",
|
"bij Lourens thuis", "in de Vrouwensteeg",
|
||||||
"bij Martijn thuis", "bij je moeder thuis",
|
"bij Martijn thuis", "bij je moeder thuis",
|
||||||
"bij de Privé2000", "Vakantiepark Landal Kasteeldomein de Cauberg"
|
"bij de Privé2000", "Vakantiepark Landal Kasteeldomein de Cauberg"
|
||||||
]
|
]
|
||||||
AANVANG = [
|
AANVANG = [
|
||||||
"17:00.", "17:30.",
|
"17:00.", "17:30.",
|
||||||
"18:00.", "wanneer Lourens vrijgelaten wordt door de burgemeester.",
|
"18:00.", "wanneer Lourens vrijgelaten wordt door de burgemeester.",
|
||||||
"nadat de big in de bakfiets is langsgeweest.", "na Lourens' t-break.",
|
"nadat de big in de bakfiets is langsgeweest.", "na Lourens' t-break.",
|
||||||
"als Mark zijn frikadelbroodjes heeft.", "wanneer Martijn de datumprikker heeft ingevuld",
|
"als Mark zijn frikadelbroodjes heeft.", "wanneer Martijn de datumprikker heeft ingevuld",
|
||||||
"nadat iedereen tot 20:30 het uitgebreid over databases \"bij ons op het werk\" heeft gehad en de DM er een sarcastische opmerking over maakt.",
|
"nadat iedereen tot 20:30 het uitgebreid over databases \"bij ons op het werk\" heeft gehad en de DM er een sarcastische opmerking over maakt.",
|
||||||
"na een flinke portie slap gelul.", "nadat Mark tenminste 20 plaatjes in #tiger-girls heeft gepost.",
|
"na een flinke portie slap gelul.", "nadat Mark tenminste 20 plaatjes in #tiger-girls heeft gepost.",
|
||||||
@@ -683,15 +670,15 @@ class Shitpost(commands.Cog):
|
|||||||
"ongeveer een uur voordat JP's trein gaat."
|
"ongeveer een uur voordat JP's trein gaat."
|
||||||
]
|
]
|
||||||
PERSONEN = [
|
PERSONEN = [
|
||||||
"Mark", "Lourens", "JP",
|
"Mark", "Lourens", "JP",
|
||||||
"Freek", "Martijn", "Erik"
|
"Freek", "Martijn", "Erik"
|
||||||
]
|
]
|
||||||
VIDYA = [
|
VIDYA = [
|
||||||
"Factorio.", "Terraria.",
|
"Factorio.", "Terraria.",
|
||||||
"Factorio maar dan moet Martijn 5gr wiet inhaleren en Lourens 5mg ritalin slikken en dan kunnen JP en Mark fijn spelen.",
|
"Factorio maar dan moet Martijn 5gr wiet inhaleren en Lourens 5mg ritalin slikken en dan kunnen JP en Mark fijn spelen.",
|
||||||
"Terraria prepare to restart world edition.",
|
"Terraria prepare to restart world edition.",
|
||||||
"Crusader Kings III.", "Deep Rock Galactic.",
|
"Crusader Kings III.", "Deep Rock Galactic.",
|
||||||
"Dota 2.", "Minecraft.",
|
"Dota 2.", "Minecraft.",
|
||||||
"Minecraft met mods waardoor Guus niet mee kan doen maar maakt niet uit ik vond mijn huis toch leuker zonder TNT-traps.",
|
"Minecraft met mods waardoor Guus niet mee kan doen maar maakt niet uit ik vond mijn huis toch leuker zonder TNT-traps.",
|
||||||
"Minecraft met een of andere kutmodpack die Martijn gevonden heeft waardoor je de meeste troep niet zo maar kunt craften.",
|
"Minecraft met een of andere kutmodpack die Martijn gevonden heeft waardoor je de meeste troep niet zo maar kunt craften.",
|
||||||
"Golf with y- oh het werkt niet op Linux? Oh jeetje oh nee, ja wat moeten we? Misschien kunnen we een ander spelletje - ja echt sorry ik weet het ook niet.",
|
"Golf with y- oh het werkt niet op Linux? Oh jeetje oh nee, ja wat moeten we? Misschien kunnen we een ander spelletje - ja echt sorry ik weet het ook niet.",
|
||||||
@@ -725,7 +712,7 @@ class Shitpost(commands.Cog):
|
|||||||
lekkerzaad += 1
|
lekkerzaad += 1
|
||||||
|
|
||||||
random.seed(lekkerzaad)
|
random.seed(lekkerzaad)
|
||||||
|
|
||||||
if Now.weekday() == 4:
|
if Now.weekday() == 4:
|
||||||
DAG = "vandaag "
|
DAG = "vandaag "
|
||||||
else:
|
else:
|
||||||
@@ -736,21 +723,20 @@ class Shitpost(commands.Cog):
|
|||||||
if KEUZEMOGELIJKHEDEN == 10:
|
if KEUZEMOGELIJKHEDEN == 10:
|
||||||
message = "We spelen " + DAG + random.choice(SASS)# + " Nee, we spelen eigenlijk " + random.choice(SPELLEN) + ", aanvang " + random.choice(AANVANG)
|
message = "We spelen " + DAG + random.choice(SASS)# + " Nee, we spelen eigenlijk " + random.choice(SPELLEN) + ", aanvang " + random.choice(AANVANG)
|
||||||
elif KEUZEMOGELIJKHEDEN == 9:
|
elif KEUZEMOGELIJKHEDEN == 9:
|
||||||
message = random.choice(PERSONEN) + " " + random.choice(GEBEURTENIS) + " " + random.choice(VIDYA)
|
message = random.choice(PERSONEN) + " " + random.choice(GEBEURTENIS) + " " + random.choice(VIDYA)
|
||||||
elif KEUZEMOGELIJKHEDEN == 8:
|
elif KEUZEMOGELIJKHEDEN == 8:
|
||||||
message = "We gaan " + DAG + "poppetjes verven " + random.choice(PLAATSEN) + ", aanvang " + random.choice(AANVANG)
|
message = "We gaan " + DAG + "poppetjes verven " + random.choice(PLAATSEN) + ", aanvang " + random.choice(AANVANG)
|
||||||
elif KEUZEMOGELIJKHEDEN == 7:
|
elif KEUZEMOGELIJKHEDEN == 7:
|
||||||
message = "We spelen " + DAG + random.choice(SPELLEN) + " " + random.choice(PLAATSEN) + ", aanvang " + random.choice(AANVANG) + random.choice(EXTRA)
|
message = "We spelen " + DAG + random.choice(SPELLEN) + " " + random.choice(PLAATSEN) + ", aanvang " + random.choice(AANVANG) + random.choice(EXTRA)
|
||||||
elif KEUZEMOGELIJKHEDEN == 6:
|
elif KEUZEMOGELIJKHEDEN == 6:
|
||||||
message = "We spelen " + DAG + random.choice(VIDYA) + " Ja, ik weet het, eigenlijk \"D&D\"-avond maar ja. Wees nou eerlijk heh. Aanvang " + random.choice(AANVANG)
|
message = "We spelen " + DAG + random.choice(VIDYA) + " Ja, ik weet het, eigenlijk \"D&D\"-avond maar ja. Wees nou eerlijk heh. Aanvang " + random.choice(AANVANG)
|
||||||
else:
|
else:
|
||||||
message = "We spelen " + DAG + random.choice(SPELLEN) + " " + random.choice(PLAATSEN) + ", aanvang " + random.choice(AANVANG)
|
message = "We spelen " + DAG + random.choice(SPELLEN) + " " + random.choice(PLAATSEN) + ", aanvang " + random.choice(AANVANG)
|
||||||
|
|
||||||
return message
|
return message
|
||||||
|
|
||||||
@commands.command(pass_context=True)
|
@commands.command(pass_context=True)
|
||||||
@asyncio.coroutine
|
async def watspelenwe(self, ctx):
|
||||||
def watspelenwe(self, ctx):
|
|
||||||
"""Stroop weet wat we spelen op vrijdag.
|
"""Stroop weet wat we spelen op vrijdag.
|
||||||
Geeft elke week een pseudo-random antwoord.
|
Geeft elke week een pseudo-random antwoord.
|
||||||
Geseed op weeknummer + jaar.
|
Geseed op weeknummer + jaar.
|
||||||
@@ -764,19 +750,19 @@ class Shitpost(commands.Cog):
|
|||||||
message += ". En wilt iemand even aan Mark vragen of hij de kalender bijhoudt?"
|
message += ". En wilt iemand even aan Mark vragen of hij de kalender bijhoudt?"
|
||||||
|
|
||||||
try:
|
try:
|
||||||
yield from ctx.message.delete()
|
await ctx.message.delete()
|
||||||
except:
|
except:
|
||||||
print("No permission to delete message")
|
print("No permission to delete message")
|
||||||
yield from ctx.channel.send(message)
|
await ctx.channel.send(message)
|
||||||
|
|
||||||
def get_review_string(self, topic = ""):
|
def get_review_string(self, topic = ""):
|
||||||
if topic == "":
|
if topic == "":
|
||||||
random.seed(datetime.now().timestamp())
|
random.seed(datetime.now().timestamp())
|
||||||
else:
|
else:
|
||||||
random.seed(topic.lower().replace(" ", ""))
|
random.seed(topic.lower().replace(" ", ""))
|
||||||
|
|
||||||
message = ""
|
message = ""
|
||||||
|
|
||||||
if topic == "":
|
if topic == "":
|
||||||
REVIEW_START = [
|
REVIEW_START = [
|
||||||
"Ik vond 'm", "Ik vind 'm", "Ik vond het", "Ik vind het", "Als je het mij vraagt was ie", "Mijn mening:",
|
"Ik vond 'm", "Ik vind 'm", "Ik vond het", "Ik vind het", "Als je het mij vraagt was ie", "Mijn mening:",
|
||||||
@@ -788,7 +774,7 @@ class Shitpost(commands.Cog):
|
|||||||
"Ik ben geen expert, maar ik vond "+topic, topic+" was", topic+" is", topic+" is gewoon", "Mijn mening over "+topic+ ":",
|
"Ik ben geen expert, maar ik vond "+topic, topic+" was", topic+" is", topic+" is gewoon", "Mijn mening over "+topic+ ":",
|
||||||
"Mijn review van "+topic+ ":"
|
"Mijn review van "+topic+ ":"
|
||||||
]
|
]
|
||||||
|
|
||||||
SHORT_REVIEW = [
|
SHORT_REVIEW = [
|
||||||
"goed.", "goed!", "echt goed!", "prima.", "top.", "helemaal toppie!", "ruk.", "middelmatig.",
|
"goed.", "goed!", "echt goed!", "prima.", "top.", "helemaal toppie!", "ruk.", "middelmatig.",
|
||||||
"goed te doen.", "belabberd.", "uitstekend!", "uitmuntend.", "een beetje saai.", "supersick, yo.",
|
"goed te doen.", "belabberd.", "uitstekend!", "uitmuntend.", "een beetje saai.", "supersick, yo.",
|
||||||
@@ -799,10 +785,10 @@ class Shitpost(commands.Cog):
|
|||||||
":watermelon:", ":middle_finger:", ":poop:", ":banana:", ":eggplant:", ":red_car:", ":gem:",
|
":watermelon:", ":middle_finger:", ":poop:", ":banana:", ":eggplant:", ":red_car:", ":gem:",
|
||||||
":heart:", ":flag_nl: ", ":cow:", ":dolphin:", ":four_leaf_clover:", ":basketball: ", ":thumbsup:"
|
":heart:", ":flag_nl: ", ":cow:", ":dolphin:", ":four_leaf_clover:", ":basketball: ", ":thumbsup:"
|
||||||
]
|
]
|
||||||
|
|
||||||
message = random.choice(REVIEW_START) + " "
|
message = random.choice(REVIEW_START) + " "
|
||||||
message += random.choice(SHORT_REVIEW) + " "
|
message += random.choice(SHORT_REVIEW) + " "
|
||||||
|
|
||||||
pickerScore = random.randint(1, 10)
|
pickerScore = random.randint(1, 10)
|
||||||
if pickerScore < 7:
|
if pickerScore < 7:
|
||||||
rating = random.randint(1, 5)
|
rating = random.randint(1, 5)
|
||||||
@@ -816,13 +802,54 @@ class Shitpost(commands.Cog):
|
|||||||
emoj = random.choice(EMOJI)
|
emoj = random.choice(EMOJI)
|
||||||
message += str(rating) + " " + emoj*rating + " out of " + str(maxRating) + "."
|
message += str(rating) + " " + emoj*rating + " out of " + str(maxRating) + "."
|
||||||
|
|
||||||
return message
|
return message
|
||||||
|
|
||||||
@commands.command(pass_context=True)
|
@commands.command(pass_context=True)
|
||||||
@asyncio.coroutine
|
async def review(self, ctx, *args):
|
||||||
def review(self, ctx, *args):
|
|
||||||
"""Stroop heeft (bijna) overal een mening over. Vraag het hem!
|
"""Stroop heeft (bijna) overal een mening over. Vraag het hem!
|
||||||
"""
|
"""
|
||||||
topic = " ".join(args)
|
topic = " ".join(args)
|
||||||
message = self.get_review_string(topic)
|
message = self.get_review_string(topic)
|
||||||
yield from ctx.channel.send(message)
|
await ctx.channel.send(message)
|
||||||
|
|
||||||
|
def get_zaagmans(self):
|
||||||
|
now = datetime.now(self.TIME_ZONE)
|
||||||
|
|
||||||
|
if now.weekday() in (5, 6): # za, zo
|
||||||
|
return "Ga weekend vieren of zo."
|
||||||
|
|
||||||
|
noon_today = now.replace(hour=12, minute=0, second=0, microsecond=0)
|
||||||
|
if now.weekday() == 2 and now >= noon_today: # als woensdag na 12:00
|
||||||
|
return "Zaagmans heeft de week doormidden gezaagd!"
|
||||||
|
|
||||||
|
# tijd tot volgende woensdag 12:00. % 7 wraps als al geweest die week. vb zondag 6; (-4 % 7 = 3 dagen)
|
||||||
|
zaagmans_o_clock = noon_today + timedelta(days=(2 - now.weekday()) % 7)
|
||||||
|
if zaagmans_o_clock <= now:
|
||||||
|
zaagmans_o_clock += timedelta(days=7)
|
||||||
|
time_til_zaagmans = zaagmans_o_clock - now
|
||||||
|
|
||||||
|
if time_til_zaagmans <= timedelta(hours=5):
|
||||||
|
return "Zaagmans komt bijna, nog even geduld!" # I'm epsilon there!
|
||||||
|
|
||||||
|
whole_days = time_til_zaagmans.days
|
||||||
|
extra_hours = time_til_zaagmans.seconds // 3600
|
||||||
|
day_suffix = ""
|
||||||
|
if whole_days != 1:
|
||||||
|
day_suffix = "en"
|
||||||
|
if whole_days == 0:
|
||||||
|
time_to_wait = "minder dan 1 dag"
|
||||||
|
elif extra_hours >= 12:
|
||||||
|
time_to_wait = f"iets minder dan {whole_days + 1} dagen"
|
||||||
|
else:
|
||||||
|
time_to_wait = f"iets meer dan {whole_days} dag{day_suffix}"
|
||||||
|
|
||||||
|
if now.weekday() in (3,4): # do, vr
|
||||||
|
return f"Zaagmans heeft de week doormidden gezaagd en komt pas weer over {time_to_wait}."
|
||||||
|
else: # ma, di, wo tot 7:00
|
||||||
|
return f"Helaas, meneer Zaagmans is nog niet langsgeweest om de week doormidden te zagen. Nog {time_to_wait} wachten."
|
||||||
|
|
||||||
|
@commands.command()
|
||||||
|
async def zaagmans(self, ctx):
|
||||||
|
"""Is zaagmans al langsgeweest? Is de week al doormidden. Wie weet."""
|
||||||
|
message = ctx.author.mention + ": " + self.get_zaagmans()
|
||||||
|
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 = 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
|
@bot.event
|
||||||
async def on_ready():
|
async def on_ready():
|
||||||
await add_cogs(bot)
|
await add_cogs(bot)
|
||||||
|
|||||||
@@ -14,3 +14,4 @@ STROOP_IMGFLIP_PASSWORD=
|
|||||||
STROOP_RESET_PASSWORD=
|
STROOP_RESET_PASSWORD=
|
||||||
STROOP_CHANNEL_SHITPOST=
|
STROOP_CHANNEL_SHITPOST=
|
||||||
STROOP_CHANNEL_BELANGRIJK=
|
STROOP_CHANNEL_BELANGRIJK=
|
||||||
|
STROOP_HDCON_DATE=2025-12-01
|
||||||
@@ -3,3 +3,6 @@ discord.py
|
|||||||
praw
|
praw
|
||||||
numpy
|
numpy
|
||||||
python-dotenv
|
python-dotenv
|
||||||
|
feedparser
|
||||||
|
audioop-lts
|
||||||
|
vobject
|
||||||
+2
-2
@@ -41,9 +41,9 @@ class TestGeneral(unittest.TestCase):
|
|||||||
if not isinstance(self.cog.r, praw.Reddit):
|
if not isinstance(self.cog.r, praw.Reddit):
|
||||||
self.skipTest("PRAW Reddit instance failed to create")
|
self.skipTest("PRAW Reddit instance failed to create")
|
||||||
post = self.cog.get_kopieerpasta()
|
post = self.cog.get_kopieerpasta()
|
||||||
self.assertIsInstance(post.url, str)
|
if post:
|
||||||
|
self.assertIsInstance(post.url, str)
|
||||||
|
|
||||||
def test_huge(self):
|
def test_huge(self):
|
||||||
embed = self.cog.get_emoji_embed("<:test:123456789>")
|
embed = self.cog.get_emoji_embed("<:test:123456789>")
|
||||||
self.assertIsInstance(embed, discord.Embed)
|
self.assertIsInstance(embed, discord.Embed)
|
||||||
|
|
||||||
+9
-1
@@ -3,6 +3,7 @@ import dotenv
|
|||||||
import os
|
import os
|
||||||
import discord
|
import discord
|
||||||
import requests
|
import requests
|
||||||
|
from datetime import datetime
|
||||||
from discord.ext import commands
|
from discord.ext import commands
|
||||||
|
|
||||||
import Shitpost
|
import Shitpost
|
||||||
@@ -39,7 +40,7 @@ class TestShitpost(unittest.TestCase):
|
|||||||
def test_watspelenwe_cal(self):
|
def test_watspelenwe_cal(self):
|
||||||
data = requests.get(os.getenv('STROOP_CALDAV_CAL'))
|
data = requests.get(os.getenv('STROOP_CALDAV_CAL'))
|
||||||
if not data:
|
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()
|
(activiteit, reden) = self.cog.get_watspelenwe_cal()
|
||||||
with self.subTest(msg="Watspelenwe activiteit does not return a string"):
|
with self.subTest(msg="Watspelenwe activiteit does not return a string"):
|
||||||
@@ -169,3 +170,10 @@ class TestShitpost(unittest.TestCase):
|
|||||||
message = self.cog.zalgofy(inmsg)
|
message = self.cog.zalgofy(inmsg)
|
||||||
self.assertIsInstance(message, str)
|
self.assertIsInstance(message, str)
|
||||||
self.assertEqual(len(message), len(inmsg)*5)
|
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)
|
||||||
Reference in new issue
Block a user