Skip to content

Commit

Permalink
Oprava bugu s databází, checkup databáze zvýšen z 5 sekund na 1 minut…
Browse files Browse the repository at this point in the history
…u, vylepšen try except ve main.py souboru a updatován kód na python 3.10
  • Loading branch information
TheXer committed Nov 17, 2021
1 parent 168ec10 commit 6cb3299
Show file tree
Hide file tree
Showing 10 changed files with 89 additions and 173 deletions.
136 changes: 77 additions & 59 deletions cogs/event.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,12 @@
import discord
from discord.ext import commands, tasks

from db_folder.mysqlwrapper import MySQLWrapper
from db_folder.sqldatabase import SQLDatabase


class EventSystem(commands.Cog):
"""Class for event system, creating pools and sending a message on exact day"""

def __init__(self, bot):
self.bot = bot
self.caching = set()
Expand All @@ -30,7 +31,7 @@ def __init__(self, bot):
# Caching systém, oproti caching systému ve poll.py se tento vždy smaže pokud je event odeslán a zpracován.
@tasks.loop(minutes=30)
async def cache(self):
with MySQLWrapper() as db:
with SQLDatabase() as db:
query = "SELECT `EventEmbedID` FROM `EventPlanner`"
tuples = db.query(query=query)

Expand All @@ -45,10 +46,11 @@ async def cache(self):
async def before_cache(self):
await self.bot.wait_until_ready()

# Ověřuje databázi jestli něco není starší než dané datum a pak jej pošle.
@tasks.loop(seconds=5.0)
# Ověřuje databázi jestli něco není starší než dané datum a pak jej pošle. Změněno na 1 minutu, něco mi tam shazuje
# connection k databázi
@tasks.loop(minutes=1)
async def send_events(self):
with MySQLWrapper() as db:
with SQLDatabase() as db:

sql = "SELECT * FROM EventPlanner;"
result = db.query(query=sql)
Expand Down Expand Up @@ -115,7 +117,7 @@ async def before_send_events(self):
for table_name in tables:
table_description = tables[table_name]

with MySQLWrapper() as db:
with SQLDatabase() as db:
db.execute(query=table_description, commit=True)

await self.bot.wait_until_ready()
Expand All @@ -133,6 +135,8 @@ async def udalost(self, ctx):

@udalost.command()
async def create(self, ctx, title, description, eventdatetime):
await ctx.message.delete()

try:
datetime_formatted = datetime.datetime.strptime(eventdatetime, '%d.%m.%Y %H:%M')

Expand Down Expand Up @@ -173,7 +177,7 @@ async def create(self, ctx, title, description, eventdatetime):
) VALUES (%s, %s, %s, %s, %s, %s)"""
val = (ctx.guild.id, sent.id, title, description, datetime_formatted, ctx.channel.id)

with MySQLWrapper() as db:
with SQLDatabase() as db:
db.execute(sql, val, commit=True)

self.caching.add(sent.id)
Expand All @@ -186,7 +190,7 @@ async def vypis(self, ctx):
WHERE GuildID = %s
ORDER BY EventDate; """

with MySQLWrapper() as db:
with SQLDatabase() as db:
result = db.query(query=sql, val=(ctx.guild.id,))
embed = discord.Embed(title="Výpis všech událostí", colour=discord.Colour.gold())

Expand All @@ -201,7 +205,7 @@ async def vypis(self, ctx):
# Smaže event z databáze pomocí ID embedu. Přijít na lepší způsob?
@udalost.command(aliases=["delete"])
async def smazat(self, ctx, embed_id: str):
with MySQLWrapper() as db:
with SQLDatabase() as db:
try:
sql = "DELETE FROM EventPlanner WHERE EventEmbedID = %s;"
db.execute(sql, (embed_id,), commit=True)
Expand All @@ -228,39 +232,41 @@ async def on_raw_reaction_add(self, payload: discord.RawReactionActionEvent):
async for user in reaction.users()
if not user.id == self.bot.user.id]

if payload.emoji.name == "✅":
edit = embed.set_field_at(
1,
name="Ano, pojedu:",
value=f"{len(vypis_hlasu)} | {', '.join(vypis_hlasu)}",
inline=False)
await reaction.message.edit(embed=edit)
match payload.emoji.name:
case "✅":
edit = embed.set_field_at(
1,
name="Ano, pojedu:",
value=f"{len(vypis_hlasu)} | {', '.join(vypis_hlasu)}",
inline=False)

sql = """ INSERT INTO `ReactionUsers` (
EventEmbedID,
ReactionUser)
VALUES (%s, %s)
"""
val = (payload.message_id, payload.user_id)
await reaction.message.edit(embed=edit)

with MySQLWrapper() as db:
db.execute(sql, val, commit=True)
sql = """ INSERT INTO `ReactionUsers` (
EventEmbedID,
ReactionUser)
VALUES (%s, %s)"""
val = (payload.message_id, payload.user_id)

if payload.emoji.name == "❌":
edit = embed.set_field_at(
2,
name="Ne, nejedu:",
value=f"{len(vypis_hlasu)} | {', '.join(vypis_hlasu)}", inline=False)
with SQLDatabase() as db:
db.execute(sql, val, commit=True)

await reaction.message.edit(embed=edit)
case "❌":
edit = embed.set_field_at(
2,
name="Ne, nejedu:",
value=f"{len(vypis_hlasu)} | {', '.join(vypis_hlasu)}",
inline=False)

if payload.emoji.name == "❓":
edit = embed.set_field_at(
3,
name="Ještě nevím:",
value=f"{len(vypis_hlasu)} | {', '.join(vypis_hlasu)}", inline=False)
await reaction.message.edit(embed=edit)

await reaction.message.edit(embed=edit)
case "❓":
edit = embed.set_field_at(
3,
name="Ještě nevím:",
value=f"{len(vypis_hlasu)} | {', '.join(vypis_hlasu)}", inline=False)

await reaction.message.edit(embed=edit)

@commands.Cog.listener()
async def on_raw_reaction_remove(self, payload: discord.RawReactionActionEvent):
Expand All @@ -275,29 +281,41 @@ async def on_raw_reaction_remove(self, payload: discord.RawReactionActionEvent):
async for user in reaction.users()
if not user.id == self.bot.user.id]

if payload.emoji.name == "✅":
edit = embed.set_field_at(
1,
name="Ano, pojedu:",
value=f"{len(vypis_hlasu)} | {', '.join(vypis_hlasu)}", inline=False)

await reaction.message.edit(embed=edit)

if payload.emoji.name == "❌":
edit = embed.set_field_at(
2,
name="Ne, nejedu:",
value=f"{len(vypis_hlasu)} | {', '.join(vypis_hlasu)}", inline=False)

await reaction.message.edit(embed=edit)

if payload.emoji.name == "❓":
edit = embed.set_field_at(
3,
name="Ještě nevím:",
value=f"{len(vypis_hlasu)} | {', '.join(vypis_hlasu)}", inline=False)

await reaction.message.edit(embed=edit)
match payload.emoji.name:
case "✅":
edit = embed.set_field_at(
1,
name="Ano, pojedu:",
value=f"{len(vypis_hlasu)} | {', '.join(vypis_hlasu)}",
inline=False)

await reaction.message.edit(embed=edit)

sql = """ INSERT INTO `ReactionUsers` (
EventEmbedID,
ReactionUser)
VALUES (%s, %s)"""
val = (payload.message_id, payload.user_id)

with SQLDatabase() as db:
db.execute(sql, val, commit=True)

case "❌":
edit = embed.set_field_at(
2,
name="Ne, nejedu:",
value=f"{len(vypis_hlasu)} | {', '.join(vypis_hlasu)}",
inline=False)

await reaction.message.edit(embed=edit)

case "❓":
edit = embed.set_field_at(
3,
name="Ještě nevím:",
value=f"{len(vypis_hlasu)} | {', '.join(vypis_hlasu)}", inline=False)

await reaction.message.edit(embed=edit)


def setup(bot):
Expand Down
8 changes: 4 additions & 4 deletions cogs/poll.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import discord
from discord.ext import commands, tasks

from db_folder.mysqlwrapper import MySQLWrapper
from db_folder.sqldatabase import SQLDatabase


class Poll(commands.Cog):
Expand Down Expand Up @@ -85,7 +85,7 @@ async def anketa(self, ctx, question, *answer: str):
for reaction in reactions[:len(answer)]:
await sent.add_reaction(reaction)

with MySQLWrapper() as db:
with SQLDatabase() as db:
sql = "INSERT INTO `Poll`(PollID, DateOfPoll) VALUES (%s, %s)"
val = (sent.id, datetime.datetime.now())

Expand All @@ -104,7 +104,7 @@ async def on_raw_reaction_remove(self, payload: discord.RawReactionActionEvent):
# Caching systém pro databázi, ať discord bot nebombarduje furt databázi a vše udržuje ve své paměti
@tasks.loop(minutes=30)
async def cache(self):
with MySQLWrapper() as db:
with SQLDatabase() as db:
# Query pro to, aby se každý záznam, který je starší než měsíc, smazal
query2 = "DELETE FROM `Poll` WHERE `DateOfPoll` < CURRENT_DATE - 30;"
db.execute(query2, commit=True)
Expand All @@ -122,7 +122,7 @@ async def cache(self):

