3 Commits

Author SHA1 Message Date
f4e46c6854 added config file 2020-11-20 21:03:03 +01:00
60d6bd2c40 Started creating config file system 2020-11-20 21:01:41 +01:00
ae2e63da56 Started creating config file system 2020-11-20 21:00:56 +01:00
7 changed files with 119 additions and 75 deletions

32
bot.py
View File

@@ -1,27 +1,11 @@
#!/usr/bin/python
import sys
from discord.ext import commands
import os
import yaml
from bots.discordbot import DiscordBot
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
bot = DiscordBot(None)
bot.run()
if __name__ == "__main__":
bot = DiscordBot(sys.argv[1])
bot.run()

45
bots/discordbot.py Normal file
View File

@@ -0,0 +1,45 @@
import sys
from discord.ext import commands
import os
import yaml
class DiscordBot:
def __init__(self, config):
print("jajajah")
self.constants = ["token"]
self.modules = {"quiz": "quiz"}
prefixes = ["/"]
self.client = commands.Bot(command_prefix=prefixes, case_insensitive=True)
self.client.prefixes = prefixes
self.load_config(config)
# 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):
if "token" in self.client.config.keys():
print(self.client.config["token"])
self.client.run(self.client.config["token"])
def get_client(self):
return self.client
def load_config(self, config):
with open(config, 'r') as file:
try:
self.client.config = yaml.safe_load(file)
for cog in self.client.config:
if cog not in self.constants and self.loaded_cog(cog):
print(f"Loaded cog {cog}")
except yaml.YAMLError as exc:
print(exc)
def loaded_cog(self, module):
if os.path.isfile(f"/cogs/{self.modules[module]}.py"):
self.client.load_extension(f"cogs.{self.modules[module]}")
return True
return False

View File

