async def post(self, ctx): """ Manually posts guild count using discordlists.py (BotBlock) """ try: result = await self.api.post_count() except Exception as e: try: await ctx.send("Request failed: `{}`".format(e)) return except Exception: s = default.traceback_maker(e, advance=False) print(s) return print(result['success']) await ctx.send( "Successfully manually posted server count ({:,}) to {:,} lists." "\nFailed to post server count to {} lists.".format( self.api.server_count, len(result["success"].keys()), len(result["failure"].keys()))) if len(result['failure']) != 0: for item in result['failure']: await botlist_exception(self, item, result['failure'][item]) await asyncio.sleep(5)
async def on_command_error(self, ctx, err): if isinstance(err, errors.MissingRequiredArgument) or isinstance(err, errors.BadArgument): helper = str(ctx.invoked_subcommand) if ctx.invoked_subcommand else str(ctx.command) await ctx.send_help(helper) elif isinstance(err, errors.CommandInvokeError): error = default.traceback_maker(err.original) if "2000 or fewer" in str(err) and len(ctx.message.clean_content) > 1900: return await ctx.send( f"You attempted to make the command display more than 2,000 characters...\n" f"Both error and command will be ignored." ) await ctx.send(f"There was an error processing the command ;-;\n{error}") elif isinstance(err, errors.CheckFailure): pass elif isinstance(err, errors.MaxConcurrencyReached): await ctx.send(f"You've reached max capacity of command usage at once, please finish the previous one...") elif isinstance(err, errors.CommandOnCooldown): await ctx.send(f"This command is on cooldown... try again in {err.retry_after:.2f} seconds.") elif isinstance(err, errors.CommandNotFound): pass
async def on_command_error(self, ctx, err): if isinstance(err, errors.MissingRequiredArgument) or isinstance(err, errors.BadArgument): helper = str(ctx.invoked_subcommand) if ctx.invoked_subcommand else str(ctx.command) await ctx.send_help(helper) elif isinstance(err, errors.CommandInvokeError): error = default.traceback_maker(err.original) if "2000 or fewer" in str(err) and len(ctx.message.clean_content) > 1900: return await ctx.send( "You attempted to make the command display more than 2,000 characters...\n" "Both error and command will be ignored." ) embed=discord.Embed(color=0xf04747) embed.set_author(name="An Exception Occured", icon_url="https://media.discordapp.net/attachments/764915659002871858/769763505318395914/impact-discord.png") embed.add_field(name="The Impact Discord bot has faced a critical error and could not process your command.", value=error, inline=False) await ctx.send(embed=embed) elif isinstance(err, errors.CheckFailure): pass elif isinstance(err, errors.MaxConcurrencyReached): await ctx.send("You've reached max capacity of command usage at once, please finish the previous one...") elif isinstance(err, errors.CommandOnCooldown): await ctx.send(f"This command is on cooldown... try again in {err.retry_after:.2f} seconds.") elif isinstance(err, errors.CommandNotFound): pass
async def reload_cogs(self, ctx, name: str): """ 重新載入 cogs 擴展功能。 """ try: self.bot.reload_extension(f"cogs.{name}") except Exception as e: return await ctx.send(default.traceback_maker(e)) await ctx.send(f"窩成功ㄉ重新載入了 **{name}.py** 哦汪 (`・ω・´)。")
async def on_command_error(self, ctx, err): if isinstance(err, errors.MissingRequiredArgument) or isinstance( err, errors.BadArgument): helper = str( ctx.invoked_subcommand) if ctx.invoked_subcommand else str( ctx.command) await ctx.send_help(helper) elif isinstance(err, errors.CommandInvokeError): error = default.traceback_maker(err.original) await ctx.send( f"There was an error processing the command ;-;\n{error}") elif isinstance(err, errors.MaxConcurrencyReached): await ctx.send( f"You've reached max capacity of command usage at once, please finish the previous one..." ) elif isinstance(err, errors.CheckFailure): pass elif isinstance(err, errors.CommandOnCooldown): await ctx.send( f"This command is on cooldown... try again in {err.retry_after:.2f} seconds." ) elif isinstance(err, errors.CommandNotFound): pass
async def reload(self, ctx, name: str): """ Reloads an extension. """ try: self.bot.reload_extension(f"cogs.{name}") except Exception as e: return await ctx.send(default.traceback_maker(e)) await ctx.send(f"Reloaded extension **{name}.py**")
async def about(self, ctx): """ About the bot """ try: avg_members = sum(g.member_count for g in self.bot.guilds) embed_color = discord.Embed.Empty if hasattr(ctx, 'guild') and ctx.guild is not None: embed_color = ctx.me.top_role.color embed = discord.Embed(title=f"About {ctx.bot.user.name}", color=embed_color) embed.set_thumbnail(url=ctx.bot.user.avatar) embed.add_field( name=f"Developer{'' if len(self.config.owners) == 1 else 's'}", value=',\n'.join([ str(await self.bot.fetch_user(x)) for x in self.config.owners ])) embed.add_field( name="Servers", value=f"{len(ctx.bot.guilds)} (serving {avg_members} members)") await ctx.send(content=f"", embed=embed) except Exception as e: await ctx.send(default.traceback_maker(e))
async def on_command_error(self, ctx, err): if isinstance(err, errors.MissingRequiredArgument) or isinstance(err, errors.BadArgument): helper = str(ctx.invoked_subcommand) if ctx.invoked_subcommand else str(ctx.command) await ctx.send_help(helper) elif isinstance(err, errors.CommandInvokeError): error = default.traceback_maker(err.original) if "Unauthorized" in str(err) and len(ctx.message.clean_content): return await ctx.send( f"the error was over 2000 characters, or the error leaked a token.\n" f"error will not be displayed." ) await print(f"cyka blyat! there was an error.\n{error}") elif isinstance(err, errors.CheckFailure): pass elif isinstance(err, errors.MaxConcurrencyReached): await ctx.send(f"cyka blyat! you're being ratelimited due to your command usage at a time, please finish the previous one.") elif isinstance(err, errors.CommandOnCooldown): await ctx.send(f"cyka blyat! this command is on cooldown. try again in {err.retry_after:.2f} seconds.") elif isinstance(err, errors.CommandNotFound): pass
async def on_command_error(self, ctx, err): if isinstance(err, errors.CommandInvokeError): error = default.traceback_maker(err.original) if "2000 or fewer" in str(err) and len( ctx.message.clean_content) > 1900: return await ctx.send( f"You attempted to make the command display more than 2,000 characters...\n" f"Both error and command will be ignored.") await ctx.send( f"oops. big oops.\n{error}\nthis shouldn't happen. do `poo support` so we can help..." ) elif isinstance(err, errors.CheckFailure): pass # elif isinstance(err, errors.MaxConcurrencyReached): # await ctx.send(f"you're using too many commands at once, finish the last one wtf.") elif isinstance(err, errors.CommandOnCooldown): await ctx.send( f"you're on cooldown. try again in {err.retry_after:.2f} seconds." ) elif isinstance(err, errors.CommandNotFound): pass
async def unload(self, ctx, name: str): """Unload any extension""" try: self.bot.unload_extension(f"cogs.{name}") except Exception as e: return await ctx.send(default.traceback_maker(e)) await ctx.send(f"{emote.check} | Unloaded extension **{name}**")
async def reloadutils(self, ctx, name: str): """ Reloads a utils module. """ name_maker = f"utils/{name}.py" try: module_name = importlib.import_module(f"utils.{name}") importlib.reload(module_name) except ModuleNotFoundError: return await ctx.send(f"Couldn't find module named **{name_maker}**") except Exception as e: error = default.traceback_maker(e) return await ctx.send(f"Module **{name_maker}** returned error and was not reloaded...\n{error}") await ctx.send(f"Reloaded module **{name_maker}**")
async def reload_utils(self, ctx, name: str): """ 重新載入 utils 模組。 """ name_maker = f"utils/{name}.py" try: module_name = importlib.import_module(f"utils.{name}") importlib.reload(module_name) except ModuleNotFoundError: return await ctx.send(f"汪嗚 ... 窩找不到 **{name_maker}** 這個東西呐汪 。・゚・(つд`゚)・゚・。") except Exception as e: error = default.traceback_maker(e) return await ctx.send(f"汪嗚 ... 載入模組 **{name_maker}** 的時候,好像怪怪的吶 。・゚・(つд`゚)・゚・ 有怪怪的東西窩看不懂\n{error}") await ctx.send(f"窩已經成功重新載入 **{name_maker}** 哦汪 (`・ω・´)。")
async def temp_ban(self): for guild, user, mod, reason, timed, ban in self.bot.temp_bans: now = datetime.utcnow() seconds = (timed - now).total_seconds() if timed and seconds <= 0: try: g = self.bot.get_guild(guild) mm = g.get_member(mod) reasons = "Auto unmute" try: await g.unban( discord.Object(user), reason=f"Auto unban. Previously banned by: {mm}") except Exception as e: print(traceback_maker(e)) pass except Exception as e: print(traceback_maker(e)) pass await self.bot.db.execute( "DELETE FROM moddata WHERE user_id = $1 AND guild_id = $2 AND type = $3", user, guild, ban) self.bot.temp_bans.remove( (guild, user, mod, reason, timed, ban))
async def reloadall(self, ctx): error_collection = [] for file in os.listdir("cogs"): if file.endswith(".py"): name = file[:-3] try: self.bot.reload_extension(f"cogs.{name}") except Exception as e: error_collection.append( [file, default.traceback_maker(e, advance=False)]) if error_collection: output = "\n".join( [f"**{g[0]}** ```diff\n- {g[1]}```" for g in error_collection]) return await ctx.send(output) await ctx.send("Successfully reloaded all extensions")
async def sync(self, ctx): await ctx.trigger_typing() proc = await asyncio.create_subprocess_shell( "git pull", stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE) stdout, stderr = await proc.communicate() if stdout: shell = f'[stdout]\n{stdout.decode()}' if stderr: shell = f'[stderr]\n{stderr.decode()}' embed = discord.Embed( title="Pulling from GitHub", description= f"```\nppotatoo@36vp:~/SYSTEM32$ git pull\n{shell}\n```", color=self.bot.embed_color, timestamp=ctx.message.created_at).set_footer( text=f"Requested by {ctx.author}", icon_url=ctx.author.avatar_url) error_collection = [] for file in os.listdir("cogs"): if file.endswith(".py"): name = file[:-3] try: self.bot.reload_extension(f"cogs.{name}") except Exception as e: error_collection.append( [file, traceback_maker(e, advance=False)]) if error_collection: output = "\n".join(f"**{g[0]}** ```diff\n- {g[1]}```" for g in error_collection) embed.add_field( name='Cog Reloading', value=f"Attempted to reload all extensions, was able to reload, " f"however the following failed...\n\n{output}") else: embed.add_field(name='Cog Reloading', value='```\nAll cogs were loaded successfully```') await ctx.send(embed=embed)
async def reload_all_cogs(self, ctx): """ 重新載入所有的 cogs 擴展功能。 """ error_collection = [] for file in os.listdir("cogs"): if file.endswith(".py"): name = file[:-3] try: self.bot.reload_extension(f"cogs.{name}") except Exception as e: error_collection.append( [file, default.traceback_maker(e, advance=False)]) if error_collection: output = "\n".join( [f"**{g[0]}** ```diff\n- {g[1]}```" for g in error_collection]) return await ctx.send(f"汪嗚 ... 窩嘗試重新載入所有擴展功能,能夠重新載入這些咚咚 " f"但是有些咚咚失敗惹嗚 ... 。・゚・(つд`゚)・゚・。\n\n{output}") await ctx.send(f"窩已經成功重新載入所~有的 cogs 哦汪 (`・ω・´)。")
async def reloadall(self, ctx): """ Reloads all extensions. """ error_collection = [] for file in os.listdir("cogs"): if file.endswith(".py"): name = file[:-3] try: self.bot.reload_extension(f"cogs.{name}") except Exception as e: error_collection.append( [file, default.traceback_maker(e, advance=False)]) if error_collection: output = "\n".join( [f"**{g[0]}** ```diff\n- {g[1]}```" for g in error_collection]) return await ctx.send( f"Attempted to reload all extensions, was able to reload, " f"however the following failed...\n\n{output}") await ctx.send("Successfully reloaded all extensions")
async def on_command_error(self, ctx, error): # This prevents any commands with local handlers being handled here in on_command_error. if hasattr(ctx.command, 'on_error'): return # This prevents any cogs with an overwritten cog_command_error being handled here. cog = ctx.cog if cog: if cog._get_overridden_method(cog.cog_command_error) is not None: return ignored = (commands.CommandNotFound, ) #if you want to not send error messages #ignored = () # Allows us to check for original exceptions raised and sent to CommandInvokeError. # If nothing is found. We keep the exception passed to on_command_error. error = getattr(error, 'original', error) # Anything in ignored will return and prevent anything happening. if isinstance(error, ignored): return if isinstance(error, commands.CommandNotFound): #await qembed.send(ctx, f'`{ctx.command}` was not found.') pass elif isinstance(error, commands.CheckFailure): return await qembed.send( ctx, f'You do not have the correct permissions for `{ctx.command}`') if isinstance(error, discord.Forbidden): return await qembed.send( ctx, f'I do not have the correct permissions for `{ctx.command}`') elif isinstance(error, commands.CommandOnCooldown): return await qembed.send( ctx, f"This command is on cooldown.\nTry again in {humanize.precisedelta(error.retry_after, minimum_unit='seconds')}" ) elif isinstance(error, commands.NoPrivateMessage): try: e = discord.Embed( description= f'`{ctx.command}` can not be used in Private Messages.', color=self.bot.embed_color) return await ctx.author.send(embed=e) except discord.HTTPException: pass elif isinstance(error, commands.MissingRequiredArgument): return await qembed.send(ctx, f'{error}') elif isinstance(error, commands.DisabledCommand): return await qembed.send(ctx, f'`{ctx.command}` has been disabled.') # For this error example we check to see where it came from... elif isinstance(error, commands.BadArgument): if ctx.command.qualified_name == 'tag list': # Check if the command being invoked is 'tag list' return await qembed.send( ctx, 'I could not find that member. Please try again.') else: # All other Errors not returned come here. And we can just print the default TraceBack. print('Ignoring exception in command {}:'.format(ctx.command), file=sys.stderr) traceback.print_exception(type(error), error, error.__traceback__, file=sys.stderr) error_collection = [] error_collection.append( [default.traceback_maker(error, advance=False)]) output = "\n".join( [f"```diff\n- {g[0]}```" for g in error_collection]) await qembed.send(ctx, f"{output}\n¯\_(ツ)_/¯")
async def send_bot_help(self, mapping): """ See bot help """ Moksej = self.context.bot.get_user(345457928972533773) support = self.context.bot.support invite = self.context.bot.invite if self.context.guild is not None: p = await self.context.bot.db.fetchval( "SELECT prefix FROM guilds WHERE guild_id = $1", self.context.guild.id) prefix = f"**Prefix:** `{p}`" elif self.context.guild is None: prefix = "**Prefix:** `!`" s = "Support" i = "Bot invite" dbl = "[top.gg](https://top.gg/bot/667117267405766696/vote)" boats = "[discord.boats](https://discord.boats/bot/667117267405766696/vote)" privacy = "[Privacy Policy](https://github.com/TheMoksej/Dredd/blob/master/PrivacyPolicy.md)" emb = discord.Embed(color=self.color['embed_color']) emb.description = f"{emotes.social_discord} [{s}]({support}) | {emotes.pfp_normal} [{i}]({invite}) | {emotes.boats} {boats} | {emotes.discord_privacy} {privacy}\n\n**Made by:** {Moksej}\n{prefix}\n" def check(r, u): return u.id == self.context.author.id and r.message.id == msg.id exts = [] to_react = [] for extension in self.context.bot.cogs.values(): if extension.qualified_name in self.ignore_cogs: continue if extension.qualified_name == "Devishaku": continue if extension.qualified_name in self.owner_cogs and not await self.context.bot.is_owner( self.context.author): continue if extension.qualified_name in self.admin_cogs and not await self.context.bot.is_admin( self.context.author): continue if extension.qualified_name in self.vip_cogs and not await self.context.bot.is_booster( self.context.author): continue exts.append( f"{extension.help_icon} **{extension.qualified_name}**") to_react.append(f"{extension.help_icon}") # emb.description += f'\n{exts}' #emb.set_author(name=self.context.bot.user, icon_url=self.context.bot.user.avatar_url) emb.title = f"{self.context.bot.user.name} Help" emb.set_thumbnail(url=self.context.bot.user.avatar_url) updates = await self.context.bot.db.fetchval('SELECT * FROM updates') num = int(len(exts) / 2) emb.add_field(name="\u200b", value="\n".join(exts[:4])) if not await self.context.bot.is_admin(self.context.author): num = 2 if await self.context.bot.is_booster(self.context.author): num = 3 emb.add_field(name="\u200b", value="\n".join(exts[-num:])) # emb.add_field(name="\u200b", value="\u200b", inline=False) emb.add_field(name='\u200b\n📰 **Latest news**', value=f"{updates}", inline=False) emb.set_footer( text= f"- You can type {self.clean_prefix}help <command> to see that command help and {self.clean_prefix}help <category> to see that category commands" ) msg = await self.context.send(embed=emb) try: if self.context.guild: for reaction in to_react: await msg.add_reaction(reaction) await msg.add_reaction('\U000023f9') cog_emojis = { "<:staff:706190137058525235>": 'Staff', "<:automod:701056320673153034>": 'Automod', "<:booster:686251890027266050>": 'Booster', "<:funn:747192603564441680>": 'Fun', "<:tag:686251889586864145>": 'Info', "<:settingss:695707235833085982>": 'Management', "<:etaa:747192603757248544>": 'Misc', "<:bann:747192603640070237>": 'Moderation', "<:owners:691667205082841229>": 'Owner', "\U000023f9": 'Stop' } react, user = await self.context.bot.wait_for('reaction_add', check=check, timeout=300.0) # Thanks @Dutchy#6127 try: if cog_emojis[str(react)]: pass except: return await msg.delete() await self.context.send_help( self.context.bot.get_cog(cog_emojis[str(react)])) except asyncio.TimeoutError: try: await msg.clear_reactions() except: return except Exception as e: try: print(traceback_maker(e)) except: pass pass
async def get_user_avatar(self, ctx): try: await ctx.send(ctx.guild.icon.with_format("png").with_size(2048)) except Exception as e: await ctx.send(default.traceback_maker(err=e))