Merge branch 'master' into release_branch

This commit is contained in:
2020-11-17 01:18:37 +01:00
6 changed files with 296 additions and 61 deletions

View File

@@ -2,6 +2,7 @@ import discord
from discord.ext import commands
from data.DatabaseConnection import *
from datetime import datetime, timedelta
from functions.emoji_check import *
class Leaderboards(commands.Cog):
def __init__(self, client):
@@ -11,7 +12,7 @@ class Leaderboards(commands.Cog):
async def top(self, ctx, *args):
pass
def create_leaderboard_embed(self, title, column, time=False):
async def create_leaderboard_embed(self, title, column, time=False):
def seconds_to_time(s):
t = timedelta(seconds=s)
@@ -27,9 +28,19 @@ class Leaderboards(commands.Cog):
res += f"{d.second}s".zfill(3)
return res
playerdb = PlayerDBLinker()
top_players = playerdb.get_stats(column)
playerdb.close()
if column == "quizWins":
top_players = []
quizplayersdb = QuizPlayersDB()
for player in quizplayersdb.get_top_players():
discorduser = {}
discorduser["playerName"] = deEmojify((await self.client.fetch_user(player["discordid"])).name).strip()
discorduser["stat"] = player["stat"]
top_players.append(discorduser)
quizplayersdb.close()
else:
playerdb = PlayerDBLinker()
top_players = playerdb.get_stats(column)
playerdb.close()
embed = discord.Embed()
embed.colour = discord.Colour.orange()
embed.set_author(name="Top")
@@ -50,35 +61,48 @@ class Leaderboards(commands.Cog):
@top.command(name="broken", case_insensitive=True)
async def top_broken(self, ctx):
await ctx.send(embed=self.create_leaderboard_embed("Broken blocks", "brokenBlocks"))
embed = await self.create_leaderboard_embed("Broken blocks", "brokenBlocks")
await ctx.send(embed=embed)
@top.command(name="kills", case_insensitive=True)
async def top_kills(self, ctx):
await ctx.send(embed=self.create_leaderboard_embed("Kills", "pvpKills"))
embed = await self.create_leaderboard_embed("Kills", "pvpKills")
await ctx.send(embed=embed)
@top.command(name="deaths", case_insensitive=True)
async def top_deaths(self, ctx):
await ctx.send(embed=self.create_leaderboard_embed("Deaths", "pvpDeaths"))
embed = await self.create_leaderboard_embed("Deaths", "pvpDeaths")
await ctx.send(embed=embed)
@top.command(name="level", case_insensitive=True)
async def top_level(self, ctx):
await ctx.send(embed=self.create_leaderboard_embed("Level", "playerLevel"))
embed = await self.create_leaderboard_embed("Level", "playerLevel")
await ctx.send(embed=embed)
@top.command(name="placed", case_insensitive=True)
async def top_placed(self, ctx):
await ctx.send(embed=self.create_leaderboard_embed("Placed blocks", "placedBlocks"))
embed = await self.create_leaderboard_embed("Placed blocks", "placedBlocks")
await ctx.send(embed=embed)
@top.command(name="playedtime", aliases=["onlinetime"], case_insensitive=True)
async def top_playedtime(self, ctx):
await ctx.send(embed=self.create_leaderboard_embed("Played time", "onlineTime", time=True))
embed = await self.create_leaderboard_embed("Played time", "onlineTime", time=True)
await ctx.send(embed=embed)
@top.command(name="sailed", case_insensitive=True)
async def top_sailed(self, ctx):
await ctx.send(embed=self.create_leaderboard_embed("Sailed", "waterTravelledBlocks"))
embed = await self.create_leaderboard_embed("Sailed", "waterTravelledBlocks")
await ctx.send(embed=embed)
@top.command(name="walked", case_insensitive=True)
async def top_walked(self, ctx):
await ctx.send(embed=self.create_leaderboard_embed("Walked", "travelledBlocks"))
embed = await self.create_leaderboard_embed("Walked", "travelledBlocks")
await ctx.send(embed=embed)
@top.command(name="quiz", case_insensitive=True)
async def top_quiz(self, ctx):
embed = await self.create_leaderboard_embed("Quiz wins", "quizWins")
await ctx.send(embed=embed)
def setup(client):

