async def embedcolor(self, ctx, color:str): colorint = f"0x{color}" oldembedcolor = config("embedcolor") try: newembedcolor = int(colorint, 16) except ValueError: await ctx.reply("Invalid Color!") return embed = discord.Embed(color=embedcolor, title="Embed Color", description = f"Old color: #{oldembedcolor}\nNew color: #{color}") #Generate image with specified hex hexcolor = f"#{color}" image = Image.new("RGB", (100,100), hexcolor) buffer = BytesIO() image.save(buffer, "png") buffer.seek(0) #Attach image and set thumbnail file = discord.File(fp=buffer, filename="colorimage.png") embed.set_thumbnail(url='attachment://colorimage.png') msg = await ctx.reply(embed=embed, file=file) confirmation = await ConfirmationCheck.confirm(self, ctx, msg) if confirmation: embed = discord.Embed(color=newembedcolor, title="Embed Color Set!", description = f"Old color: #{oldembedcolor}\nNew color: #{color}") embed.set_thumbnail(url='attachment://colorimage.png') await msg.edit(embed=embed) #Update the config file set_config("embedcolor", colorint) #Reload cogs for cog in ctx.bot.coglist: self.bot.reload_extension(cog) elif confirmation is False: embed = discord.Embed(color=embedcolor, title="Embed Color", description = "Embed color unchanged") await msg.edit(embed=embed) elif confirmation is None: await ctx.reply("Confirmation timed out") return
import logging import time, datetime import discord from discord.ext import commands from disputils import BotEmbedPaginator from customfunctions import EmbedMaker from customfunctions import config logger = logging.getLogger("bot.utility") logger.setLevel(logging.INFO) embedcolor = int(config("embedcolor"), 16) class UtilityCog(commands.Cog, name="Utility"): def __init__(self, bot): self.bot = bot @commands.command() async def help(self, ctx): commandsdict = {} for cog in self.bot.cogs.keys(): commandsdict[str(cog)] = {} command_list = self.bot.walk_commands() for cmd in command_list: if (not cmd.hidden) and cmd.enabled: qname = cmd.qualified_name cog = cmd.cog_name commandsdict[str(cog)][str(qname)] = {
async def on_command_error(ctx, error): if hasattr(ctx.command, 'on_error'): return elif isinstance(error, CommandNotFound) or ctx.command.hidden: await ctx.message.add_reaction(str('❔')) return elif isinstance(error, errors.NotOwner): await ctx.message.add_reaction(str('🔏')) return elif isinstance(error, errors.DisabledCommand): await ctx.message.add_reaction( str('<:DisabledCommand:804476191268536320>')) return elif isinstance(error, errors.MissingPermissions): await ctx.message.add_reaction(str('🔐')) return elif isinstance(error, errors.BotMissingPermissions): await ctx.reply("I do not have the requisite permissions") return elif isinstance(error, errors.MissingRole): await ctx.message.add_reaction(str('🔐')) return elif isinstance(error, errors.CommandOnCooldown): await ctx.message.add_reaction(str('<:Cooldown:804477347780493313>')) if str(error.cooldown.type.name) != "default": cooldowntype = f'per {error.cooldown.type.name}' else: cooldowntype = 'global' await ctx.reply( f"This command is on a {round(error.cooldown.per, 0)}s {cooldowntype} cooldown. " f"Wait {round(error.retry_after, 1)} seconds", delete_after=min(10, error.retry_after)) return elif isinstance(error, errors.MissingRequiredArgument): await ctx.reply( f"Missing required argument!\nUsage:`{ctx.command.signature}`", delete_after=30) return elif isinstance(error, errors.BadArgument): await ctx.reply(f"Invalid argument!\nUsage: `{ctx.command.signature}`", delete_after=30) return elif isinstance(error, errors.NoPrivateMessage): await ctx.message.add_reaction( str('<:ServerOnlyCommand:803789780793950268>')) return elif isinstance(error, CustomChecks.IncorrectGuild): await ctx.reply(content="This command does not work in this server.", delete_after=10) return else: # Send user a message error_str = str(error).replace(personal_info, '') await ctx.message.add_reaction('<:CommandError:804193351758381086>') await ctx.reply("Error:\n```" + error_str + "```\nSmallPepperZ will be informed", delete_after=60) # Get traceback info exc = error error_type = type(exc) trace = exc.__traceback__ lines = traceback.format_exception(error_type, exc, trace) traceback_text = ''.join(lines) # Github gist configuration errornum = config("errornum") errornum = int(errornum) + 1 set_config("errornum", str(errornum)) traceback_text = traceback_text.replace(personal_info, '') apiurl = "https://api.github.com/gists" gist_id = config("githubgist") gisttoedit = f'{apiurl}/{gist_id}' githubtoken = config('githubtoken') headers = {'Authorization': 'token %s' % githubtoken} params = {'scope': 'gist'} content = f'Error - {error} \n\n\n {traceback_text}' formatted_error_number = f'{errornum:02d}' payload = { "description": "SachiBot Errors - A gist full of errors for my bot", "public": False, "files": { "SachiBotPyError %s.log" % formatted_error_number: { "content": content } } } # Upload to github gist requests.patch(gisttoedit, headers=headers, params=params, data=json.dumps(payload)) # Build and send embed for error channel channel = bot.get_channel(errorchannel) embed1 = discord.Embed(title=f"Error {formatted_error_number}", color=embedcolor) embed1.add_field(name="Message Url:", value=ctx.message.jump_url, inline='false') embed1.add_field(name="Message:", value=ctx.message.clean_content, inline='true') embed1.add_field(name="Author:", value=ctx.message.author.mention, inline='true') embed1.add_field(name="\u200B", value='\u200B', inline='true') # Check if it was in a guild try: guildname = ctx.guild.name channelname = ctx.channel.name except: guildname = "DM" channelname = ctx.author.id embed1.add_field(name="Guild:", value=guildname, inline='true') embed1.add_field(name="Channel:", value=channelname, inline='true') embed1.add_field(name="\u200B", value='\u200B', inline='true') embed1.add_field(name="Error:", value=f'```{error}```', inline='false') embed1.add_field( name="Traceback:", value=f'Traceback Gist - ' f'[SachiBotPyError {formatted_error_number}.log](https://gist.github.com/SmallPepperZ/{gist_id}#file-sachibotpyerror-{formatted_error_number}-log' f' \"Github Gist #{formatted_error_number}\") ', inline='false') await channel.send(embed=embed1) ghost_ping = await channel.send('<@!545463550802395146>') await ghost_ping.delete()
async def on_ready(): logger.info("Bot initialized") status = config('status') await bot.change_presence(activity=discord.Activity(type=status[0][1], name=status[1]), status=status[2][1])
import discord import requests from discord.enums import Status from discord.ext import commands from discord.ext.commands import CommandNotFound, errors from discord_slash import SlashCommand from customfunctions import config, set_config from customfunctions import CustomChecks # endregion # region Variable Stuff embedcolor = int(config("embedcolor"), 16) token = config('discordtoken') personal_info = config("pathtohide") prefix = config("prefix") start_time_local = time.time() intents = discord.Intents.all() intents.typing = False bot = commands.Bot(command_prefix=prefix, intents=intents, case_insensitive=True) slash = SlashCommand(bot, override_type=True, sync_commands=True)
async def on_resume(self): status = config('status') await self.bot.change_presence(activity=discord.Activity( type=status[0][1], name=status[1]), status=status[2][1])
import json import time import sqlite3 as sl import logging import discord from discord.ext import commands from customfunctions import config #region Variable Stuff embedcolor = int(config("embedcolor"), 16) prefix = config("prefix") db_path = "storage/DiscordMessages.db" dbcon = sl.connect(str(db_path)) logger = logging.getLogger("bot.logging") #endregion with open("storage/loggingignore.json", "r") as loggingignore: ignore_json = loggingignore.read() channelignore = json.loads(ignore_json)["channels"] guildignore = json.loads(ignore_json)["guilds"] class ListenerCog(commands.Cog, name="Logging"): def __init__(self, bot): self.bot = bot @commands.Cog.listener("on_message") async def logmessages(self, message: discord.Message):
import os import inspect import discord from discord.ext import commands from discord.ext.commands.errors import ExtensionNotLoaded, ExtensionFailed from discord.ext.commands import Context from customfunctions import config, master_logger, ErrorHandling embedcolor = config("embedcolor") logger = master_logger.getChild("cogs") class CogsCog(commands.Cog, name="Cogs"): def __init__(self, bot): self.bot: discord.Client = bot @commands.command() @commands.is_owner() async def reload(self, ctx: Context, *cogs_to_reload): def format_cog_name(cog_name: str) -> str: return cog_name.replace('cogs.', '').replace('_', ' ').title().replace('.', '/') cog_text_lines = [] if len(cogs_to_reload) == 0: reload_cogs = [ inspect.getmodule(cog).__name__ for cog in self.bot.cogs.values() ] else:
from datetime import datetime import datetime as dt import json import time import discord from discord.ext import commands from customfunctions import config, DBManager, EmbedMaker, StatusManager from customfunctions import master_logger #region Variable Stuff embedcolor = config("embedcolor") prefix = config("prefix") database = DBManager.Database() messages_database = DBManager.Database("messages") logger = master_logger.getChild("listeners") delete_logger = master_logger.getChild("listeners").getChild("deletions") #endregion def get_logging_channel(bot: discord.Client, channel_name: str, guild: int = None) -> discord.TextChannel: logging_channels = { "joins": lambda: bot.get_guild(797308956162392094).get_thread( database.cursor.execute( "select join_thread from log_threads where guild_id=?", (guild, )).fetchone()[0]), "invites":
async def uncaught_error(ctx, error, bot: discord.Client, silent: bool = False): error_str = str(error).replace(personal_info, '') # Send user a message if not silent: await ctx.message.add_reaction('<:CommandError:804193351758381086>') await ctx.reply( f"Error:\n```{error_str}```\n{bot.owner.name} will be informed", delete_after=60) # Get traceback info lines = traceback.format_exception(type(error), error, error.__traceback__) traceback_text = ''.join(lines) # Github gist configuration errornum = int(config("errornum")) + 1 set_config("errornum", str(errornum)) traceback_text = traceback_text.replace(personal_info, '') apiurl = "https://api.github.com/gists" gist_id = config("githubgist") githubtoken = config('githubtoken') payload = { "description": "SachiBot Errors - A gist full of errors for my bot", "public": False, "files": { f"SachiBotPyError {errornum:02d}.log": { "content": f'Error - {error} \n\n\n {traceback_text}' } } } # Upload to github gist requests.patch(f'{apiurl}/{gist_id}', headers={'Authorization': f'token {githubtoken}'}, params={'scope': 'gist'}, data=json.dumps(payload)) # Build and send embed for error channel channel = bot.get_channel(errorchannel) embed1 = discord.Embed(title=f"Error {errornum:02d}", color=embedcolor) embed1.add_field(name="Message Url:", value=ctx.message.jump_url, inline='false') embed1.add_field(name="Message:", value=ctx.message.clean_content, inline='true') embed1.add_field(name="Author:", value=ctx.message.author.mention, inline='true') embed1.add_field(name="\u200B", value='\u200B', inline='true') # Check if it was in a guild try: guildname = ctx.guild.name channelname = ctx.channel.name except: guildname = "DM" channelname = ctx.author.id embed1.add_field(name="Guild:", value=guildname, inline='true') embed1.add_field(name="Channel:", value=channelname, inline='true') embed1.add_field(name="\u200B", value='\u200B', inline='true') embed1.add_field(name="Error:", value=f'```{error}```', inline='false') embed1.add_field( name="Traceback:", value=f'Traceback Gist - ' f'[SachiBotPyError {errornum:02d}.log](https://gist.github.com/SmallPepperZ/{gist_id}#file-sachibotpyerror-{errornum:02d}-log' f' \"Github Gist #{errornum:02d}\") ', inline='false') await channel.send(embed=embed1) ghost_ping = await channel.send(f'<@!{bot.owner.id}>') await ghost_ping.delete()
import json import traceback import requests from discord.ext import commands import discord from customfunctions import config, set_config errorchannel = int(config("errorchannel")) personal_info = config("pathtohide") embedcolor = config("embedcolor") async def command_on_cooldown(ctx, error): await ctx.message.add_reaction(str('<:Cooldown:804477347780493313>')) if str(error.cooldown.type.name) != "default": cooldowntype = f'per {error.cooldown.type.name}' else: cooldowntype = 'global' await ctx.reply( f"This command is on a {round(error.cooldown.per, 0)}s {cooldowntype} cooldown. " f"Wait {round(error.retry_after, 1)} seconds", delete_after=min(10, error.retry_after)) async def invalid_invocation(ctx, error): #pylint:disable=unused-argument command: commands.Command = ctx.command if command.help is not None: await ctx.reply( f"Missing required argument!\nUsage:`{ctx.command.signature}`\n\nHelp: {command.help}", delete_after=30) else: