Merge pull request #39 from victormylle/quiz_streak

Quiz streak
This commit is contained in:
victormylle
2020-11-18 20:09:37 +01:00
committed by GitHub
18 changed files with 112 additions and 43 deletions

0
.gitignore vendored Normal file → Executable file
View File

0
DiscordVerifier/src/DatabaseConnection.java Normal file → Executable file
View File

0
DiscordVerifier/src/RedeemCommandListeners.java Normal file → Executable file
View File

0
Dockerfile Normal file → Executable file
View File

37
bot.py
View File

@@ -1,18 +1,27 @@
from discord.ext import commands
import os
from discord.ext import commands
class DiscordBot:
def __init__(self, config):
prefixes = ["/"]
self.client = commands.Bot(command_prefix=prefixes, case_insensitive=True)
self.client.prefixes = prefixes
# Load this cog first so the other cogs can use properties initialized here
self.client.load_extension("cogs.events")
for file in os.listdir("./cogs"):
if file.endswith(".py") and not (file.startswith(("events",))):
self.client.load_extension(f"cogs.{file[:-3]}")
def run(self):
self.client.run("NzYwNTI5NDY2MDI3MDE2MjUy.X3NYQg.Nz3bwxgltlayMStfT7F-OCbx9pE")
def get_client(self):
return self.client
prefixes = ["/"]
client = commands.Bot(command_prefix=prefixes, case_insensitive=True)
client.prefixes = prefixes
# Load this cog first so the other cogs can use properties initialized here
client.load_extension("cogs.events")
for file in os.listdir("./cogs"):
if file.endswith(".py") and not (file.startswith(("events",))):
client.load_extension(f"cogs.{file[:-3]}")
client.run("NzYwNTI5NDY2MDI3MDE2MjUy.X3NYQg.Nz3bwxgltlayMStfT7F-OCbx9pE")
bot = DiscordBot(None)
bot.run()

0
cogs/events.py Normal file → Executable file
View File

0
cogs/leaderboards.py Normal file → Executable file
View File

53
cogs/quiz.py Normal file → Executable file
View File