View File

@@ -7,6 +7,8 @@ import asyncio
import threading
from functions.timer import Timer
from data import constants
from functions.emoji_check import *
import re
from data.DatabaseConnection import *
# 25216 --> uuid server
@@ -42,7 +44,7 @@ def send_chat(discordname, minecraftname, code):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
s.send(bytes("{}\t{}\t{}\n".format(discordname, minecraftname, code), encoding="ascii"))
s.send(bytes("{}\t{}\t{}\n".format(deEmojify(discordname), minecraftname, code), encoding="ascii"))
data = s.recv(1024)
data_string = data.decode("utf-8").strip('\n')
if data_string == "PlayerError":
@@ -149,8 +151,8 @@ class PlayerLink(commands.Cog):
except PlayerError:
await ctx.send("Player '" + arg + "' not found")
except:
await ctx.send("Something went wrong")
# except:
# await ctx.send("Something went wrong")
@commands.command(name="Unlink")
async def unlink(self, ctx):

View File

@@ -75,80 +75,198 @@ class QuizQuestions(commands.Cog):
finally:
quizdb.close()
@commands.group(name="wordgame",case_insensitive=True, invoke_without_command=True)
@commands.check(checks.isModPlus)
# /q&a add "What is ...." "Australia"
async def wordgame(self, ctx, *args):
pass
@wordgame.command(name="add")
@commands.check(checks.isModPlus)
async def add_word(self, ctx, w, reward=50):
try:
wordgamedb = WordGameDB()
w_id = wordgamedb.add_word(w, reward)
embed = discord.Embed()
embed.colour = discord.Colour.green()
embed.add_field(name="Success", value=f"Added word with {w_id}", inline=False)
await ctx.send(embed=embed)
except:
await ctx.send("Something went wrong")
finally:
wordgamedb.close()
@wordgame.command(name="rm")
@commands.check(checks.isModPlus)
async def rm_word(self, ctx, id):
try:
wordgamedb = WordGameDB()
wordgamedb.rm_word(id)
embed = discord.Embed()
embed.colour = discord.Colour.green()
embed.add_field(name="Success", value=f"Question removed with id {id}", inline=False)
await ctx.send(embed=embed)
except QuestionNotFound:
await ctx.send("No question found with id " + str(id))
except:
await ctx.send("Something went wrong")
finally:
wordgamedb.close()
@wordgame.command(name="show")
@commands.check(checks.isModPlus)
async def show_words(self, ctx):
try:
wordgamedb = WordGameDB()
words = wordgamedb.get_words()
if len(words) == 0:
embed = discord.Embed()
embed.colour = discord.Colour.red()
embed.add_field(name="Words", value=f"No words found", inline=False)
await ctx.send(embed=embed)
else:
embed = discord.Embed()
embed.set_author(name="Words")
embed.colour = discord.Colour.orange()
for w in words:
embed.add_field(name=f"id: {w['id']}", value=f"Word: '{w['word']}'\nReward: {w['reward']}\nUsed: {w['asked']}", inline=False)
await ctx.send(embed=embed)
except:
await ctx.send("Something went wrong")
finally:
wordgamedb.close()
class Quiz(commands.Cog):
def __init__(self, client):
self.client = client
self.interval = (5, 10)
self.interval = (8*60, 30*60)
#self.interval = (5, 10)
self.interval = (5*60, 20*60)
self.auto = False
self.timeout = 60*10
self.timeout = 10*60
@commands.command(name="quiz")
@commands.group(name="quiz",case_insensitive=True, invoke_without_command=True)
@commands.check(checks.isModPlus)
async def quiz_bot(self, ctx, f, *args):
if (f == "auto" and not self.auto):
self.auto = True
asyncio.create_task(self.start_auto_quiz())
elif (f == "stop" and self.auto):
self.auto = False
async def quiz(self, ctx, f, *args):
pass
@quiz.command(name="auto")
@commands.check(checks.isModPlus)
async def auto_quiz(self, ctx):
self.auto = True
asyncio.create_task(self.start_auto_quiz())
@quiz.command(name="stop")
@commands.check(checks.isModPlus)
async def auto_quiz(self, ctx):
self.auto = False
async def start_auto_quiz(self):
while self.auto:
await asyncio.sleep(random.randint(self.interval[0], self.interval[1]))
await self.ask_question()
perc = random.random()
if perc < 0.5:
await self.guess_the_number()
elif perc < 0.8:
await self.start_word_game()
else:
await self.ask_question()
@commands.Cog.listener()
async def on_ready(self):
self.auto = True
asyncio.create_task(self.start_auto_quiz())
async def ask_question(self):
question = self.get_random_question()
self.increment_asked_count(question[0])
channel = self.client.get_channel(constants.QuizChannelID)
def create_question_embed(self, question, reward):
embed = discord.Embed()
#embed.set_author(name="Quiz")
embed.colour = discord.Colour.orange()
embed.add_field(name="Question:", value=f"{question[1]}", inline=False)
embed.add_field(name="Reward:", value=f"${question[3]} in game", inline=False)
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="End:", value=f"The quiz will end in 10 minutes!", inline=False)
await channel.send(embed=embed)
return embed
def create_answer_embed(self, question, answer, reward, author=None, linked=False, correct=False):
embed = discord.Embed()
embed.colour = discord.Colour.orange()
embed.add_field(name="Question:", value=f"{question[1]}", inline=False)
embed.add_field(name="Reward:", value=f"${question[3]} in game", inline=False)
embed.add_field(name="Answer:", value=f"{question[2]}", inline=False)
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="Answer:", value=f"{answer}", inline=False)
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])
playerdblinker = PlayerDBLinker()
if correct:
embed.colour = discord.Colour.green()
if playerdblinker.discordidused(message.author.id):
embed.add_field(name="Winner:", value=f"{message.author.mention} 🎉🎉", inline=False)
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")
#embed.add_field(name="Claim:", value=f"Claim your reward in Minecraft when the server is online")
await message.channel.send(embed=embed)
else:
embed.add_field(name="Winner:", value=f"{message.author.mention} 🎉🎉", inline=False)
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"Claim your reward in Minecraft when the server is online")
await message.channel.send(embed=embed)
else:
embed.colour = discord.Colour.red()
return embed
async def guess_the_number(self):
ranges = {10: 50, 25: 75, 50: 100, 75: 125, 100: 150}
range = random.choice(list(ranges))
random_number = random.randint(1, range)
channel = self.client.get_channel(constants.QuizChannelID)
await channel.send(embed=self.create_question_embed(f"Guess the number from 1 to {range}", ranges[range]))
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])
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))
playerdblinker.close()
except asyncio.TimeoutError:
await channel.send("Nobody found the correct answer!")
embed.colour = discord.Colour.red()
await channel.send(embed=embed)
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)
async def ask_question(self):
question = self.get_random_question()
self.increment_asked_count(question[0])
channel = self.client.get_channel(constants.QuizChannelID)
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])
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))
playerdblinker.close()
except asyncio.TimeoutError:
await channel.send("Nobody found the correct answer!")
await channel.send(embed=self.create_answer_embed(question[1], question[2], question[3]))
async def start_word_game(self):
word = self.get_random_word()
self.increment_asked_word(int(word["id"]))
channel = self.client.get_channel(constants.QuizChannelID)
shaken_word = self.shake_word(word["word"].lower())
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"])
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))
playerdblinker.close()
except asyncio.TimeoutError:
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"]))
def shake_word(self, word):
word_list = list(word)
random.shuffle(word_list)
return "".join(word_list)
def increment_asked_count(self, q_id):
quizdb = QuizDB()
@@ -161,6 +279,17 @@ class Quiz(commands.Cog):
quizdb.close()
return q
def get_random_word(self):
wordgamedb = WordGameDB()
w = wordgamedb.get_random_word()
wordgamedb.close()
return w
def increment_asked_word(self, w_id):
wordgamedb = WordGameDB()
wordgamedb.word_asked_increment(w_id)
wordgamedb.close()
def give_reward(self, discordid, reward):
quiz_players_db = QuizPlayersDB()
quiz_players_db.player_won(discordid, reward)

