Compare commits
35
Commits
gpt
..
925e908865
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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 |
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.11
|
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:
|
||||||
|
|||||||
+65
-6
@@ -5,6 +5,8 @@ import random
|
|||||||
import requests
|
import requests
|
||||||
import asyncio
|
import asyncio
|
||||||
import os
|
import os
|
||||||
|
import feedparser
|
||||||
|
import json
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
import re
|
import re
|
||||||
|
|
||||||
@@ -18,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:
|
||||||
@@ -46,7 +50,6 @@ class Chatbot(commands.Cog):
|
|||||||
"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.getResponseForMessageLocal("stroopwafel")
|
||||||
]
|
]
|
||||||
try:
|
try:
|
||||||
@@ -222,6 +225,11 @@ 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:
|
||||||
@@ -288,11 +296,13 @@ class Chatbot(commands.Cog):
|
|||||||
await message.channel.send(response)
|
await message.channel.send(response)
|
||||||
|
|
||||||
#Gets a response
|
#Gets a response
|
||||||
async def getResponseForMessage(self, wordsToRespondTo):
|
async def getResponseForMessage(self, wordsToRespondTo, gptChance=0.1):
|
||||||
if random.random() > 0.9:
|
if random.random() < 1-gptChance:
|
||||||
try:
|
try:
|
||||||
# GPT request moet echt even in een non-blocking executortje, anders loopt de hele boel vast
|
# GPT request moet echt even in een non-blocking executortje, anders loopt de hele boel vast
|
||||||
return await self.bot.loop.run_in_executor(None,self.getResponseForMessageOnline, wordsToRespondTo)
|
response = await self.bot.loop.run_in_executor(None,self.getResponseForMessageOnline, wordsToRespondTo)
|
||||||
|
if response:
|
||||||
|
return response # Anders door naar local
|
||||||
except:
|
except:
|
||||||
pass # Door naar local call
|
pass # Door naar local call
|
||||||
return self.getResponseForMessageLocal(wordsToRespondTo)
|
return self.getResponseForMessageLocal(wordsToRespondTo)
|
||||||
@@ -303,8 +313,11 @@ class Chatbot(commands.Cog):
|
|||||||
return req.json()["translations"][0]["text"]
|
return req.json()["translations"][0]["text"]
|
||||||
|
|
||||||
def getResponseForMessageOnline(self, wordsToRespondTo):
|
def getResponseForMessageOnline(self, wordsToRespondTo):
|
||||||
text = self.translateTo("en", " ".join(wordsToRespondTo))
|
prompt = " ".join(wordsToRespondTo)
|
||||||
req = requests.post('http://gpt.hoekveen.net/complete', json={"prompt": text, "max_tokens": 60})
|
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())
|
print(req.json())
|
||||||
respons = req.json()["text"]
|
respons = req.json()["text"]
|
||||||
respons = respons[0:respons.rfind(".")+1] # Alles weg na de laatste punt
|
respons = respons[0:respons.rfind(".")+1] # Alles weg na de laatste punt
|
||||||
@@ -469,3 +482,49 @@ class Chatbot(commands.Cog):
|
|||||||
await 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.11
|
FROM python:3.13
|
||||||
|
|
||||||
WORKDIR /opt/stroopwafel
|
WORKDIR /opt/stroopwafel
|
||||||
|
|
||||||
|
|||||||
+49
-13
@@ -5,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):
|
||||||
@@ -12,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"),
|
||||||
@@ -22,7 +23,7 @@ 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)
|
||||||
@@ -58,19 +59,25 @@ class General(commands.Cog):
|
|||||||
|
|
||||||
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)
|
||||||
async def kopieerpasta(self, ctx):
|
async 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
|
||||||
@@ -87,14 +94,43 @@ class General(commands.Cog):
|
|||||||
await ctx.channel.send('**'+post.title+'**```'+post.selftext+'```')
|
await ctx.channel.send('**'+post.title+'**```'+post.selftext+'```')
|
||||||
else:
|
else:
|
||||||
await 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)
|
||||||
async def playlist(self, ctx):
|
async def muzak(self, ctx):
|
||||||
"""HDcon2021 playlist"""
|
"""HD muzak 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'])
|
||||||
|
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)
|
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,284 +1,317 @@
|
|||||||
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)
|
|
||||||
async def geefpunten(self, ctx, user, points: int):
|
|
||||||
"""Wees eens lief. Geef iemand wat punten.
|
|
||||||
Bijvoorbeeld:
|
|
||||||
!geefpunten @ikbenjp 42
|
|
||||||
Let op: je moet iemand taggen om punten uit te delen
|
|
||||||
De eerste 10 punten zijn on the house. (Als er genoeg in de bank zit.)
|
|
||||||
"""
|
|
||||||
|
|
||||||
self.reloadPointsCount()
|
|
||||||
|
|
||||||
if points == 0:
|
|
||||||
await ctx.channel.send("0 punten? Gul hoor.")
|
|
||||||
return
|
|
||||||
if points < 0:
|
|
||||||
await self.sendErrorDm(ctx, "Daar hebben we de !neempunten functie voor. Voor meer info typ: ```!help neempunten```")
|
|
||||||
return
|
|
||||||
|
|
||||||
if user[0:2] != "<@":
|
|
||||||
await self.sendErrorDm(ctx, "Je moet iemand taggen om punten te geven. :)")
|
|
||||||
#TODO ook userId oid toestaan?
|
|
||||||
return
|
|
||||||
|
|
||||||
userObj = ctx.message.mentions[0]
|
def __init__(self, bot):
|
||||||
|
self.bot = bot
|
||||||
if userObj.id == ctx.author.id:
|
self.voice_states = {}
|
||||||
await ctx.channel.send("Nee. Je mag niet jezelf punten geven.")
|
|
||||||
time.sleep(0.6)
|
|
||||||
await ctx.channel.send("Gekkie.")
|
|
||||||
return
|
|
||||||
if not self.isUserOnList(userObj):
|
|
||||||
await ctx.channel.send("Nee. Die krijgt geen punten.")
|
|
||||||
return
|
|
||||||
if self.getUserBalance(ctx.author) < points:
|
|
||||||
await ctx.channel.send("Daar heb jij niet genoeg puntjes voor. :bell:")
|
|
||||||
return
|
|
||||||
|
|
||||||
# Execute the transaction:
|
|
||||||
self.execute_geefpunten(ctx.author.id, userObj.id, points)
|
|
||||||
|
|
||||||
self.savePointsCount()
|
|
||||||
|
|
||||||
message = self.getMessageForAwardingPoints(ctx.author.name, userObj.name, points)
|
self.BANK_ID = 42
|
||||||
await 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)
|
|
||||||
async def neempunten(self, ctx, user, points: int):
|
|
||||||
"""Tijd om iemand the shamen. Haal wat punten weg.
|
|
||||||
Bijvoorbeeld:
|
|
||||||
!neempunten @mark 5
|
|
||||||
Punten gaan naar de bank. Je mag niet meer dan 10 punten per dag afnemen.
|
|
||||||
Let op: je moet iemand taggen om punten weg te nemen.
|
|
||||||
"""
|
|
||||||
|
|
||||||
self.reloadPointsCount()
|
|
||||||
|
|
||||||
if points < 1:
|
|
||||||
await ctx.channel.send("Volgens mij snap je het niet.")
|
|
||||||
return
|
|
||||||
if points > 10:
|
|
||||||
await self.sendErrorDm(ctx, "Je mag niet meer dan 10 punten afnemen.")
|
|
||||||
return
|
|
||||||
remainingToTakeAway = self.getUsersRemainingPointsToTakeToday(ctx.author.id)
|
|
||||||
if points > remainingToTakeAway: # The limit per day is 10
|
|
||||||
await self.sendErrorDm(ctx, "Je mag vandaag nog maar " + str(remainingToTakeAway) + " punten wegnemen.")
|
|
||||||
return
|
|
||||||
|
|
||||||
if user[0:2] != "<@":
|
|
||||||
await self.sendErrorDm(ctx, "Je moet iemand taggen. :)")
|
|
||||||
return
|
|
||||||
|
|
||||||
userObj = ctx.message.mentions[0]
|
|
||||||
|
|
||||||
if not self.isUserOnList(userObj):
|
|
||||||
await ctx.channel.send("Nee.")
|
|
||||||
return
|
|
||||||
if self.getUserBalance(userObj) < points:
|
|
||||||
await ctx.channel.send(userObj.name + " mag niet rood staan.")
|
|
||||||
return
|
|
||||||
|
|
||||||
# Execute the transaction:
|
|
||||||
self.execute_neempunten(ctx.author.id, userObj.id, points);
|
|
||||||
|
|
||||||
self.savePointsCount()
|
|
||||||
|
|
||||||
message = self.getMessageForTakingPoints(userObj.name, ctx.author.name, points)
|
self.pointsCount = {}
|
||||||
await 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)
|
|
||||||
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
|
|
||||||
|
|
||||||
|
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)
|
||||||
+30
-23
@@ -16,6 +16,7 @@ class Shitpost(commands.Cog):
|
|||||||
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'
|
||||||
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]
|
||||||
@@ -40,33 +41,36 @@ 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)
|
||||||
async def ishetalhdcon(self, ctx):
|
async def ishetalhdcon(self, ctx):
|
||||||
"""Hoe lang nog tot Hoestende Draken Con 2022?
|
"""Hoe lang nog tot Hoestende Draken Con dit jaar? Of is het pas volgend jaar?
|
||||||
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:
|
||||||
await ctx.channel.send(ctx.author.mention + ' ' + str(Message))
|
await ctx.channel.send(ctx.author.mention + ' ' + str(Message))
|
||||||
return
|
return
|
||||||
|
|
||||||
NachtjesSlapen = Distance.days + 1
|
NachtjesSlapen = Distance.days + 1
|
||||||
if NachtjesSlapen == 1:
|
Message = f"Nog {NachtjesSlapen} nachtje{'s' if NachtjesSlapen > 1 else ''} slapen..."
|
||||||
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;
|
||||||
@@ -94,14 +98,14 @@ class Shitpost(commands.Cog):
|
|||||||
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:
|
||||||
await 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."
|
||||||
|
|
||||||
await ctx.channel.send(ctx.author.mention + ' ' + str(Message))
|
await ctx.channel.send(ctx.author.mention + ' ' + str(Message))
|
||||||
@@ -808,7 +812,10 @@ class Shitpost(commands.Cog):
|
|||||||
|
|
||||||
def get_zaagmans(self):
|
def get_zaagmans(self):
|
||||||
zaagman_url = "http://iszaagmansallangsgeweest.nl/"
|
zaagman_url = "http://iszaagmansallangsgeweest.nl/"
|
||||||
zreq = requests.get(zaagman_url)
|
headers = {
|
||||||
|
'User-Agent': self.userAgent,
|
||||||
|
}
|
||||||
|
zreq = requests.get(zaagman_url, headers=headers)
|
||||||
if zreq:
|
if zreq:
|
||||||
return zreq.text.partition("<h1>")[2].partition("</h1>")[0]
|
return zreq.text.partition("<h1>")[2].partition("</h1>")[0]
|
||||||
else:
|
else:
|
||||||
@@ -823,4 +830,4 @@ class Shitpost(commands.Cog):
|
|||||||
message += gezaagd
|
message += gezaagd
|
||||||
else:
|
else:
|
||||||
message += "De waarheid over zaagmans is niet te doorgronden."
|
message += "De waarheid over zaagmans is niet te doorgronden."
|
||||||
await ctx.channel.send(message)
|
await ctx.channel.send(message)
|
||||||
@@ -29,6 +29,21 @@ intents.members = True
|
|||||||
|
|
||||||
bot = commands.Bot(command_prefix=commands.when_mentioned_or('!'), description='Stroopwafel. Shitpost bot extraordinaire.', pm_help=True, intents=intents)
|
bot = 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)
|
||||||
|
|
||||||
Reference in new issue
Block a user