@cache.before_loop
async def before_cache(self):
with MySQLWrapper() as db:
with SQLDatabase() as db:
query = """
CREATE TABLE IF NOT EXISTS `Poll` (
ID_Row INT NOT NULL AUTO_INCREMENT,
Expand Down
36 changes: 0 additions & 36 deletions cogs/statictics.py

This file was deleted.

65 changes: 0 additions & 65 deletions cogs/utility.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,71 +42,6 @@ async def rozcestnik(self, ctx):
async def ping(self, ctx):
await ctx.send('Odezva je takováhle: {} ms'.format(round(self.bot.latency * 1000)))

# TODO: Vše co je pod tímto vylepšit nebo pořešit lépe!

@commands.command(pass_context=True)
async def vypis(self, ctx):
embed = discord.Embed(title="Výpis všech členů na discordu", timestamp=ctx.message.created_at, color=0xff0000)

embed.add_field(name="Členové",
value=", ".join([x.display_name for x in ctx.message.guild.members if not x.bot]))

embed.set_author(name=ctx.author.display_name, icon_url=ctx.author.avatar_url)
embed.set_footer(text=self.bot.user.name, icon_url=self.bot.user.avatar_url)

await ctx.send(embed=embed)

@commands.command(pass_context=True)
async def userinfo(self, ctx, user: discord.Member):
list_members = ctx.guild.members
if user in list_members:

roles = [role for role in user.roles]

embed = discord.Embed(title="Uživatelské informace", timestamp=ctx.message.created_at,
colour=discord.Color.gold())
embed.set_author(name=user.display_name, icon_url=user.avatar_url)
embed.set_thumbnail(url=user.avatar_url)
embed.set_footer(text="Jáchym", icon_url=self.bot.user.avatar_url)

fields = [
("Jméno", str(user), False),
("ID", user.id, False),
(f"Role ({len(roles) - 1})",
", ".join([str(role) for role in user.roles if role != ctx.guild.default_role]), False),
("Vytvořen účet:", user.created_at.strftime("%d.%m.%Y"), False),
("Připojil se:", user.joined_at.strftime("%d.%m.%Y %H:%M:%S"), False)]

for name, value, inline in fields:
embed.add_field(name=name, value=value, inline=inline)

await ctx.send(embed=embed)

else:
await ctx.send('Musíš někoho pingnout z tohoto serveru!')

@commands.command(pass_context=True)
async def serverinfo(self, ctx):
role_count = len(ctx.guild.roles)
list_of_bots = [bot.mention for bot in ctx.guild.members if bot.bot]
member_count = len([m for m in ctx.guild.members if not m.bot])

embed = discord.Embed(timestamp=ctx.message.created_at, color=ctx.author.color)
embed.add_field(name='Jméno', value=f"{ctx.guild.name}", inline=False)
embed.add_field(name='Hlavní vedoucí', value=f"{ctx.message.guild.owner.display_name} 👑", inline=False)
embed.add_field(name='Vertifikační level', value=str(ctx.guild.verification_level), inline=False)
embed.add_field(name='Nejvyšší role', value=ctx.guild.roles[-2], inline=False)

embed.add_field(name='Celkem rolí', value=str(role_count), inline=False)
embed.add_field(name='Celkem členů beze botů', value=f"{member_count}", inline=False)
embed.add_field(name='Botové:', value=(', '.join(list_of_bots)))
embed.add_field(name='Vytvořeno', value=ctx.guild.created_at.strftime('%d.%m.%Y'), inline=False)
embed.set_thumbnail(url=ctx.guild.icon_url)
embed.set_author(name=ctx.author.display_name, icon_url=ctx.author.avatar_url)
embed.set_footer(text=self.bot.user.name, icon_url=self.bot.user.avatar_url)

await ctx.send(embed=embed)

@commands.command(pass_context=True, aliases=["smazat"])
@has_permissions(administrator=True)
async def clear(self, ctx, limit: int):
Expand Down
2 changes: 1 addition & 1 deletion db_folder/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
from db_folder.mysqlwrapper import MySQLWrapper
from db_folder.sqldatabase import SQLDatabase
2 changes: 1 addition & 1 deletion db_folder/mysqlwrapper.py → db_folder/sqldatabase.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
DATABASE = getenv("DATABASE")


class MySQLWrapper:
class SQLDatabase:
"""
Small wrapper for mysql.connector, so I can use magic with statement. Because readibility counts!
"""
Expand Down
Binary file added fotky/Jáchym.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
2 changes: 1 addition & 1 deletion main.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,6 @@
print(f"{filename[:-3]} has loaded successfully")

except Exception as e:
print(f"{filename[:-3]} load extension error: {e}")
raise e

bot.run(DISCORD_TOKEN)
Loading

0 comments on commit 6cb3299

Please sign in to comment.