View File

@@ -10,6 +10,8 @@ class PlayerNotLinked(Exception):
pass
class QuestionNotFound(Exception):
pass
class WordNotFound(Exception):
pass
class PlayerNotFound(Exception):
pass
@@ -26,8 +28,9 @@ class DatabaseConnection:
elif database == "s13_worldcraft":
self.mydb = mysql.connector.connect(
host="192.168.1.251",
user="u13_f2zpWZpIKY",
password="@fZQ6Uu3+U^WH1i2JNemgTC7",
user="worldcraft",
port="3308",
password="uJpa9VOW2P0bh0p1",
database=database
)
elif database == "s13_ecobridge":
@@ -77,9 +80,76 @@ class QuizPlayersDB:
cursor.execute(sql)
self.discorddbconn.get_db().commit()
def get_top_players(self, limit = 20):
cursor = self.discorddbconn.get_cursor(dictionary=True)
sql = f"SELECT discordid, wins as stat FROM {self.tablename} ORDER BY wins DESC LIMIT {str(limit)}"
cursor.execute(sql)
return list(cursor.fetchall())
def close(self):
self.discorddbconn.close()
class WordGameDB:
def __init__(self):
self.tablename = "wordGame"
self.discorddbconn = DatabaseConnection(database="worldcraft_discord")
cursor = self.discorddbconn.get_cursor()
cursor.execute("create table IF NOT EXISTS {} (id int NOT NULL PRIMARY KEY AUTO_INCREMENT, word text NOT NULL, reward int NOT NULL, asked int DEFAULT 0)".format(self.tablename))
def add_word(self, word, reward):
cursor = self.discorddbconn.get_cursor()
sql = f"insert into {self.tablename} (word, reward) VALUES ('{word}', {str(reward)})"
try:
cursor.execute(sql)
self.discorddbconn.get_db().commit()
return cursor.lastrowid
except:
raise SQLInsertError()
def rm_word(self, id):
cursor = self.discorddbconn.get_cursor()
cursor.execute("select count(*) from {} where id={}".format(self.tablename, str(id)))
res = cursor.fetchone()
if res[0] == 1:
sql = f"DELETE FROM {self.tablename} WHERE id = {str(id)}"
cursor.execute(sql)
self.discorddbconn.get_db().commit()
else:
raise QuestionNotFound()
def get_words(self):
# word, used, reward
cursor = self.discorddbconn.get_cursor(dictionary=True)
sql = f"SELECT * FROM {self.tablename}"
cursor.execute(sql)
return list(cursor.fetchall())
def word_asked_increment(self, w_id):
cursor = self.discorddbconn.get_cursor()
sql = f"UPDATE {self.tablename} SET asked = asked + 1 WHERE id = {str(w_id)}"
cursor.execute(sql)
self.discorddbconn.get_db().commit()
def count_words(self):
cursor = self.discorddbconn.get_cursor()
cursor.execute("select count(*) from {}".format(self.tablename))
res = cursor.fetchone()
return res[0]
def get_random_word(self):
if self.count_words() != 0:
cursor = self.discorddbconn.get_cursor(dictionary=True)
sql = f"SELECT * FROM {self.tablename} ORDER BY RAND() LIMIT 1"
cursor.execute(sql)
return cursor.fetchone()
else:
raise WordNotFound()
def close(self):
self.discorddbconn.close()
class QuizDB:
def __init__(self):
self.tablename = "questions"
@@ -209,7 +279,6 @@ class PlayerDBLinker:
serverdb_cursor.execute(sql)
return list(serverdb_cursor.fetchall())
def close(self):
self.discorddbconn.close()
self.serverdbconn.close()

View File

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

10
functions/emoji_check.py Normal file
View File

@@ -0,0 +1,10 @@
import re
def deEmojify(text):
regrex_pattern = re.compile(pattern = "["
u"\U0001F600-\U0001F64F" # emoticons
u"\U0001F300-\U0001F5FF" # symbols & pictographs
u"\U0001F680-\U0001F6FF" # transport & map symbols
u"\U0001F1E0-\U0001F1FF" # flags (iOS)
"]+", flags = re.UNICODE)
return regrex_pattern.sub(r'',text)