@@ -1,6 +1,5 @@
import discord
from discord.ext import commands
from data import constants
import asyncio
import threading
import random
@@ -8,14 +7,13 @@ from functions.timer import Timer
from data.DatabaseConnection import *
from functions import checks
class QuizQuestions(commands.Cog):
def __init__(self, client):
self.client = client
@commands.group(name="questions", case_insensitive=True, invoke_without_command=True)
@commands.group(name="questions",case_insensitive=True, invoke_without_command=True)
@commands.check(checks.isModPlus)
# /q&a add "What is ...." "answer"
# /q&a add "What is ...." "Australia"
async def questions(self, ctx, *args):
pass
@@ -27,14 +25,14 @@ class QuizQuestions(commands.Cog):
q_id = quizdb.add_question(q, a, reward)
embed = discord.Embed()
embed.colour = discord.Colour.green()
embed.add_field(
name="Success", value=f"Added question with {q_id}", inline=False)
embed.add_field(name="Success", value=f"Added question with {q_id}", inline=False)
await ctx.send(embed=embed)
except:
await ctx.send("Something went wrong")
finally:
quizdb.close()
@questions.command(name="rm")
@commands.check(checks.isModPlus)
async def rm_question(self, ctx, id):
@@ -43,8 +41,7 @@ class QuizQuestions(commands.Cog):
quizdb.rm_question(id)
embed = discord.Embed()
embed.colour = discord.Colour.green()
embed.add_field(
name="Success", value=f"Question removed with id {id}", inline=False)
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))
@@ -62,8 +59,7 @@ class QuizQuestions(commands.Cog):
if len(questions) == 0:
embed = discord.Embed()
embed.colour = discord.Colour.red()
embed.add_field(name="Questions",
value=f"No questions found", inline=False)
embed.add_field(name="Questions", value=f"No questions found", inline=False)
await ctx.send(embed=embed)
else:
@@ -71,15 +67,16 @@ class QuizQuestions(commands.Cog):
embed.set_author(name="Questions")
embed.colour = discord.Colour.orange()
for q in questions:
embed.add_field(
name=f"id: {q[0]}", value=f"Question: '{q[1]}'\nAnswer: '{q[2]}'\nReward: {q[3]}\nUsed: {q[4]}", inline=False)
embed.add_field(name=f"id: {q[0]}", value=f"Question: '{q[1]}'\nAnswer: '{q[2]}'\nReward: {q[3]}\nUsed: {q[4]}", inline=False)
await ctx.send(embed=embed)
except:
await ctx.send("Something went wrong")
finally:
quizdb.close()
@commands.group(name="wordgame", case_insensitive=True, invoke_without_command=True)
@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):
@@ -93,14 +90,14 @@ class QuizQuestions(commands.Cog):
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)
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):
@@ -109,8 +106,7 @@ class QuizQuestions(commands.Cog):
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)
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))
@@ -128,8 +124,7 @@ class QuizQuestions(commands.Cog):
if len(words) == 0:
embed = discord.Embed()
embed.colour = discord.Colour.red()
embed.add_field(
name="Words", value=f"No words found", inline=False)
embed.add_field(name="Words", value=f"No words found", inline=False)
await ctx.send(embed=embed)
else:
@@ -137,24 +132,22 @@ class QuizQuestions(commands.Cog):
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)
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 = (1, 4)
self.interval = (5*60, 20*60)
self.auto = False
self.timeout = 10*60
self.quiz_config = self.client.config["quiz"]
self.interval = (int(self.quiz_config["interval_start"]) * 60, int(self.quiz_config["interval_end"]) * 60)
self.timeout = int(self.quiz_config["timeout"])*60
@commands.group(name="quiz", case_insensitive=True, invoke_without_command=True)
@commands.group(name="quiz",case_insensitive=True, invoke_without_command=True)
@commands.check(checks.isModPlus)
async def quiz(self, ctx, f, *args):
pass
@@ -170,6 +163,7 @@ class Quiz(commands.Cog):
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]))
@@ -191,38 +185,29 @@ 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} x streak in game", inline=False)
embed.add_field(
name="End:", value=f"The quiz will end in 10 minutes!", 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, streak=-1, author=None, linked=False, correct=False):
embed = discord.Embed()
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} in game", inline=False)
embed.add_field(name="Answer:", value=f"{answer}", inline=False)
if correct:
embed.colour = discord.Colour.green()
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="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)
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", 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", inline=False)
if streak > 1:
embed.add_field(
name="Streak:", value=f"{author.mention} has a streak going of {streak}", inline=False)
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
@@ -231,7 +216,7 @@ class Quiz(commands.Cog):
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)
channel = self.client.get_channel(self.quiz_config["channel"])
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:
@@ -251,7 +236,7 @@ class Quiz(commands.Cog):
async def ask_question(self):
question = self.get_random_question()
self.increment_asked_count(question[0])
channel = self.client.get_channel(constants.QuizChannelID)
channel = self.client.get_channel(self.quiz_config["channel"])
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)
@@ -268,7 +253,7 @@ class Quiz(commands.Cog):
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)
channel = self.client.get_channel(self.quiz_config["channel"])
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:
@@ -284,6 +269,7 @@ class Quiz(commands.Cog):
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)
@@ -324,8 +310,7 @@ class Quiz(commands.Cog):
quiz_players_db.reset_streak(previousstreak["discordid"])
if previousstreak is not None and str(previousstreak["discordid"]) == str(discordid):
quiz_players_db.player_won(
discordid, reward * (previousstreak["cur_streak"] + 1))
quiz_players_db.player_won(discordid, reward * (previousstreak["cur_streak"] + 1))
else:
quiz_players_db.player_won(discordid, reward)

12
config.yaml Normal file
View File

@@ -0,0 +1,12 @@
quiz:
channel: 779084465426399272
# question interval between questions in minutes
interval_start: 1
interval_end: 1
# timeout for answer in minutes
timeout: 10
streaks: False
# test channel
token: "Nzc4NjQ0MjMxNDI1MDk3NzQx.X7U-8w.TOqNKPWQkNSIRByTRcgkjaZqbUE"
#token: NzYwNTI5NDY2MDI3MDE2MjUy.X3NYQg.Nz3bwxgltlayMStfT7F-OCbx9pE

View File

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

1
test.py Normal file
View File

@@ -0,0 +1 @@
from tests.quiz_test import *

17
tests/quiz_test.py Normal file
View File

@@ -0,0 +1,17 @@
from bots.discordbot import DiscordBot
import discord.ext.test as dpytest
import pytest
@pytest.mark.asyncio
async def test_bot():
bot = DiscordBot("config.yaml")
# Load any extensions/cogs you want to in here
dpytest.configure(bot.get_client())
config = dpytest.get_config()
channel = config.channels[0]
user = dpytest.backend.make_user("test", 1, 1)
member = dpytest.backend.make_member(user, config.guilds[0])
guild = config.guilds[0]
await dpytest.message("hallo", channel, member)
dpytest.verify_message("[Expected help output]")