Added =delete

This commit is contained in:
Nemika
2021-03-08 10:25:57 +02:00
parent 695bfc3a3f
commit ea36e57272
5 changed files with 90 additions and 14 deletions

View File

@@ -13,7 +13,7 @@ class ErrorHandler(commands.Cog):
return await ctx.send(embed=embeds.Embeds(f"Missing `{error.param}` as a required argument.").error()) return await ctx.send(embed=embeds.Embeds(f"Missing `{error.param}` as a required argument.").error())
elif isinstance(error, commands.CommandNotFound): elif isinstance(error, commands.CommandNotFound):
return return
elif isinstance(error, commands.CheckAnyFailure): elif isinstance(error, commands.CheckFailure):
return await ctx.send(embed=embeds.Embeds("You are not allowed to do this.").error()) return await ctx.send(embed=embeds.Embeds("You are not allowed to do this.").error())
elif isinstance(error, commands.CommandOnCooldown): elif isinstance(error, commands.CommandOnCooldown):
seconds = error.retry_after seconds = error.retry_after

View File

@@ -85,25 +85,97 @@ class BumpSetup(commands.Cog):
'message', 'message',
timeout=120, timeout=120,
check=lambda message: message.author.id == ctx.author.id and len(message.content) and message.channel.id == ctx.channel.id check=lambda message: message.author.id == ctx.author.id and len(message.content) and message.channel.id == ctx.channel.id
)).content, 16) )).content.replace("#", ""), 16)
except asyncio.TimeoutError: except asyncio.TimeoutError:
return await ctx.send(embed=Embeds("Setup canceled, timeout!").error()) return await ctx.send(embed=Embeds("Setup canceled, timeout!").error())
except ValueError: except ValueError:
return await ctx.send(embed=Embeds("Setup canceled, invalid color!").error()) return await ctx.send(embed=Embeds("Setup canceled, invalid color!").error())
webhook = await listing.create_webhook(name=self.config['bot_name'], avatar=self.bot.avatar_url) webhook = await listing.create_webhook(name=self.config['bot_name'])
Servers(ctx.guild.id).add(webhook=webhook.id, listing=listing, color=color, description=description) Servers(ctx.guild.id).add(webhook=webhook.id, listing=listing.id, color=color, description=description)
await ctx.send("Setup complete! Server added to DB and the webhook was created.") await ctx.send("Setup complete! Server added to DB and the webhook was created.")
@commands.guild_only()
@commands.has_permissions(manage_guild=True)
@commands.check(lambda ctx: ctx.guild not in setting_up)
@commands.command()
async def delete(self, ctx):
if not Servers(ctx.guild.id).get():
return await ctx.send(embed=Embeds("The server does not have any data in the Database!").error())
confirmation_message = await ctx.send(embed=discord.Embed(
title="⚠️ Confirmation Required ⚠️",
description=f"**{ctx.author}**, you're about to delete your server from the database! This will remove all data. **Are you sure?**",
color=discord.Color.orange()
))
emojis = ["", ""]
for emoji in emojis: await confirmation_message.add_reaction(emoji)
try:
reaction, user = await self.bot.wait_for(
'reaction_add',
timeout=120,
check=lambda r, u: r.emoji in emojis and r.message.id == confirmation_message.id and u.id == ctx.author.id
)
except asyncio.TimeoutError:
await ctx.send(embed=Embeds("Server deletion canceled due to timeout!").error())
return await confirmation_message.delete()
if reaction.emoji == emojis[1]:
return await ctx.send(embed=Embeds("Server deletion canceled.").error())
db_entry = Servers(ctx.guild.id)
cache_data = db_entry.get()
db_entry.delete()
setting_up.remove(ctx.guild)
del_message = await ctx.send(embed=discord.Embed(
title="🗑️ Server Deleted",
description="The server was deleted from the database! You also can react below within one minute to restore it.",
color=discord.Color.green()
))
await del_message.add_reaction("♻️")
try:
await self.bot.wait_for(
'reaction_add',
timeout=60,
check=lambda r,u: r.emoji == "♻️" and r.message.id == del_message.id and u.id == ctx.author.id
)
except asyncio.TimeoutError:
return await del_message.remove_reaction("♻️", self.bot.user)
if Servers(ctx.guild.id).get():
return await ctx.send(embed=discord.Embed(
title="❎ Restore Failed",
description="The server seems to have been setup from the beginning, therefore restore is not possible.",
color=discord.Color.red()
))
Servers(ctx.guild.id).add(**cache_data)
return await ctx.send(embed=discord.Embed(
title="♻️ Server Restored",
description="Your server was restored, all data are safe and sound.",
color=discord.Color.green()
))
@setup.before_invoke @setup.before_invoke
@delete.before_invoke
async def add_to_setting_up(self, ctx): async def add_to_setting_up(self, ctx):
setting_up.append(ctx.guild) setting_up.append(ctx.guild)
@setup.after_invoke @setup.after_invoke
@setup.error @delete.after_invoke
async def remove_from_setting_up(self, ctx): async def remove_from_setting_up(self, ctx):
try: try:
setting_up.remove(ctx.guild) setting_up.remove(ctx.guild)

