Added Bump

This commit is contained in:
Nemika
2021-03-08 12:03:35 +02:00
parent ea36e57272
commit 4712fdb127
5 changed files with 121 additions and 5 deletions

99
cogs/bump.py Normal file
View File

@@ -0,0 +1,99 @@
import discord, io, traceback, json, os
from colorama import Fore, Style, init
init(autoreset=True)
from core.database import Servers
from core.files import Data
from core.embeds import Embeds
commands = discord.ext.commands
settings = Data("settings").json_read()
class Bumps(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.config = Data("config").yaml_read()
@commands.guild_only()
@commands.cooldown(1, settings['cooldown'], commands.BucketType.guild)
@commands.command()
async def bump(self, ctx):
server = Servers(ctx.guild.id)
if not server.get():
ctx.command.reset_cooldown(ctx)
return await ctx.send(embed=Embeds(f"You must setup this server first! Use `{self.config['prefix']}setup` to do so!"))
servers = Servers().get_all()
success, fail = 0, 0
for entry in servers:
try:
server = self.bot.get_guild(entry['_id'])
webhook = await self.bot.fetch_webhook(entry['webhook'])
invite_channel = self.bot.get_channel(entry['invite'])
invite = await invite_channel.create_invite(max_uses=0, max_age=0, unique=False)
embed = discord.Embed(
title=server.name,
description=entry['description'],
color=discord.Color(value=entry['color']),
url=invite.url
)
embed.add_field(name="🌍 Members", value=len(server.members))
embed.add_field(name="🤣 Emojis", value=f"{len(server.emojis)}/{server.emoji_limit}")
embed.add_field(name="💎 Boost Tier", value=f"Tier {server.premium_tier} ({server.premium_subscription_count} Boosts)")
embed.add_field(name="👑 Owner", value=str(server.owner))
embed.add_field(name="🔗 Invite", value=f"[Click to join!]({invite.url})")
embed.set_thumbnail(url=server.icon_url_as(static_format="png"))
embed.set_footer(text=f"Powered by • {self.config['bot_name']}")
await webhook.send(
username=self.config['bot_name'],
avatar_url=self.bot.user.avatar_url,
embed=embed
)
success += 1
except Exception as e:
error = f"{e.__class__.__name__}"
value = io.StringIO().getvalue()
print(f"{Fore.RED}[ERROR] {Style.RESET_ALL}{error}\n{Fore.YELLOW}Error was recorded in {Fore.RED}error.log")
#with open("error.log", "w+") as f:
#f.write(f"{value}{traceback.format_exc()}")
"""
with open("cache_data.json", "w+") as f:
json.dump(entry, f, indent=4)
"""
Servers(entry['_id']).delete()
try:
await self.bot.get_guild(entry['_id']).owner.send(embed=discord.Embed(
title="⚠️ Server Removed ⚠️",
description="Your server was removed from the database because it caused an error! Make sure I have permission to `Manage Webhooks` and `Create Instant Invites`! I've attached your server info below.",
color=discord.Color.red()
))
except: pass
fail += 1
#os.remove("cache_data.json")
return await ctx.send(embed=discord.Embed(
title="⏫ Server Bumped",
description=f"Your server was bumped to `{success+fail}` servers!\n✅ There were `{success}` successful bumps!\n❎ There were `{fail}` failed ones, they got booted from the Database!",
color=discord.Color.green()
)
.set_footer(text=f"Powered by • {self.config['bot_name']}"))
def setup(bot):
bot.add_cog(Bumps(bot))

View File

@@ -1,4 +1,6 @@
import discord import discord
from humanfriendly import format_timespan as ftime
from core import embeds from core import embeds
commands = discord.ext.commands commands = discord.ext.commands
@@ -17,7 +19,7 @@ class ErrorHandler(commands.Cog):
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
return await ctx.send(embed=embeds.Embeds(f"**You are on cooldown!** You can use this command again in **{seconds} seconds**.").error()) return await ctx.send(embed=embeds.Embeds(f"**You are on cooldown!** You can use this command again in **{ftime(seconds)}**.").error())
else: else:
await ctx.send(embed=embeds.Embeds("There was an error executing this command.").error(Error=error)) await ctx.send(embed=embeds.Embeds("There was an error executing this command.").error(Error=error))
raise error raise error

View File

@@ -94,7 +94,7 @@ class BumpSetup(commands.Cog):
webhook = await listing.create_webhook(name=self.config['bot_name']) webhook = await listing.create_webhook(name=self.config['bot_name'])
Servers(ctx.guild.id).add(webhook=webhook.id, listing=listing.id, color=color, description=description) Servers(ctx.guild.id).add(webhook=webhook.id, invite=invite.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.")
@@ -152,9 +152,19 @@ class BumpSetup(commands.Cog):
check=lambda r,u: r.emoji == "♻️" and r.message.id == del_message.id and u.id == ctx.author.id check=lambda r,u: r.emoji == "♻️" and r.message.id == del_message.id and u.id == ctx.author.id
) )
except asyncio.TimeoutError: except asyncio.TimeoutError:
try:
wh = await self.bot.fetch_webhook(cache_data['webhook'])
await wh.delete()
except:
pass
return await del_message.remove_reaction("♻️", self.bot.user) return await del_message.remove_reaction("♻️", self.bot.user)
if Servers(ctx.guild.id).get(): if Servers(ctx.guild.id).get():
try:
wh = await self.bot.fetch_webhook(cache_data['webhook'])
await wh.delete()
except:
pass
return await ctx.send(embed=discord.Embed( return await ctx.send(embed=discord.Embed(
title="❎ Restore Failed", title="❎ Restore Failed",
description="The server seems to have been setup from the beginning, therefore restore is not possible.", description="The server seems to have been setup from the beginning, therefore restore is not possible.",

3
data/settings.json Normal file
View File

@@ -0,0 +1,3 @@
{
"cooldown": 30
}

View File

@@ -13,7 +13,9 @@ 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()) intents = discord.Intents.default(); intents.members = True
bot = commands.Bot(command_prefix=config["prefix"], case_insensitive=True, help_command=None, intents=intents)
@bot.event @bot.event
async def on_ready(): async def on_ready():
@@ -106,7 +108,7 @@ for file in [i for i in os.listdir("cogs") if i.endswith(".py")]:
bot.load_extension(f"cogs.{file[:-3]}") bot.load_extension(f"cogs.{file[:-3]}")
print(f"{Fore.GREEN}[SUCCESS] {Style.RESET_ALL}Successfully loaded {Fore.YELLOW}{file}") print(f"{Fore.GREEN}[SUCCESS] {Style.RESET_ALL}Successfully loaded {Fore.YELLOW}{file}")
except Exception as e: except Exception as e:
print(f"{Fore.RED}[ERROR] {Style.RESET_ALL}Failed to load {Fore.YELLOW}{file} due to an exception: {Style.DIM}{e}") print(f"{Fore.RED}[ERROR] {Style.RESET_ALL}Failed to load {Fore.YELLOW}{file} {Style.RESET_ALL}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]
@@ -117,6 +119,6 @@ for folder in dirs:
bot.load_extension(f"cogs.{folder}.{file[:-3]}") bot.load_extension(f"cogs.{folder}.{file[:-3]}")
print(f"{Fore.GREEN}[SUCCESS] {Style.RESET_ALL}Successfully loaded {Fore.YELLOW}{file}") print(f"{Fore.GREEN}[SUCCESS] {Style.RESET_ALL}Successfully loaded {Fore.YELLOW}{file}")
except Exception as e: except Exception as e:
print(f"{Fore.RED}[ERROR] {Style.RESET_ALL}Failed to load {Fore.YELLOW}{file} due to an exception: {Style.DIM}{e}") print(f"{Fore.RED}[ERROR] {Style.RESET_ALL}Failed to load {Fore.YELLOW}{file} {Style.RESET_ALL}due to an exception: {Style.DIM}{e}")
bot.run(config["token"]) bot.run(config["token"])