@@ -143,8 +143,8 @@ class QuizQuestions(commands.Cog):
class Quiz(commands.Cog):
def __init__(self, client):
self.client = client
#self.interval = (5, 10)
self.interval = (5*60, 20*60)
self.interval = (1, 4)
#self.interval = (5*60, 20*60)
self.auto = False
self.timeout = 10*60
@@ -187,11 +187,11 @@ class Quiz(commands.Cog):
embed.colour = discord.Colour.orange()
embed.add_field(name="Question:", value=f"{question}", inline=False)
embed.add_field(name="Reward:", value=f"${reward} in game", inline=False)
embed.add_field(name="Reward:", value=f"${reward} x streak in game", inline=False)
embed.add_field(name="End:", value=f"The quiz will end in 10 minutes!", inline=False)
return embed
def create_answer_embed(self, question, answer, reward, author=None, linked=False, correct=False):
def create_answer_embed(self, question, answer, reward, streak=-1, author=None, linked=False, correct=False):
embed = discord.Embed()
embed.add_field(name="Question:", value=f"{question}", inline=False)
@@ -203,9 +203,13 @@ class Quiz(commands.Cog):
if linked:
embed.add_field(name="Winner:", value=f"{author.mention} 🎉🎉", inline=False)
embed.add_field(name="Claim:", value=f"Claim your reward in Minecraft by using /redeem")
if streak > 1:
embed.add_field(name="Streak:", value=f"{author.mention} has a streak going of {streak}", inline=False)
else:
embed.add_field(name="Winner:", value=f"{author.mention} 🎉🎉", inline=False)
embed.add_field(name="Claim:", value=f"1. Link your account by using /link <MinecraftName> \n2. Claim your reward in Minecraft by using /redeem")
embed.add_field(name="Claim:", value=f"1. Link your account by using /link <MinecraftName> \n2. Claim your reward in Minecraft by using /redeem", inline=False)
if streak > 1:
embed.add_field(name="Streak:", value=f"{author.mention} has a streak going of {streak}", inline=False)
else:
embed.colour = discord.Colour.red()
return embed
@@ -219,12 +223,14 @@ class Quiz(commands.Cog):
await channel.edit(slowmode_delay=1)
try:
message = await self.client.wait_for("message", check=lambda message: message.content.isdigit() and int(message.content) == random_number, timeout=self.timeout)
self.give_reward(message.author.id, ranges[range])
streak = self.give_reward(message.author.id, ranges[range])
playerdblinker = PlayerDBLinker()
linked = playerdblinker.discordidused(message.author.id)
await message.channel.send(embed=self.create_answer_embed(f"Guess the number from 1 to {range}", str(random_number), ranges[range], message.author, linked, True))
await message.channel.send(embed=self.create_answer_embed(f"Guess the number from 1 to {range}", str(random_number), ranges[range] * streak, streak, message.author, linked, True))
playerdblinker.close()
except asyncio.TimeoutError:
self.reset_current_streak()
await channel.send("Nobody found the correct answer!")
await channel.send(embed=self.create_answer_embed(f"Guess the number from 1 to {range}", str(random_number), ranges[range]))
await channel.edit(slowmode_delay=10)
@@ -236,12 +242,17 @@ class Quiz(commands.Cog):
await channel.send(embed=self.create_question_embed(question[1], question[3]))
try:
message = await self.client.wait_for("message", check=lambda message: message.content.lower() == question[2].lower(), timeout=self.timeout)
self.give_reward(message.author.id, question[3])
streak = self.give_reward(message.author.id, question[3])
playerdblinker = PlayerDBLinker()
linked = playerdblinker.discordidused(message.author.id)
await message.channel.send(embed=self.create_answer_embed(question[1], question[2], question[3], message.author, linked, True))
await message.channel.send(embed=self.create_answer_embed(question[1], question[2], question[3] * streak, streak, message.author, linked, True))
if streak > 1:
await message.channel.send(f"{message.author.mention} has a streak going of {streak}")
playerdblinker.close()
except asyncio.TimeoutError:
self.reset_current_streak()
await channel.send("Nobody found the correct answer!")
await channel.send(embed=self.create_answer_embed(question[1], question[2], question[3]))
@@ -253,12 +264,14 @@ class Quiz(commands.Cog):
await channel.send(embed=self.create_question_embed(f"Find the word from: {shaken_word}", word['reward']))
try:
message = await self.client.wait_for("message", check=lambda message: message.content.lower() == word['word'].lower(), timeout=self.timeout)
self.give_reward(message.author.id, word["reward"])
streak = self.give_reward(message.author.id, word["reward"])
playerdblinker = PlayerDBLinker()
linked = playerdblinker.discordidused(message.author.id)
await message.channel.send(embed=self.create_answer_embed(f"Find the word from: {shaken_word}", word["word"], word["reward"], message.author, linked, True))
await message.channel.send(embed=self.create_answer_embed(f"Find the word from: {shaken_word}", word["word"], word["reward"] * streak, streak, message.author, linked, True))
playerdblinker.close()
except asyncio.TimeoutError:
self.reset_current_streak()
await channel.send("Nobody found the correct answer!")
await channel.send(embed=self.create_answer_embed(f"Find the word from: {shaken_word}", word["word"], word["reward"]))
@@ -290,10 +303,26 @@ class Quiz(commands.Cog):
wordgamedb.word_asked_increment(w_id)
wordgamedb.close()
def reset_current_streak(self):
quiz_players_db = QuizPlayersDB()
current = quiz_players_db.get_current_streak()
if current != None:
quiz_players_db.reset_streak(current["discordid"])
def give_reward(self, discordid, reward):
quiz_players_db = QuizPlayersDB()
quiz_players_db.player_won(discordid, reward)
previousstreak = quiz_players_db.get_current_streak()
if previousstreak is not None and str(previousstreak["discordid"]) != str(discordid):
quiz_players_db.reset_streak(previousstreak["discordid"])
if previousstreak is not None and previousstreak["discordid"] == discordid:
quiz_players_db.player_won(discordid, reward * (previousstreak["cur_streak"] + 1))
else:
quiz_players_db.player_won(discordid, reward)
current_streak = quiz_players_db.get_current_streak()
quiz_players_db.close()
return current_streak["cur_streak"]
def setup(client):

0
cogs/serverstatus.py Normal file → Executable file
View File

0
credentials.json Normal file → Executable file
View File

View File