View File

@@ -16,11 +16,11 @@ class Servers:
""" """
Add a server to the database. Add a server to the database.
Expected params: Desc, Color, Listing, Invite Expected params: Desc, Color, Listing, WebhookID
""" """
def add(self, **params): def add(self, **params):
kwargs['_id'] = self.server params['_id'] = self.server
self.col.insert_one(params) self.col.insert_one(params)
""" """

View File

@@ -1,5 +1,5 @@
managers: managers:
- 219567539049594880 - your-id
prefix: '=' prefix: '='
token: ODAzNTc1Mzc5MDgzNzg4MzQ4.YA_x5A.l_mTE2ae1UH0wIEAPQk20BCcBzc token: token-here
version: '1.0' version: '1.0'

14
main.py
View File

@@ -5,15 +5,19 @@ from contextlib import redirect_stdout
from core.files import Data from core.files import Data
from core import checks from core import checks
from colorama import init, Style, Fore
from discord.ext import commands from discord.ext import commands
init(autoreset=True)
config = Data("config").yaml_read() config = Data("config").yaml_read()
bot = commands.Bot(command_prefix=config["prefix"], case_insensitive=True, help_command=None, intents=discord.Intents.default()) bot = commands.Bot(command_prefix=config["prefix"], case_insensitive=True, help_command=None, intents=discord.Intents.default())
@bot.event @bot.event
async def on_ready(): async def on_ready():
print("Bot is ready!") print(f"{Fore.CYAN}[READY] {Style.RESET_ALL}Bot initialized!")
@checks.manager() @checks.manager()
@bot.command(aliases=["e"]) @bot.command(aliases=["e"])
@@ -100,9 +104,9 @@ async def _reload(ctx, *, module):
for file in [i for i in os.listdir("cogs") if i.endswith(".py")]: for file in [i for i in os.listdir("cogs") if i.endswith(".py")]:
try: try:
bot.load_extension(f"cogs.{file[:-3]}") bot.load_extension(f"cogs.{file[:-3]}")
print(f"Loaded {file}") print(f"{Fore.GREEN}[SUCCESS] {Style.RESET_ALL}Successfully loaded {Fore.YELLOW}{file}")
except Exception as e: except Exception as e:
print(f"######\nFailed to load {file}: {e}\n######") print(f"{Fore.RED}[ERROR] {Style.RESET_ALL}Failed to load {Fore.YELLOW}{file} due to an exception: {Style.DIM}{e}")
dirs = [i for i in [x for x in os.walk("cogs")][0][1] if i.find(".") == -1] dirs = [i for i in [x for x in os.walk("cogs")][0][1] if i.find(".") == -1]
@@ -111,8 +115,8 @@ for folder in dirs:
for file in [i for i in os.listdir(f"cogs/{folder}") if i.endswith(".py")]: for file in [i for i in os.listdir(f"cogs/{folder}") if i.endswith(".py")]:
try: try:
bot.load_extension(f"cogs.{folder}.{file[:-3]}") bot.load_extension(f"cogs.{folder}.{file[:-3]}")
print(f"Loaded {file}") print(f"{Fore.GREEN}[SUCCESS] {Style.RESET_ALL}Successfully loaded {Fore.YELLOW}{file}")
except Exception as e: except Exception as e:
print(f"######\nFailed to load {folder}.{file}: {e}\n######") print(f"{Fore.RED}[ERROR] {Style.RESET_ALL}Failed to load {Fore.YELLOW}{file} due to an exception: {Style.DIM}{e}")
bot.run(config["token"]) bot.run(config["token"])