mirror of
https://github.com/stijndcl/didier.git
synced 2026-04-07 15:48:29 +02:00
Initial commit
Transfer Didier to this repo
This commit is contained in:
commit
f1138c3b56
116 changed files with 353825 additions and 0 deletions
0
functions/__init__.py
Normal file
0
functions/__init__.py
Normal file
72
functions/checks.py
Normal file
72
functions/checks.py
Normal file
|
|
@ -0,0 +1,72 @@
|
|||
import math
|
||||
|
||||
import discord
|
||||
from discord import utils, Member, User
|
||||
from discord.ext import commands
|
||||
from data import constants
|
||||
import requests
|
||||
from functions.database import currency
|
||||
|
||||
|
||||
# Checks if caller of a command is me
|
||||
def isMe(ctx):
|
||||
return str(ctx.author.id) == constants.myId
|
||||
|
||||
|
||||
# Checks if the caller of a command is an admin
|
||||
def isMod(ctx):
|
||||
if ctx.guild is None:
|
||||
return isMe(ctx)
|
||||
|
||||
return ctx.author.id in constants.mods[ctx.guild.id]
|
||||
|
||||
|
||||
# Checks if a command is allowed to be used in this channel
|
||||
def allowedChannels(ctx):
|
||||
return isMe(ctx) or ctx.channel.type == discord.ChannelType.private or int(ctx.channel.id) in constants.allowedChannels.values()
|
||||
|
||||
|
||||
# TODO find a better way to check for legit links because reddit posts return a 502
|
||||
def freeGamesCheck(ctx):
|
||||
if str(ctx.channel.id) != str(constants.allowedChannels["freegames"]):
|
||||
return True
|
||||
|
||||
# Replace newlines with spaces
|
||||
noNewLines = ctx.content.replace("\n", " ")
|
||||
|
||||
link = ""
|
||||
for word in noNewLines.split(" "):
|
||||
if "http" in word and "://" in word:
|
||||
link = word.strip()
|
||||
break
|
||||
|
||||
if link == "":
|
||||
return False
|
||||
request = requests.get(link)
|
||||
if request.status_code != 200:
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
|
||||
# Checks if a user can invest/gamble/... [amount]
|
||||
def isValidAmount(ctx, amount):
|
||||
if not amount:
|
||||
return [False, "Geef een geldig bedrag op."]
|
||||
dinks = float(currency.dinks(ctx.author.id))
|
||||
if amount == "all":
|
||||
if dinks > 0:
|
||||
return [True, dinks]
|
||||
else:
|
||||
return [False, "Je hebt niet genoeg Didier Dinks om dit te doen."]
|
||||
# Check if it's a number <= 0 or text != all
|
||||
if (all(char.isalpha() for char in str(amount)) and amount != "all") or \
|
||||
(all(char.isdigit() for char in str(abs(int(amount)))) and int(amount) <= 0):
|
||||
return [False, "Geef een geldig bedrag op."]
|
||||
if int(amount) > dinks:
|
||||
return [False, "Je hebt niet genoeg Didier Dinks om dit te doen."]
|
||||
return [True, amount]
|
||||
|
||||
|
||||
def pluralS(amount):
|
||||
return "s" if round(float(amount)) != 1 else ""
|
||||
62
functions/clap.py
Normal file
62
functions/clap.py
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
def clap(content: str):
|
||||
if content == "":
|
||||
return "Dit is geen geldig bericht"
|
||||
text = "".join([str(s).lower() if s.isdigit() or s.isalpha() else "" for s in content])
|
||||
newStr = ":clap: " + " :clap: ".join(fetch("regional_indicator_{}".format(char) if char.isalpha() else char) for char in text) + " :clap:"
|
||||
return newStr if 0 < len(newStr) <= 1100 else "Dit is geen geldig bericht."
|
||||
|
||||
|
||||
def fetch(char):
|
||||
dic = {
|
||||
"regional_indicator_a": "🇦",
|
||||
"regional_indicator_b": "🇧",
|
||||
"regional_indicator_c": "🇨",
|
||||
"regional_indicator_d": "🇩",
|
||||
"regional_indicator_e": "🇪",
|
||||
"regional_indicator_f": "🇫",
|
||||
"regional_indicator_g": "🇬",
|
||||
"regional_indicator_h": "🇭",
|
||||
"regional_indicator_i": "🇮",
|
||||
"regional_indicator_j": "🇯",
|
||||
"regional_indicator_k": "🇰",
|
||||
"regional_indicator_l": "🇱",
|
||||
"regional_indicator_m": "🇲",
|
||||
"regional_indicator_n": "🇳",
|
||||
"regional_indicator_o": "🇴",
|
||||
"regional_indicator_p": "🇵",
|
||||
"regional_indicator_q": "🇶",
|
||||
"regional_indicator_r": "🇷",
|
||||
"regional_indicator_s": "🇸",
|
||||
"regional_indicator_t": "🇹",
|
||||
"regional_indicator_u": "🇺",
|
||||
"regional_indicator_v": "🇻",
|
||||
"regional_indicator_w": "🇼",
|
||||
"regional_indicator_x": "🇽",
|
||||
"regional_indicator_y": "🇾",
|
||||
"regional_indicator_z": "🇿",
|
||||
"zero": "0⃣",
|
||||
"one": "1️⃣",
|
||||
"two": "2️⃣",
|
||||
"three": "3️⃣",
|
||||
"four": "4️⃣",
|
||||
"five": "5️⃣",
|
||||
"six": "6️⃣",
|
||||
"seven": "7️⃣",
|
||||
"eight": "8️⃣",
|
||||
"nine": "9️⃣"
|
||||
}
|
||||
|
||||
nums = {
|
||||
"0": "zero",
|
||||
"1": "one",
|
||||
"2": "two",
|
||||
"3": "three",
|
||||
"4": "four",
|
||||
"5": "five",
|
||||
"6": "six",
|
||||
"7": "seven",
|
||||
"8": "eight",
|
||||
"9": "nine"
|
||||
}
|
||||
|
||||
return dic[str(char)] if char[-1].isalpha() else dic[nums[str(char)]]
|
||||
67
functions/colours.py
Normal file
67
functions/colours.py
Normal file
|
|
@ -0,0 +1,67 @@
|
|||
import random
|
||||
|
||||
|
||||
def randomRGB():
|
||||
return random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)
|
||||
|
||||
|
||||
def RGBToHEX(r, g, b):
|
||||
return "#" + str(hex(r))[2:] + str(hex(g))[2:] + str(hex(b))[2:]
|
||||
|
||||
|
||||
def RGBToHSL(r, g, b):
|
||||
r /= 255
|
||||
g /= 255
|
||||
b /= 255
|
||||
Cmax = max(r, g, b)
|
||||
Cmin = min(r, g, b)
|
||||
delta = Cmax - Cmin
|
||||
|
||||
# Hue
|
||||
h = RGBHue(r, g, b)
|
||||
|
||||
# Lightness
|
||||
l = (Cmax + Cmin)/2
|
||||
|
||||
# Saturation
|
||||
s = 0 if delta == 0 else delta / (1 - abs(((2 * l) - 1)))
|
||||
|
||||
return round(h), round(s * 100, 2), round(l * 100, 2)
|
||||
|
||||
|
||||
def RGBToHSV(r, g, b):
|
||||
r /= 255
|
||||
g /= 255
|
||||
b /= 255
|
||||
Cmax = max(r, g, b)
|
||||
Cmin = min(r, g, b)
|
||||
delta = Cmax - Cmin
|
||||
|
||||
# Hue
|
||||
h = RGBHue(r, g, b)
|
||||
|
||||
# Saturation
|
||||
s = 0 if Cmax == 0 else delta / Cmax
|
||||
|
||||
# Value
|
||||
v = Cmax
|
||||
|
||||
return round(h), round(s * 100, 2), round(v * 100, 2)
|
||||
|
||||
|
||||
def RGBHue(r, g, b):
|
||||
Cmax = max(r, g, b)
|
||||
Cmin = min(r, g, b)
|
||||
delta = Cmax - Cmin
|
||||
|
||||
h = -1
|
||||
if delta == 0:
|
||||
h = 0
|
||||
elif Cmax == r:
|
||||
h = 60 * (((g - b) / delta) % 6)
|
||||
elif Cmax == g:
|
||||
h = 60 * (((b - r) / delta) + 2)
|
||||
elif Cmax == b:
|
||||
h = 60 * (((r - g) / delta) + 4)
|
||||
|
||||
return h
|
||||
23
functions/config.py
Normal file
23
functions/config.py
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
import json
|
||||
|
||||
|
||||
def config(category: str, value):
|
||||
try:
|
||||
with open("files/config.json", "r") as fp:
|
||||
configFile = json.load(fp)
|
||||
|
||||
configFile[category] = value
|
||||
|
||||
with open("files/config.json", "w") as fp:
|
||||
json.dump(configFile, fp)
|
||||
|
||||
return True
|
||||
except Exception:
|
||||
raise Exception
|
||||
|
||||
|
||||
def get(category):
|
||||
with open("files/config.json", "r") as fp:
|
||||
configFile = json.load(fp)
|
||||
|
||||
return configFile[category] if category in configFile else None
|
||||
0
functions/database/__init__.py
Normal file
0
functions/database/__init__.py
Normal file
27
functions/database/birthdays.py
Normal file
27
functions/database/birthdays.py
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
from functions.database import utils
|
||||
|
||||
|
||||
def get_user(userid):
|
||||
connection = utils.connect()
|
||||
cursor = connection.cursor()
|
||||
cursor.execute("SELECT day, month, year FROM birthdays WHERE userid = %s", (int(userid),))
|
||||
return cursor.fetchall()
|
||||
|
||||
|
||||
def get_users_on_date(day, month):
|
||||
connection = utils.connect()
|
||||
cursor = connection.cursor()
|
||||
cursor.execute("SELECT userid FROM birthdays WHERE day = %s AND month = %s", (int(day), int(month),))
|
||||
return cursor.fetchall()
|
||||
|
||||
|
||||
def add_user(userid, day, month, year):
|
||||
connection = utils.connect()
|
||||
cursor = connection.cursor()
|
||||
if get_user(userid):
|
||||
cursor.execute("UPDATE birthdays SET day = %s, month = %s, year = %s WHERE userid = %s",
|
||||
(int(day), int(month), int(year), int(userid),))
|
||||
else:
|
||||
cursor.execute("INSERT INTO birthdays(userid, day, month, year) VALUES (%s, %s, %s, %s)",
|
||||
(int(userid), int(day), int(month), int(year),))
|
||||
connection.commit()
|
||||
107
functions/database/currency.py
Normal file
107
functions/database/currency.py
Normal file
|
|
@ -0,0 +1,107 @@
|
|||
import datetime
|
||||
from functions.database import utils, stats
|
||||
import time
|
||||
|
||||
|
||||
def dinks(userid):
|
||||
return getOrAddUser(userid)[1]
|
||||
|
||||
|
||||
def dinksAll(userid):
|
||||
platinumDinks = 0
|
||||
|
||||
connection = utils.connect()
|
||||
cursor = connection.cursor()
|
||||
cursor.execute("SELECT amount FROM inventory WHERE userid = %s AND itemid = %s", (int(userid), 1,))
|
||||
result = cursor.fetchall()
|
||||
|
||||
if result:
|
||||
platinumDinks = result[0][0]
|
||||
|
||||
return {"dinks": dinks(userid), "platinum": platinumDinks}
|
||||
|
||||
|
||||
def getAllRows():
|
||||
connection = utils.connect()
|
||||
cursor = connection.cursor()
|
||||
cursor.execute(
|
||||
"""SELECT * FROM currencytable"""
|
||||
)
|
||||
|
||||
return cursor.fetchall()
|
||||
|
||||
|
||||
def getAllPlatDinks():
|
||||
connection = utils.connect()
|
||||
cursor = connection.cursor()
|
||||
cursor.execute("SELECT userid, amount FROM inventory WHERE itemid = 1")
|
||||
result = cursor.fetchall()
|
||||
dic = {}
|
||||
for user in result:
|
||||
dic[str(user[0])] = user[1]
|
||||
return dic
|
||||
|
||||
|
||||
def getOrAddUser(userid):
|
||||
connection = utils.connect()
|
||||
cursor = connection.cursor()
|
||||
query = "SELECT * FROM currencytable WHERE userid = %s"
|
||||
cursor.execute(
|
||||
query, (int(userid),)
|
||||
)
|
||||
result = cursor.fetchall()
|
||||
# User didn't exist yet, so create a new default file
|
||||
if len(result) == 0:
|
||||
createNewUser(userid, connection)
|
||||
return getOrAddUser(userid)
|
||||
return result[0]
|
||||
|
||||
|
||||
# TODO check for nightly bonus & add+return that instead of 420
|
||||
def nightly(userid):
|
||||
user = getOrAddUser(userid)
|
||||
today = datetime.datetime.today().date()
|
||||
lastNightly = datetime.datetime.fromtimestamp(user[9]).date()
|
||||
streak = int(user[10])
|
||||
if lastNightly < today:
|
||||
update(userid, "dinks", float(user[1]) + 420.0)
|
||||
update(userid, "nightly", int(time.time()))
|
||||
|
||||
# Update the streak
|
||||
if (today - lastNightly).days > 1:
|
||||
update(userid, "nightly_streak", 1)
|
||||
streak = 1
|
||||
else:
|
||||
update(userid, "nightly_streak", streak + 1)
|
||||
streak += 1
|
||||
|
||||
s = stats.getOrAddUser(userid)
|
||||
|
||||
if streak > int(s[5]):
|
||||
stats.update(userid, "longest_streak", streak)
|
||||
|
||||
stats.update(userid, "nightlies_count", int(s[6]) + 1)
|
||||
|
||||
return [True, 420, streak]
|
||||
return [False, 0, -1]
|
||||
|
||||
|
||||
def createNewUser(userid, connection=None):
|
||||
if connection is None:
|
||||
connection = utils.connect()
|
||||
cursor = connection.cursor()
|
||||
query = "INSERT INTO currencytable(userid, dinks, banklevel, investedamount, investeddays, profit, defense, offense, bitcoins, nightly) " \
|
||||
"VALUES (%s, 0.0, 1, 0.0, 0, 0, 1, 1, 0.0, 0)"
|
||||
cursor.execute(query, (int(userid),))
|
||||
connection.commit()
|
||||
|
||||
|
||||
def update(userid, column, value):
|
||||
_ = getOrAddUser(userid)
|
||||
connection = utils.connect()
|
||||
cursor = connection.cursor()
|
||||
query = "UPDATE currencytable " \
|
||||
"SET {} = %s " \
|
||||
"WHERE userid = %s".format(column)
|
||||
cursor.execute(query, (value, userid,))
|
||||
connection.commit()
|
||||
16
functions/database/dadjoke.py
Normal file
16
functions/database/dadjoke.py
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
from functions.database import utils
|
||||
import random
|
||||
|
||||
|
||||
def getRandomJoke():
|
||||
connection = utils.connect()
|
||||
cursor = connection.cursor()
|
||||
cursor.execute("SELECT * FROM dad_jokes")
|
||||
return random.choice(cursor.fetchall())[1]
|
||||
|
||||
|
||||
def addJoke(joke):
|
||||
connection = utils.connect()
|
||||
cursor = connection.cursor()
|
||||
cursor.execute("INSERT INTO dad_jokes(joke) VALUES (%s)", (str(joke),))
|
||||
connection.commit()
|
||||
60
functions/database/faq.py
Normal file
60
functions/database/faq.py
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
from functions.database import utils
|
||||
|
||||
|
||||
def getCategories():
|
||||
connection = utils.connect()
|
||||
cursor = connection.cursor()
|
||||
cursor.execute(
|
||||
"""SELECT name FROM faq_categories"""
|
||||
)
|
||||
return cursor.fetchall()
|
||||
|
||||
|
||||
def addCategory(name):
|
||||
connection = utils.connect()
|
||||
cursor = connection.cursor()
|
||||
cursor.execute(
|
||||
"""INSERT INTO faq_categories(name) VALUES (%s)""", (name.lower(),)
|
||||
)
|
||||
connection.commit()
|
||||
|
||||
|
||||
def addQuestion(category: str, question: str, answer: str, answer_markdown: str = None):
|
||||
connection = utils.connect()
|
||||
cursor = connection.cursor()
|
||||
|
||||
# Find the Id of this category
|
||||
cursor.execute(
|
||||
"""SELECT id FROM faq_categories WHERE name = %s""", (category.lower(),)
|
||||
)
|
||||
categoryId = cursor.fetchall()[0]
|
||||
|
||||
if not categoryId:
|
||||
return
|
||||
|
||||
categoryId = categoryId[0]
|
||||
|
||||
# Check if a markdown string has to be added
|
||||
if answer_markdown is None:
|
||||
cursor.execute(
|
||||
"""INSERT INTO faq_entries(category_id, question, answer) VALUES (%s, %s, E%s)""",
|
||||
(categoryId, question, answer,)
|
||||
)
|
||||
else:
|
||||
cursor.execute(
|
||||
"""INSERT INTO faq_entries(category_id, question, answer, answer_markdown) VALUES (%s, %s, E%s, E%s)""", (categoryId, question, answer, answer_markdown)
|
||||
)
|
||||
|
||||
connection.commit()
|
||||
|
||||
|
||||
def getCategory(category):
|
||||
connection = utils.connect()
|
||||
cursor = connection.cursor()
|
||||
cursor.execute(
|
||||
"""SELECT *
|
||||
FROM faq_entries INNER JOIN faq_categories fc on faq_entries.category_id = fc.id
|
||||
WHERE %s = fc.name""",
|
||||
(category.lower(),)
|
||||
)
|
||||
return cursor.fetchall()
|
||||
27
functions/database/githubs.py
Normal file
27
functions/database/githubs.py
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
from functions.database import utils
|
||||
|
||||
|
||||
def add(userid, link):
|
||||
user = get_user(userid)
|
||||
connection = utils.connect()
|
||||
cursor = connection.cursor()
|
||||
if len(user) == 0:
|
||||
cursor.execute("INSERT INTO githubs(userid, githublink) VALUES (%s, %s)", (int(userid), str(link),))
|
||||
else:
|
||||
cursor.execute("""UPDATE githubs SET githublink = %s WHERE userid = %s""", (user[0][0] + "\n" + link, int(userid),))
|
||||
connection.commit()
|
||||
|
||||
|
||||
def getAll():
|
||||
connection = utils.connect()
|
||||
cursor = connection.cursor()
|
||||
cursor.execute("SELECT * FROM githubs")
|
||||
result = cursor.fetchall()
|
||||
return result
|
||||
|
||||
|
||||
def get_user(userid):
|
||||
connection = utils.connect()
|
||||
cursor = connection.cursor()
|
||||
cursor.execute("SELECT githublink FROM githubs WHERE userid = %s", (int(userid),))
|
||||
return cursor.fetchall()
|
||||
29
functions/database/memes.py
Normal file
29
functions/database/memes.py
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
from functions.database import utils
|
||||
|
||||
|
||||
def insert(id, name, fields):
|
||||
if getMeme(name)[0]:
|
||||
return [False, "Deze meme staat al in de database."]
|
||||
connection = utils.connect()
|
||||
cursor = connection.cursor()
|
||||
cursor.execute("INSERT INTO memes(id, name, fields) VALUES (%s, %s, %s)", [int(id), name.lower(), int(fields)])
|
||||
connection.commit()
|
||||
return [True, "{} is toegevoegd aan de database.".format(name[0].upper() + name[1:].lower())]
|
||||
|
||||
|
||||
def getMeme(name):
|
||||
connection = utils.connect()
|
||||
cursor = connection.cursor()
|
||||
cursor.execute("SELECT * FROM memes WHERE name like %s", ["%" + name.lower() + "%"])
|
||||
result = cursor.fetchall()
|
||||
if len(result) == 0:
|
||||
return [False, "Deze meme staat niet in de database."]
|
||||
return [True, result[0]]
|
||||
|
||||
|
||||
def getAllMemes():
|
||||
connection = utils.connect()
|
||||
cursor = connection.cursor()
|
||||
cursor.execute("SELECT * FROM memes")
|
||||
result = cursor.fetchall()
|
||||
return result
|
||||
76
functions/database/muttn.py
Normal file
76
functions/database/muttn.py
Normal file
|
|
@ -0,0 +1,76 @@
|
|||
from data import constants
|
||||
from functions.database import utils
|
||||
import random
|
||||
|
||||
|
||||
def getOrAddUser(userid):
|
||||
connection = utils.connect()
|
||||
cursor = connection.cursor()
|
||||
query = "SELECT * FROM muttn WHERE userid = %s"
|
||||
cursor.execute(
|
||||
query, (int(userid),)
|
||||
)
|
||||
result = cursor.fetchall()
|
||||
# User didn't exist yet, so create a new default file
|
||||
if len(result) == 0:
|
||||
createNewUser(userid, connection)
|
||||
return getOrAddUser(userid)
|
||||
return result[0]
|
||||
|
||||
|
||||
def getAllRows():
|
||||
connection = utils.connect()
|
||||
cursor = connection.cursor()
|
||||
cursor.execute("SELECT * FROM muttn")
|
||||
return cursor.fetchall()
|
||||
|
||||
|
||||
def createNewUser(userid, connection):
|
||||
cursor = connection.cursor()
|
||||
cursor.execute("INSERT INTO muttn(userid, stats, count, message) VALUES (%s, %s, %s, %s)", (
|
||||
int(userid), random.randint(0, 50) + (random.randint(0, 100)/100), 0, 0,
|
||||
))
|
||||
connection.commit()
|
||||
|
||||
|
||||
def muttn(userid, count, messageid):
|
||||
if str(userid) == constants.didierId:
|
||||
return
|
||||
|
||||
connection = utils.connect()
|
||||
cursor = connection.cursor()
|
||||
|
||||
user = getOrAddUser(userid)
|
||||
|
||||
# Dont' allow earlier messages to be spammed to avoid abuse
|
||||
if messageid < user[3]:
|
||||
return
|
||||
|
||||
# 5 or more = percentage increase
|
||||
if count >= 5:
|
||||
# React was removed & added again: don't do anything
|
||||
# New count is smaller than or equal to old max for this message
|
||||
if count <= user[4] and messageid == user[3]:
|
||||
return
|
||||
|
||||
cursor.execute("UPDATE muttn SET stats = %s, message = %s, highest = %s WHERE userid = %s",
|
||||
(float(user[1]) + (random.randint(2, 50) * count/1000), int(messageid), count, int(userid)))
|
||||
connection.commit()
|
||||
cursor.execute("UPDATE muttn SET count = %s WHERE userid = %s",
|
||||
(int(user[2]) + 1, int(userid),))
|
||||
connection.commit()
|
||||
|
||||
|
||||
def removeMuttn(message):
|
||||
if str(message.author.id) == constants.didierId:
|
||||
return
|
||||
|
||||
connection = utils.connect()
|
||||
cursor = connection.cursor()
|
||||
|
||||
user = getOrAddUser(message.author.id)
|
||||
|
||||
cursor.execute("UPDATE muttn SET count = %s WHERE userid = %s",
|
||||
(int(user[2]) - 1, int(message.author.id),))
|
||||
connection.commit()
|
||||
|
||||
58
functions/database/poke.py
Normal file
58
functions/database/poke.py
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
from functions.database import utils, stats
|
||||
import time
|
||||
|
||||
|
||||
def get():
|
||||
connection = utils.connect()
|
||||
cursor = connection.cursor()
|
||||
cursor.execute("SELECT * FROM poke")
|
||||
return cursor.fetchall()[0]
|
||||
|
||||
|
||||
def update(user, new):
|
||||
connection = utils.connect()
|
||||
cursor = connection.cursor()
|
||||
cursor.execute(
|
||||
"UPDATE poke "
|
||||
"SET current = %s, poketime = %s, previous = %s",
|
||||
(int(new), int(time.time()), int(user))
|
||||
)
|
||||
connection.commit()
|
||||
|
||||
|
||||
def blacklisted(user):
|
||||
connection = utils.connect()
|
||||
cursor = connection.cursor()
|
||||
cursor.execute("SELECT poke_blacklist FROM info WHERE userid = %s", (int(user),))
|
||||
res = cursor.fetchall()
|
||||
if len(res) == 0:
|
||||
connection = utils.connect()
|
||||
cursor = connection.cursor()
|
||||
cursor.execute("INSERT INTO info(userid, poke_blacklist) VALUES(%s, False)", (int(user),))
|
||||
connection.commit()
|
||||
return False
|
||||
return res[0][0]
|
||||
|
||||
|
||||
# Changes the poke blacklist state to true or false
|
||||
def blacklist(user, bl=True):
|
||||
connection = utils.connect()
|
||||
cursor = connection.cursor()
|
||||
cursor.execute("UPDATE info "
|
||||
"SET poke_blacklist = %s WHERE userid = %s", (bl, int(user),))
|
||||
connection.commit()
|
||||
|
||||
|
||||
# Returns a list of all blacklisted users
|
||||
def getAllBlacklistedUsers():
|
||||
connection = utils.connect()
|
||||
cursor = connection.cursor()
|
||||
cursor.execute("SELECT userid FROM info WHERE poke_blacklist = True")
|
||||
return [str(user[0]) for user in cursor.fetchall()]
|
||||
|
||||
|
||||
def reset():
|
||||
current = get()[0]
|
||||
new = stats.pokeResetCandidate(current, [int(user) for user in getAllBlacklistedUsers()])
|
||||
update(current, new)
|
||||
return new
|
||||
44
functions/database/prison.py
Normal file
44
functions/database/prison.py
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
from functions.database import utils
|
||||
|
||||
|
||||
def getUser(userId):
|
||||
connection = utils.connect()
|
||||
cursor = connection.cursor()
|
||||
cursor.execute("SELECT * FROM prison WHERE userid = %s", (int(userId),))
|
||||
return cursor.fetchall()
|
||||
|
||||
|
||||
def remove(userId):
|
||||
connection = utils.connect()
|
||||
cursor = connection.cursor()
|
||||
cursor.execute("DELETE FROM prison WHERE userid = %s", (int(userId),))
|
||||
connection.commit()
|
||||
|
||||
|
||||
def imprison(userid, bailsum, days, daily):
|
||||
connection = utils.connect()
|
||||
cursor = connection.cursor()
|
||||
cursor.execute("INSERT INTO prison(userid, bail, days, daily) VALUES (%s, %s, %s, %s)",
|
||||
(int(userid), float(bailsum), int(days), float(daily),))
|
||||
connection.commit()
|
||||
|
||||
|
||||
def dailyLowers():
|
||||
connection = utils.connect()
|
||||
cursor = connection.cursor()
|
||||
|
||||
# Release people from prison on their last day
|
||||
cursor.execute("DELETE FROM prison WHERE days = 1")
|
||||
connection.commit()
|
||||
|
||||
# Get all remaining users
|
||||
cursor.execute("SELECT * FROM prison")
|
||||
prisoners = cursor.fetchall()
|
||||
|
||||
for prisoner in prisoners:
|
||||
cursor.execute("UPDATE prison "
|
||||
"SET bail = %s, days = %s "
|
||||
"WHERE userid = %s",
|
||||
(float(prisoner[1]) - float(prisoner[3]), int(prisoner[2]) - 1,
|
||||
int(prisoner[0]),))
|
||||
connection.commit()
|
||||
154
functions/database/stats.py
Normal file
154
functions/database/stats.py
Normal file
|
|
@ -0,0 +1,154 @@
|
|||
from functions import xp
|
||||
from functions.database import utils
|
||||
import json
|
||||
import random
|
||||
import time
|
||||
|
||||
|
||||
def getOrAddUser(userid):
|
||||
connection = utils.connect()
|
||||
cursor = connection.cursor()
|
||||
query = "SELECT * FROM personalstats WHERE userid = %s"
|
||||
cursor.execute(
|
||||
query, (int(userid),)
|
||||
)
|
||||
result = cursor.fetchall()
|
||||
# User didn't exist yet, so create a new default file
|
||||
if len(result) == 0:
|
||||
createNewUser(userid, connection)
|
||||
return getOrAddUser(userid)
|
||||
return result[0]
|
||||
|
||||
|
||||
def createNewUser(userid, connection=None):
|
||||
if connection is None:
|
||||
connection = utils.connect()
|
||||
cursor = connection.cursor()
|
||||
query = "INSERT INTO personalstats(userid, poked, robs_success, robs_failed, robs_total, longest_streak) " \
|
||||
"VALUES (%s, 0, 0, 0, 0, 0)"
|
||||
cursor.execute(query, (int(userid),))
|
||||
connection.commit()
|
||||
|
||||
|
||||
def getAllRows():
|
||||
connection = utils.connect()
|
||||
cursor = connection.cursor()
|
||||
cursor.execute(
|
||||
"""SELECT * FROM personalstats"""
|
||||
)
|
||||
|
||||
return cursor.fetchall()
|
||||
|
||||
|
||||
def update(userid, column, value):
|
||||
_ = getOrAddUser(userid)
|
||||
connection = utils.connect()
|
||||
cursor = connection.cursor()
|
||||
query = "UPDATE personalstats " \
|
||||
"SET {} = %s " \
|
||||
"WHERE userid = %s".format(column)
|
||||
cursor.execute(query, (value, userid,))
|
||||
connection.commit()
|
||||
statsTracker(column)
|
||||
|
||||
|
||||
# Automatically change global stats
|
||||
def statsTracker(column):
|
||||
if column in stats()["rob"]:
|
||||
with open("files/stats.json", "r") as fp:
|
||||
s = json.load(fp)
|
||||
|
||||
s["rob"][column] += 1
|
||||
|
||||
with open("files/stats.json", "w") as fp:
|
||||
json.dump(s, fp)
|
||||
|
||||
|
||||
def stats():
|
||||
return {"rob": ["robs_failed", "robs_success"]}
|
||||
|
||||
|
||||
# Gets a random person that has been poked before & has not blacklisted themself
|
||||
def pokeResetCandidate(current, blacklisted):
|
||||
connection = utils.connect()
|
||||
cursor = connection.cursor()
|
||||
cursor.execute("SELECT * FROM personalstats WHERE poked != 0 and userid != %s and userid not in %s",
|
||||
(int(current), tuple(blacklisted)))
|
||||
return random.choice(cursor.fetchall())[0]
|
||||
|
||||
|
||||
def sentMessage(message):
|
||||
user = message.author
|
||||
|
||||
# Ignore bots
|
||||
if user.bot:
|
||||
return
|
||||
|
||||
# Ignore dm's
|
||||
if message.guild is None:
|
||||
return
|
||||
|
||||
# Don't give xp for bot commands
|
||||
if message.content.lower().startswith(("didier", "owo", "?", "rps", "p!", "-")):
|
||||
return
|
||||
|
||||
user_db = getOrAddUser(user.id)
|
||||
|
||||
update(user.id, "messages", user_db[11] + 1)
|
||||
update_channel(message.channel.id)
|
||||
|
||||
# Only gain xp every minute
|
||||
if round(time.time()) - user_db[13] > 30:
|
||||
gainXp(user.id, user_db)
|
||||
|
||||
|
||||
def gainXp(user, user_db):
|
||||
update(user, "xp", user_db[12] + random.randint(5, 15) + (xp.calculate_level(user_db[12]) * 3))
|
||||
update(user, "last_message", round(time.time()))
|
||||
|
||||
|
||||
def getOrAddChannel(channelid: int):
|
||||
connection = utils.connect()
|
||||
cursor = connection.cursor()
|
||||
|
||||
cursor.execute("SELECT * FROM channel_activity WHERE channel_id = %s", (channelid,))
|
||||
|
||||
res = cursor.fetchall()
|
||||
|
||||
if not res:
|
||||
cursor.execute("INSERT INTO channel_activity(channel_id, message_count) VALUES (%s, 0)", (channelid,))
|
||||
connection.commit()
|
||||
|
||||
return getOrAddChannel(channelid)
|
||||
|
||||
return res
|
||||
|
||||
|
||||
def channel_activity(channel=None):
|
||||
connection = utils.connect()
|
||||
cursor = connection.cursor()
|
||||
|
||||
# All channels
|
||||
if channel is None:
|
||||
cursor.execute("SELECT * FROM channel_activity")
|
||||
return cursor.fetchall()
|
||||
return getOrAddChannel(channel.id)
|
||||
|
||||
|
||||
def update_channel(channelid: int):
|
||||
connection = utils.connect()
|
||||
cursor = connection.cursor()
|
||||
|
||||
channel = getOrAddChannel(channelid)[0]
|
||||
cursor.execute("UPDATE channel_activity SET message_count = %s WHERE channel_id = %s",
|
||||
(float(channel[1]) + 1, channelid))
|
||||
connection.commit()
|
||||
|
||||
|
||||
def lower_channel(channelid: int, message_count):
|
||||
connection = utils.connect()
|
||||
cursor = connection.cursor()
|
||||
|
||||
cursor.execute("UPDATE channel_activity SET message_count = %s WHERE channel_id = %s",
|
||||
(float(message_count), channelid,))
|
||||
connection.commit()
|
||||
87
functions/database/store.py
Normal file
87
functions/database/store.py
Normal file
|
|
@ -0,0 +1,87 @@
|
|||
from functions import checks
|
||||
from functions.database import utils, currency
|
||||
|
||||
|
||||
def buy(ctx, userid, itemid, amount):
|
||||
connection = utils.connect()
|
||||
cursor = connection.cursor()
|
||||
dinks = currency.dinks(userid)
|
||||
cursor.execute("SELECT * FROM store WHERE itemid = %s", (int(itemid),))
|
||||
result = cursor.fetchall()
|
||||
if not result:
|
||||
return False, "Er is geen item met dit id."
|
||||
|
||||
# Not an empty list, no IndexError.
|
||||
result = result[0]
|
||||
|
||||
cursor.execute("SELECT amount FROM inventory WHERE userid = %s AND itemid = %s", (int(userid), int(itemid),))
|
||||
inv = cursor.fetchall()
|
||||
# Check if user already owns this
|
||||
limit = result[3]
|
||||
if limit is not None \
|
||||
and inv \
|
||||
and inv[0][0] + amount > limit:
|
||||
return False, "Je kan dit item maar {} keer kopen.".format(limit)
|
||||
|
||||
isValid = checks.isValidAmount(ctx, result[2] * amount)
|
||||
|
||||
if not isValid[0]:
|
||||
return isValid
|
||||
|
||||
currency.update(userid, "dinks", dinks - (result[2] * amount))
|
||||
addItem(userid, itemid, amount, inv)
|
||||
return True, {"id": result[0], "name": result[1], "price": result[2] * amount}
|
||||
|
||||
|
||||
def addItem(userid, itemid, amount, inv):
|
||||
connection = utils.connect()
|
||||
cursor = connection.cursor()
|
||||
|
||||
# It's already in there, add more to the counter
|
||||
if inv:
|
||||
amount += inv[0][0]
|
||||
cursor.execute("UPDATE inventory SET amount = %s WHERE userid = %s AND itemid = %s", (amount, userid, itemid))
|
||||
connection.commit()
|
||||
return
|
||||
|
||||
# Doesn't own this item yet, add a new row
|
||||
cursor.execute("INSERT INTO inventory(userid, itemid, amount) VALUES (%s, %s, %s)", (userid, itemid, amount))
|
||||
connection.commit()
|
||||
|
||||
|
||||
def getAllItems():
|
||||
connection = utils.connect()
|
||||
cursor = connection.cursor()
|
||||
|
||||
cursor.execute("SELECT * FROM store")
|
||||
return cursor.fetchall()
|
||||
|
||||
|
||||
def getItemPrice(itemid):
|
||||
connection = utils.connect()
|
||||
cursor = connection.cursor()
|
||||
|
||||
cursor.execute("SELECT price FROM store WHERE itemid = %s", (itemid,))
|
||||
return cursor.fetchone()
|
||||
|
||||
|
||||
def inventory(userid):
|
||||
connection = utils.connect()
|
||||
cursor = connection.cursor()
|
||||
|
||||
cursor.execute("SELECT inventory.itemid, name, amount FROM inventory INNER JOIN store on inventory.itemid = store.itemid WHERE userid = %s", (int(userid),))
|
||||
return cursor.fetchall()
|
||||
|
||||
|
||||
# Amount = amount of item before sell
|
||||
def sell(userid, itemid, sold, amount):
|
||||
connection = utils.connect()
|
||||
cursor = connection.cursor()
|
||||
|
||||
# Don't store amount: 0
|
||||
if sold == amount:
|
||||
cursor.execute("DELETE FROM inventory WHERE userid = %s AND itemid = %s", (userid, itemid,))
|
||||
return connection.commit()
|
||||
|
||||
cursor.execute("UPDATE inventory SET amount = %s WHERE userid = %s AND itemid = %s", (amount - sold, userid, itemid))
|
||||
return connection.commit()
|
||||
17
functions/database/trump.py
Normal file
17
functions/database/trump.py
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
from functions.database import utils
|
||||
import random
|
||||
|
||||
|
||||
def add(quote, date, location):
|
||||
connection = utils.connect()
|
||||
cursor = connection.cursor()
|
||||
cursor.execute("INSERT INTO trump(quote, date, location) VALUES (%s, %s, %s)", (str(quote), str(date), str(location),))
|
||||
connection.commit()
|
||||
|
||||
|
||||
def getRandomQuote():
|
||||
connection = utils.connect()
|
||||
cursor = connection.cursor()
|
||||
cursor.execute("SELECT * FROM trump")
|
||||
result = cursor.fetchall()
|
||||
return random.choice(result)
|
||||
28
functions/database/twitch.py
Normal file
28
functions/database/twitch.py
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
from functions.database import utils
|
||||
|
||||
|
||||
def add(userid, link):
|
||||
user = get_user(userid)
|
||||
connection = utils.connect()
|
||||
cursor = connection.cursor()
|
||||
if len(user) == 0:
|
||||
cursor.execute("INSERT INTO twitch(userid, link) VALUES (%s, %s)", (int(userid), str(link),))
|
||||
else:
|
||||
cursor.execute("""UPDATE twitch SET link = %s WHERE userid = %s""", (link, int(userid),))
|
||||
connection.commit()
|
||||
|
||||
|
||||
def getAll():
|
||||
connection = utils.connect()
|
||||
cursor = connection.cursor()
|
||||
cursor.execute("SELECT * FROM twitch")
|
||||
result = cursor.fetchall()
|
||||
return result
|
||||
|
||||
|
||||
def get_user(userid):
|
||||
connection = utils.connect()
|
||||
cursor = connection.cursor()
|
||||
cursor.execute("SELECT link FROM twitch WHERE userid = %s", (int(userid),))
|
||||
return cursor.fetchall()
|
||||
|
||||
36
functions/database/utils.py
Normal file
36
functions/database/utils.py
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
import psycopg2
|
||||
import json
|
||||
import os
|
||||
|
||||
|
||||
connection = None
|
||||
|
||||
|
||||
def connect():
|
||||
global connection
|
||||
|
||||
if connection is None:
|
||||
create_connection()
|
||||
return connection
|
||||
|
||||
|
||||
def create_connection():
|
||||
global connection
|
||||
|
||||
dir_path = os.path.dirname(os.path.realpath(__file__))
|
||||
with open(os.path.join(dir_path, "../../files/database.json"), "r") as fp:
|
||||
db = json.load(fp)
|
||||
|
||||
connection = psycopg2.connect(
|
||||
host=db["host"],
|
||||
database=db["database"],
|
||||
user=db["username"],
|
||||
password=db["password"]
|
||||
)
|
||||
|
||||
|
||||
def reconnect():
|
||||
global connection
|
||||
|
||||
connection.close()
|
||||
create_connection()
|
||||
37
functions/dinks.py
Normal file
37
functions/dinks.py
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
import json
|
||||
|
||||
|
||||
def getRatios():
|
||||
return {
|
||||
":apple:": [1, 2, 3],
|
||||
":peach:": [2, 4, 6],
|
||||
":banana:": [0, 20, 40],
|
||||
":croissant:": [0, 0, 25],
|
||||
":taco:": [0, 0, 50],
|
||||
":burrito:": [0, 0, 0],
|
||||
":potato:": [0, 30, 60],
|
||||
":doughnut:": [0, 5, 10],
|
||||
":fries:": [5, 10, 15],
|
||||
":eggplant:": [0, 0, 10],
|
||||
":baguette_bread:": [0, 42, 75],
|
||||
":avocado:": [0, 50, 100],
|
||||
":moneybag:": [0, 0, 1000]
|
||||
}
|
||||
|
||||
|
||||
slotsHeader = ":regional_indicator_s::regional_indicator_l::regional_indicator_o::regional_indicator_t:" \
|
||||
":regional_indicator_s:"
|
||||
slotsEmptyRow = ":yellow_square::black_large_square::black_large_square::black_large_square::yellow_square:"
|
||||
slotsFooter = ":yellow_square::yellow_square::yellow_square::yellow_square::yellow_square:"
|
||||
|
||||
|
||||
def lost():
|
||||
with open("files/lost.json", "r") as fp:
|
||||
fc = json.load(fp)
|
||||
return int(fc["lost"])
|
||||
|
||||
|
||||
def lostToday():
|
||||
with open("files/lost.json", "r") as fp:
|
||||
fc = json.load(fp)
|
||||
return int(fc["today"])
|
||||
29
functions/easterEggResponses.py
Normal file
29
functions/easterEggResponses.py
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
import random
|
||||
|
||||
from data import constants
|
||||
|
||||
|
||||
def control(message):
|
||||
if str(message.author.id) == constants.didierId:
|
||||
return ""
|
||||
elif didier(message.content):
|
||||
return "Hmm?"
|
||||
elif any(term in message.content for term in ["gib dink", "gib donk"]):
|
||||
return "No."
|
||||
elif didier(message.content.split(" ")[0]) and any(term in message.content.lower() for term in ["are you sure", "are u sure"]):
|
||||
return "I'm not just sure, I'm HIV Positive."
|
||||
elif any(message.content.lower().startswith(term) for term in ["is this", "isthis", "isdis", "is dis"]):
|
||||
res = random.randint(0, 100)
|
||||
return "No, this is Patrick." if res > 90 else ""
|
||||
elif " 69" in message.content or "69 " in message.content:
|
||||
res = random.randint(0, 100)
|
||||
return "Nice." if res > 70 else ""
|
||||
elif message.content.lower() == "hey":
|
||||
res = random.randint(0, 100)
|
||||
return "You're finally awake!" if res > 90 else ""
|
||||
return ""
|
||||
|
||||
|
||||
def didier(message):
|
||||
ml = message.lower()
|
||||
return ml == "didier" or ml == "<@!{}>".format(constants.didierId)
|
||||
52
functions/eten.py
Normal file
52
functions/eten.py
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
#!/usr/bin/env python3
|
||||
|
||||
import datetime
|
||||
import requests
|
||||
import sys
|
||||
|
||||
|
||||
def etenScript(weekDag):
|
||||
# What day
|
||||
weekdagen = ('ma', 'di', 'wo', 'do', 'vr', 'za', 'zo')
|
||||
deltas = {'morgen': 1,
|
||||
'overmorgen': 2,
|
||||
'volgende': 7}
|
||||
|
||||
d = datetime.date.today()
|
||||
|
||||
if weekDag in deltas:
|
||||
d += datetime.timedelta(deltas[weekDag])
|
||||
if weekDag[0:2] in weekdagen:
|
||||
while d.weekday() != weekdagen.index(weekDag[0:2]):
|
||||
d += datetime.timedelta(1)
|
||||
|
||||
menuSoep = ""
|
||||
menuHoofdgerechten = ""
|
||||
menuGroenten = ""
|
||||
|
||||
# Fetch from API
|
||||
try:
|
||||
menu = requests.get("https://zeus.ugent.be/hydra/api/2.0/resto/menu/nl/{}/{}/{}.json".format(d.year, d.month, d.day)).json()
|
||||
# Print menu
|
||||
|
||||
for s in menu["meals"]:
|
||||
if s["kind"] == "soup":
|
||||
menuSoep += ("* {} ({})\n".format(s["name"], s["price"]))
|
||||
|
||||
for m in menu["meals"]:
|
||||
if m["kind"] == "meat":
|
||||
menuHoofdgerechten += ("* Vlees: {} ({})\n".format(m["name"], m["price"]))
|
||||
elif m["kind"] == "fish":
|
||||
menuHoofdgerechten += ("* Vis: {} ({})\n".format(m["name"], m["price"]))
|
||||
elif m["kind"] == "vegetarian":
|
||||
menuHoofdgerechten += ("* Vegetarisch: {} ({})\n".format(m["name"], m["price"]))
|
||||
elif m["kind"] == "vegan":
|
||||
menuHoofdgerechten += ("* Vegan: {} ({})\n".format(m["name"], m["price"]))
|
||||
|
||||
for v in menu["vegetables"]:
|
||||
menuGroenten += ("* {}\n".format(v))
|
||||
except Exception:
|
||||
menuSoep += "Restaurant gesloten"
|
||||
menuGroenten += "Restaurant gesloten"
|
||||
menuHoofdgerechten += "Restaurant gesloten"
|
||||
return (menuSoep, menuHoofdgerechten, menuGroenten)
|
||||
29
functions/mock.py
Normal file
29
functions/mock.py
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
import random
|
||||
|
||||
|
||||
def mock(sentence: str):
|
||||
representations = {
|
||||
"i": "1",
|
||||
"o": "0",
|
||||
"e": "3"
|
||||
}
|
||||
switch = "[[" not in sentence
|
||||
arrRep = [letter for letter in sentence]
|
||||
retStr = ""
|
||||
for index, letter in enumerate(arrRep):
|
||||
if letter == "[":
|
||||
switch = True
|
||||
elif letter == "]":
|
||||
switch = False
|
||||
elif switch:
|
||||
if letter == "l":
|
||||
retStr += "L"
|
||||
elif letter in representations and random.randint(0, 10) > 8:
|
||||
retStr += representations[letter.lower()]
|
||||
elif letter == "i":
|
||||
retStr += "i"
|
||||
else:
|
||||
retStr += letter.upper() if index % 2 == 0 else letter.lower()
|
||||
else:
|
||||
retStr += letter
|
||||
return retStr
|
||||
18
functions/numbers.py
Normal file
18
functions/numbers.py
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
from enums.numbers import getRep as rep
|
||||
|
||||
|
||||
def clamp(value, bottom, top):
|
||||
if value < bottom:
|
||||
return bottom
|
||||
|
||||
if value > top:
|
||||
return top
|
||||
|
||||
return value
|
||||
|
||||
|
||||
def getRep(number, top):
|
||||
number = int(number)
|
||||
if number < top:
|
||||
return "{:,}".format(number)
|
||||
return rep(number)
|
||||
166
functions/reactWord.py
Normal file
166
functions/reactWord.py
Normal file
|
|
@ -0,0 +1,166 @@
|
|||
def check(content, earlier=[]):
|
||||
if len(content) < 1:
|
||||
return False, ["Controleer je argumenten."]
|
||||
if any(not (x.isalpha() or x.isdigit() or x in ["#", "*", "!", "?"]) for x in content):
|
||||
return False, ["Dit is geen geldig woord."]
|
||||
if content[-1].isdigit() and len(content[-1]) > 10:
|
||||
content[0] = "".join(x for x in content[:-1])
|
||||
else:
|
||||
content[0] = "".join(x for x in content)
|
||||
|
||||
doubles = {
|
||||
"a": ["regional_indicator_a", "a", "four"],
|
||||
"b": ["regional_indicator_b", "b"],
|
||||
"o": ["regional_indicator_o", "o2", "zero"],
|
||||
"i": ["regional_indicator_i", "information_source", "one"],
|
||||
"p": ["regional_indicator_p", "parking"],
|
||||
"m": ["regional_indicator_m", "m"],
|
||||
"s": ["regional_indicator_s", "five"],
|
||||
"g": ["regional_indicator_g", "six"],
|
||||
"e": ["regional_indicator_e", "three"],
|
||||
"!": ["exclamation", "grey_exclamation"],
|
||||
"?": ["question", "grey_question"]
|
||||
}
|
||||
|
||||
nums = {
|
||||
"0": "zero",
|
||||
"1": "one",
|
||||
"2": "two",
|
||||
"3": "three",
|
||||
"4": "four",
|
||||
"5": "five",
|
||||
"6": "six",
|
||||
"7": "seven",
|
||||
"8": "eight",
|
||||
"9": "nine"
|
||||
}
|
||||
|
||||
specials = {
|
||||
"?": ["question", "grey_question"],
|
||||
"!": ["exclamation", "grey_exclamation"],
|
||||
"*": ["asterisk"],
|
||||
"#": ["hash"]
|
||||
}
|
||||
|
||||
unidic = {
|
||||
"regional_indicator_a": "🇦",
|
||||
"regional_indicator_b": "🇧",
|
||||
"regional_indicator_c": "🇨",
|
||||
"regional_indicator_d": "🇩",
|
||||
"regional_indicator_e": "🇪",
|
||||
"regional_indicator_f": "🇫",
|
||||
"regional_indicator_g": "🇬",
|
||||
"regional_indicator_h": "🇭",
|
||||
"regional_indicator_i": "🇮",
|
||||
"regional_indicator_j": "🇯",
|
||||
"regional_indicator_k": "🇰",
|
||||
"regional_indicator_l": "🇱",
|
||||
"regional_indicator_m": "🇲",
|
||||
"regional_indicator_n": "🇳",
|
||||
"regional_indicator_o": "🇴",
|
||||
"regional_indicator_p": "🇵",
|
||||
"regional_indicator_q": "🇶",
|
||||
"regional_indicator_r": "🇷",
|
||||
"regional_indicator_s": "🇸",
|
||||
"regional_indicator_t": "🇹",
|
||||
"regional_indicator_u": "🇺",
|
||||
"regional_indicator_v": "🇻",
|
||||
"regional_indicator_w": "🇼",
|
||||
"regional_indicator_x": "🇽",
|
||||
"regional_indicator_y": "🇾",
|
||||
"regional_indicator_z": "🇿",
|
||||
"a": "🅰️",
|
||||
"b": "🅱️",
|
||||
"o2": "🅾️",
|
||||
"information_source": "ℹ️",
|
||||
"parking": "🅿️",
|
||||
"m": "Ⓜ️",
|
||||
"zero": "0⃣",
|
||||
"one": "1️⃣",
|
||||
"two": "2️⃣",
|
||||
"three": "3️⃣",
|
||||
"four": "4️⃣",
|
||||
"five": "5️⃣",
|
||||
"six": "6️⃣",
|
||||
"seven": "7️⃣",
|
||||
"eight": "8️⃣",
|
||||
"nine": "9️⃣",
|
||||
"exclamation": "❗",
|
||||
"grey_exclamation": "❕",
|
||||
"question": "❓",
|
||||
"grey_question": "❔",
|
||||
"hash": "#️⃣",
|
||||
"asterisk": "*️⃣"
|
||||
}
|
||||
|
||||
for x in earlier:
|
||||
if x in unidic.values():
|
||||
word = ""
|
||||
for key in unidic:
|
||||
if unidic[key] == x:
|
||||
word = key
|
||||
break
|
||||
del unidic[word]
|
||||
for k in list(doubles.keys()):
|
||||
if word in doubles[k]:
|
||||
doubles[k].remove(word)
|
||||
if len(doubles[k]) == 0:
|
||||
del doubles[k]
|
||||
break
|
||||
for k in list(nums.keys()):
|
||||
if nums[k] == word:
|
||||
del nums[k]
|
||||
for k in list(specials.keys()):
|
||||
if word in specials[k]:
|
||||
specials[k].remove(word)
|
||||
if len(specials[k]) == 0:
|
||||
del specials[k]
|
||||
|
||||
for letter in content[0]:
|
||||
c = content[0].count(letter)
|
||||
if c != 1 and letter not in doubles:
|
||||
return False, ["Dit is geen geldig woord."]
|
||||
elif c > 1 and letter in doubles and len(doubles[letter]) < c:
|
||||
return False, ["Dit is geen geldig woord."]
|
||||
|
||||
arr = []
|
||||
for letter in content[0]:
|
||||
if letter.isalpha():
|
||||
if "regional_indicator_{}".format(letter) in unidic and unidic["regional_indicator_{}".format(letter)] not in arr:
|
||||
arr.append(unidic["regional_indicator_{}".format(letter)])
|
||||
if letter in doubles:
|
||||
doubles[letter] = doubles[letter][1:]
|
||||
elif letter in doubles:
|
||||
if len(doubles[letter]) == 0:
|
||||
return False, ["Dit is geen geldig woord."]
|
||||
# Remove the number-equivalent from nums if it is used as a substitute here
|
||||
arr.append(unidic[doubles[letter][0]])
|
||||
if doubles[letter][0] in nums.values():
|
||||
for k in nums:
|
||||
if nums[k] == doubles[letter][0]:
|
||||
del nums[k]
|
||||
break
|
||||
doubles[letter] = doubles[letter][1:]
|
||||
if len(doubles[letter]) == 0:
|
||||
del doubles[letter]
|
||||
else:
|
||||
return False, ["Dit is geen geldig woord."]
|
||||
elif letter in specials:
|
||||
if len(specials[letter]) == 0:
|
||||
return False, ["Dit is geen geldig woord."]
|
||||
arr.append(unidic[specials[letter][0]])
|
||||
specials[letter].pop(0)
|
||||
if len(specials[letter]) == 0:
|
||||
del specials[letter]
|
||||
else:
|
||||
if letter not in nums:
|
||||
return False, ["Dit is geen geldig woord."]
|
||||
arr.append(unidic[nums[letter]])
|
||||
for x in doubles:
|
||||
# Remove this number as a substitute if it is used anywhere
|
||||
if nums[letter] == doubles[x][-1]:
|
||||
doubles[x] = doubles[x][:-1]
|
||||
if len(doubles[x]) == 0:
|
||||
del doubles[x]
|
||||
break
|
||||
return True, arr
|
||||
15
functions/stringFormatters.py
Normal file
15
functions/stringFormatters.py
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
def titleCase(string):
|
||||
return " ".join(capitalize(word) for word in string.split(" "))
|
||||
|
||||
|
||||
def capitalize(string):
|
||||
if len(string) > 1:
|
||||
return string[0].upper() + string[1:].lower()
|
||||
return string[0].upper()
|
||||
|
||||
|
||||
def leadingZero(string, size=2):
|
||||
string = str(string)
|
||||
while len(string) < size:
|
||||
string = "0" + string
|
||||
return string
|
||||
123
functions/sunrise.py
Normal file
123
functions/sunrise.py
Normal file
|
|
@ -0,0 +1,123 @@
|
|||
from math import cos, sin, acos, asin, tan
|
||||
from math import degrees as deg, radians as rad
|
||||
from datetime import date, datetime, time
|
||||
|
||||
import pytz
|
||||
|
||||
|
||||
class Sun:
|
||||
"""
|
||||
Calculate sunrise and sunset based on equations from NOAA
|
||||
http://www.srrb.noaa.gov/highlights/sunrise/calcdetails.html
|
||||
|
||||
typical use, calculating the sunrise at the present day:
|
||||
|
||||
import datetime
|
||||
import sunrise
|
||||
s = sun()
|
||||
print('sunrise at ',s.sunrise(when=datetime.datetime.now())
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
self.lat = 51.027169
|
||||
self.long = 3.710359
|
||||
|
||||
def sunrise(self, when=None):
|
||||
"""
|
||||
return the time of sunrise as a datetime.time object
|
||||
when is a datetime.datetime object. If none is given
|
||||
a local time zone is assumed (including daylight saving
|
||||
if present)
|
||||
"""
|
||||
if when is None: when = datetime.now(tz=pytz.timezone("Europe/Brussels"))
|
||||
self.__preptime(when)
|
||||
self.__calc()
|
||||
return Sun.__timefromdecimalday(self.sunrise_t)
|
||||
|
||||
def sunset(self, when=None):
|
||||
if when is None: when = datetime.now(tz=pytz.timezone("Europe/Brussels"))
|
||||
self.__preptime(when)
|
||||
self.__calc()
|
||||
return Sun.__timefromdecimalday(self.sunset_t)
|
||||
|
||||
def solarnoon(self, when=None):
|
||||
if when is None: when = datetime.now(tz=pytz.timezone("Europe/Brussels"))
|
||||
self.__preptime(when)
|
||||
self.__calc()
|
||||
return Sun.__timefromdecimalday(self.solarnoon_t)
|
||||
|
||||
@staticmethod
|
||||
def __timefromdecimalday(day):
|
||||
"""
|
||||
returns a datetime.time object.
|
||||
|
||||
day is a decimal day between 0.0 and 1.0, e.g. noon = 0.5
|
||||
"""
|
||||
hours = 24.0 * day
|
||||
h = int(hours)
|
||||
minutes = (hours - h) * 60
|
||||
m = int(minutes)
|
||||
seconds = (minutes - m) * 60
|
||||
s = int(seconds)
|
||||
return time(hour=h, minute=m, second=s)
|
||||
|
||||
def __preptime(self, when):
|
||||
"""
|
||||
Extract information in a suitable format from when,
|
||||
a datetime.datetime object.
|
||||
"""
|
||||
# datetime days are numbered in the Gregorian calendar
|
||||
# while the calculations from NOAA are distibuted as
|
||||
# OpenOffice spreadsheets with days numbered from
|
||||
# 1/1/1900. The difference are those numbers taken for
|
||||
# 18/12/2010
|
||||
self.day = when.toordinal() - (734124 - 40529)
|
||||
t = when.time()
|
||||
self.time = (t.hour + t.minute / 60.0 + t.second / 3600.0) / 24.0
|
||||
|
||||
self.timezone = 0
|
||||
offset = when.utcoffset()
|
||||
if not offset is None:
|
||||
self.timezone = offset.seconds / 3600.0
|
||||
|
||||
def __calc(self):
|
||||
"""
|
||||
Perform the actual calculations for sunrise, sunset and
|
||||
a number of related quantities.
|
||||
|
||||
The results are stored in the instance variables
|
||||
sunrise_t, sunset_t and solarnoon_t
|
||||
"""
|
||||
timezone = self.timezone # in hours, east is positive
|
||||
longitude = self.long # in decimal degrees, east is positive
|
||||
latitude = self.lat # in decimal degrees, north is positive
|
||||
|
||||
time = self.time # percentage past midnight, i.e. noon is 0.5
|
||||
day = self.day # daynumber 1=1/1/1900
|
||||
|
||||
Jday = day + 2415018.5 + time - timezone / 24 # Julian day
|
||||
Jcent = (Jday - 2451545) / 36525 # Julian century
|
||||
|
||||
Manom = 357.52911 + Jcent * (35999.05029 - 0.0001537 * Jcent)
|
||||
Mlong = 280.46646 + Jcent * (36000.76983 + Jcent * 0.0003032) % 360
|
||||
Eccent = 0.016708634 - Jcent * (0.000042037 + 0.0001537 * Jcent)
|
||||
Mobliq = 23 + (26 + ((21.448 - Jcent * (46.815 + Jcent * (0.00059 - Jcent * 0.001813)))) / 60) / 60
|
||||
obliq = Mobliq + 0.00256 * cos(rad(125.04 - 1934.136 * Jcent))
|
||||
vary = tan(rad(obliq / 2)) * tan(rad(obliq / 2))
|
||||
Seqcent = sin(rad(Manom)) * (1.914602 - Jcent * (0.004817 + 0.000014 * Jcent)) + sin(rad(2 * Manom)) * (
|
||||
0.019993 - 0.000101 * Jcent) + sin(rad(3 * Manom)) * 0.000289
|
||||
Struelong = Mlong + Seqcent
|
||||
Sapplong = Struelong - 0.00569 - 0.00478 * sin(rad(125.04 - 1934.136 * Jcent))
|
||||
declination = deg(asin(sin(rad(obliq)) * sin(rad(Sapplong))))
|
||||
|
||||
eqtime = 4 * deg(
|
||||
vary * sin(2 * rad(Mlong)) - 2 * Eccent * sin(rad(Manom)) + 4 * Eccent * vary * sin(rad(Manom)) * cos(
|
||||
2 * rad(Mlong)) - 0.5 * vary * vary * sin(4 * rad(Mlong)) - 1.25 * Eccent * Eccent * sin(
|
||||
2 * rad(Manom)))
|
||||
|
||||
hourangle = deg(acos(cos(rad(90.833)) / (cos(rad(latitude)) * cos(rad(declination))) - tan(rad(latitude)) * tan(
|
||||
rad(declination))))
|
||||
|
||||
self.solarnoon_t = (720 - 4 * longitude - eqtime + timezone * 60) / 1440
|
||||
self.sunrise_t = self.solarnoon_t - hourangle * 4 / 1440
|
||||
self.sunset_t = self.solarnoon_t + hourangle * 4 / 1440
|
||||
0
functions/test.py
Normal file
0
functions/test.py
Normal file
137
functions/timeFormatters.py
Normal file
137
functions/timeFormatters.py
Normal file
|
|
@ -0,0 +1,137 @@
|
|||
import datetime
|
||||
import time
|
||||
|
||||
import dateutil.relativedelta
|
||||
import pytz
|
||||
|
||||
|
||||
def epochToDate(epochTimeStamp):
|
||||
now = dateTimeNow()
|
||||
updateTime = datetime.datetime.fromtimestamp(int(epochTimeStamp) / 1000, pytz.timezone("Europe/Brussels"))
|
||||
diff = now - updateTime
|
||||
updateFormatted = str(updateTime.strftime('%m/%d/%Y om %H:%M:%S'))
|
||||
timeAgo = str(time.strftime('%H:%M:%S', time.gmtime(diff.total_seconds())))
|
||||
return {"date": updateFormatted, "timeAgo": timeAgo}
|
||||
|
||||
|
||||
def dateTimeNow():
|
||||
return datetime.datetime.now(pytz.timezone("Europe/Brussels"))
|
||||
|
||||
|
||||
def leadingZero(hourMinutes):
|
||||
return ("0" if len(hourMinutes) == 3 else "") + hourMinutes
|
||||
|
||||
|
||||
def delimiter(hourMinutes, delim=":"):
|
||||
return hourMinutes[:2] + delim + hourMinutes[2:]
|
||||
|
||||
|
||||
def timeFromInt(value):
|
||||
return delimiter(leadingZero(str(value)))
|
||||
|
||||
|
||||
# Returns age in YMWD
|
||||
def age(seconds):
|
||||
# Amount of years
|
||||
years, seconds = timeIn(seconds, "years")
|
||||
months, seconds = timeIn(seconds, "months")
|
||||
weeks, seconds = timeIn(seconds, "weeks")
|
||||
days, seconds = timeIn(seconds, "days")
|
||||
|
||||
return {"years": years, "months": months, "weeks": weeks, "days": days}
|
||||
|
||||
|
||||
# Returns amount of [unit] in [seconds] + the remaining seconds
|
||||
def timeIn(seconds, unit):
|
||||
timeDic = {"years": 31556926, "months": 2629743, "weeks": 604800, "days": 86400}
|
||||
timeUnit = timeDic[unit]
|
||||
return seconds // timeUnit, seconds - ((seconds // timeUnit) * timeUnit)
|
||||
|
||||
|
||||
# Creates a string representation based on Days/Hours/Minutes/Seconds
|
||||
def diffDayBasisString(timestamp):
|
||||
if isinstance(timestamp, int):
|
||||
timestamp = datetime.datetime.fromtimestamp(timestamp)
|
||||
now = datetime.datetime.fromtimestamp(time.time())
|
||||
diff = dateutil.relativedelta.relativedelta(now, timestamp)
|
||||
|
||||
timeList = []
|
||||
|
||||
# Don't add obsolete info such as "0 days", ...
|
||||
if diff.days != 0:
|
||||
timeList.append("{} {}".format(diff.days, getPlural(diff.days, "days")))
|
||||
|
||||
if diff.hours != 0:
|
||||
timeList.append("{} uur".format(diff.hours))
|
||||
|
||||
if diff.minutes != 0:
|
||||
timeList.append("{} {}".format(diff.minutes, getPlural(diff.minutes, "minutes")))
|
||||
|
||||
if diff.seconds != 0:
|
||||
timeList.append("{} {}".format(diff.seconds, getPlural(diff.seconds, "seconds")))
|
||||
|
||||
timeString = ", ".join(timeList[:-1])
|
||||
if len(timeString) > 0:
|
||||
timeString += " en "
|
||||
timeString += timeList[-1]
|
||||
return timeString
|
||||
|
||||
|
||||
def diffYearBasisString(timestamp):
|
||||
if isinstance(timestamp, int):
|
||||
timestamp = datetime.datetime.fromtimestamp(timestamp)
|
||||
now = datetime.datetime.fromtimestamp(time.time())
|
||||
diff = dateutil.relativedelta.relativedelta(now, timestamp)
|
||||
|
||||
timeList = []
|
||||
|
||||
# Don't add obsolete info such as "0 days", ...
|
||||
if diff.years != 0:
|
||||
timeList.append("{} jaar".format(diff.years))
|
||||
|
||||
if diff.months != 0:
|
||||
timeList.append("{} {}".format(diff.months, getPlural(diff.months, "months")))
|
||||
|
||||
if diff.weeks != 0:
|
||||
timeList.append("{} {}".format(diff.weeks, getPlural(diff.weeks, "weeks")))
|
||||
|
||||
if diff.days != 0:
|
||||
timeList.append("{} {}".format(diff.days, getPlural(diff.days, "days")))
|
||||
|
||||
timeString = ", ".join(timeList[:-1])
|
||||
if len(timeString) > 0:
|
||||
timeString += " en "
|
||||
timeString += timeList[-1]
|
||||
return timeString
|
||||
|
||||
|
||||
# Returns the full day based on an abbreviation or full name
|
||||
def getFormat(term):
|
||||
terms = ["days", "weeks", "months", "years"]
|
||||
for word in terms:
|
||||
if word.startswith(term.lower()):
|
||||
return word
|
||||
return None
|
||||
|
||||
|
||||
# Gets the plural of a unit if necessary
|
||||
def getPlural(amount, unit):
|
||||
dic = {
|
||||
"seconds": {"s": "seconde", "p": "seconden"},
|
||||
"minutes": {"s": "minuut", "p": "minuten"},
|
||||
"hours": {"s": "uur", "p": "uur"},
|
||||
"days": {"s": "dag", "p": "dagen"},
|
||||
"weeks": {"s": "week", "p": "weken"},
|
||||
"months": {"s": "maand", "p": "maanden"},
|
||||
"years": {"s": "jaar", "p": "jaar"}
|
||||
}
|
||||
return dic[unit.lower()]["s" if amount == 1 else "p"]
|
||||
|
||||
|
||||
def weekdayToInt(day):
|
||||
days = {"maandag": 0, "dinsdag": 1, "woensdag": 2, "donderdag": 3, "vrijdag": 4, "zaterdag": 5, "zondag": 6}
|
||||
return days[day.lower()]
|
||||
|
||||
|
||||
def intToWeekday(day):
|
||||
return ["Maandag", "Dinsdag", "Woensdag", "Donderdag", "Vrijdag", "Zaterdag", "Zondag"][day]
|
||||
19
functions/xp.py
Normal file
19
functions/xp.py
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
import math
|
||||
|
||||
|
||||
def calculate_level(xp):
|
||||
xp = int(xp)
|
||||
level = 1
|
||||
|
||||
while level_to_xp(level + 1) < xp:
|
||||
level += 1
|
||||
|
||||
return level
|
||||
|
||||
|
||||
def level_to_xp(level):
|
||||
return math.floor(sum((equate(lvl) for lvl in range(1, level))) / 4)
|
||||
|
||||
|
||||
def equate(xp):
|
||||
return math.floor(xp + 300 * (2 ** (xp / 7.0)))
|
||||
Loading…
Add table
Add a link
Reference in a new issue