@@ -60,7 +60,7 @@ class QuizPlayersDB:
else:
self.discorddbconn = DatabaseConnection(database="worldcraft_discord")
cursor = self.discorddbconn.get_cursor()
cursor.execute("create table IF NOT EXISTS {} (discordid tinytext NOT NULL, wins int DEFAULT 0, rewards int DEFAULT 0, toclaim int DEFAULT 0)".format(self.tablename))
cursor.execute("create table IF NOT EXISTS {} (discordid tinytext NOT NULL, wins int DEFAULT 0, rewards int DEFAULT 0, toclaim int DEFAULT 0, cur_streak int DEFAULT 0, max_streak int DEFAULT 0, streak_count int DEFAULT 0)".format(self.tablename))
def player_exists(self, discordid):
cursor = self.discorddbconn.get_cursor()
@@ -69,15 +69,33 @@ class QuizPlayersDB:
res = cursor.fetchone()
return res[0] == 1
# give the user with discordid his reward + start streak
def player_won(self, discordid, reward):
cursor = self.discorddbconn.get_cursor()
if self.player_exists(discordid):
sql = f"UPDATE {self.tablename} SET wins = wins + 1, rewards = rewards + {str(reward)}, toclaim = toclaim + {str(reward)} WHERE discordid = {str(discordid)}"
cursor.execute(sql)
else:
sql = f"INSERT INTO {self.tablename} (discordid, wins, rewards, toclaim) VALUES ({str(discordid)}, 1, {reward}, {reward})"
sql = f"INSERT INTO {self.tablename} (discordid, wins, rewards, toclaim) VALUES ({str(discordid)}, 1, {reward}, {reward}, 0, 0)"
cursor.execute(sql)
self.increment_cur_streak(discordid)
self.discorddbconn.get_db().commit()
# get discord id of user with current streak
def get_current_streak(self):
cursor = self.discorddbconn.get_cursor(dictionary=True)
sql = f"SELECT discordid, cur_streak FROM {self.tablename} WHERE cur_streak > 0"
cursor.execute(sql)
res = cursor.fetchone()
return res
# set current streak to 0 from discorduser
def reset_streak(self, discordid):
cursor = self.discorddbconn.get_cursor(dictionary=True)
sql = f"UPDATE {self.tablename} SET cur_streak = 0 WHERE discordid = {str(discordid)}"
cursor.execute(sql)
self.discorddbconn.get_db().commit()
def get_top_players(self, limit = 20):
@@ -86,6 +104,31 @@ class QuizPlayersDB:
cursor.execute(sql)
return list(cursor.fetchall())
# increment the current streak of user with discordid (+ checks to increment max_streak and streak_count)
def increment_cur_streak(self, discordid):
cursor = self.discorddbconn.get_cursor(dictionary=True)
streaks = self.get_streaks(discordid)
if streaks["cur_streak"] == streaks["max_streak"]:
if streaks["cur_streak"] == 0:
sql = f"UPDATE {self.tablename} SET cur_streak = cur_streak + 1, max_streak = max_streak + 1, streak_count = streak_count + 1 WHERE discordid = {str(discordid)}"
else:
sql = f"UPDATE {self.tablename} SET cur_streak = cur_streak + 1, max_streak = max_streak + 1 WHERE discordid = {str(discordid)}"
else:
if streaks["cur_streak"] == 0:
sql = f"UPDATE {self.tablename} SET cur_streak = cur_streak + 1, streak_count = streak_count + 1 WHERE discordid = {str(discordid)}"
else:
sql = f"UPDATE {self.tablename} SET cur_streak = cur_streak + 1 WHERE discordid = {str(discordid)}"
cursor.execute(sql)
self.discorddbconn.get_db().commit()
# get the streak information from user with discordid
def get_streaks(self, discordid):
cursor = self.discorddbconn.get_cursor(dictionary=True)
sql = f"SELECT cur_streak, max_streak, streak_count FROM {self.tablename} WHERE discordid={str(discordid)}"
cursor.execute(sql)
return cursor.fetchone()
def close(self):
self.discorddbconn.close()

View File

@@ -21,6 +21,6 @@ modPlusRoles = [roleAdmin, roleMod, roleOwner]
# Channels
ModLogs = 760807882899193867
# dev
#QuizChannelID = 774418250665951232
QuizChannelID = 775776550871498752
QuizChannelID = 774418250665951232
#QuizChannelID = 775776550871498752
DiscordLinkerID = 776944220119760927

0
files/banned_words.json Normal file → Executable file
View File

0
functions/bannedWords.py Normal file → Executable file
View File

0
functions/embeds.py Normal file → Executable file
View File

0
functions/emoji_check.py Normal file → Executable file
View File

0
functions/timer.py Normal file → Executable file
View File

View File

@@ -1,12 +0,0 @@
#!/usr/bin/env python3
import socket
HOST = '127.0.0.1' # The server's hostname or IP address
PORT = 3333 # The port used by the server
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
s.sendall(b'Pieter suckt\n')
data = s.recv(1024)
print('Received', repr(data))