def translate(key, location, **kwargs): lid = None if location is not None: if hasattr(location, "guild"): location = location.guild if location is not None and hasattr(location, "id"): lid = location.id else: lid = location if lid is None: lang_key = "en_US" else: lang_key = Configuration.get_var(lid, "GENERAL", "LANG") translated = key if key not in LANGS[lang_key]: if key not in untranlatable: BOT.loop.create_task(tranlator_log('WARNING', f'Untranslatable string detected: {key}\n')) untranlatable.add(key) return key if key not in LANGS["en_US"] else format(LANGS['en_US'][key], kwargs, 'en_US') try: translated = format(LANGS[lang_key][key], kwargs, lang_key) except (KeyError, ValueError, ParseError, VisitationError) as ex: BOT.loop.create_task(tranlator_log('NO', f'Corrupt translation detected!\n**Lang code:** {lang_key}\n**Translation key:** {key}\n```\n{LANGS[lang_key][key]}```')) GearbotLogging.exception("Corrupt translation", ex) if key in LANGS["en_US"].keys(): try: translated = format(LANGS['en_US'][key], kwargs, 'en_US') except (KeyError, ValueError, ParseError, VisitationError) as ex: BOT.loop.create_task(tranlator_log('NO', f'Corrupt English source string detected!\n**Translation key:** {key}\n```\n{LANGS["en_US"][key]}```')) GearbotLogging.exception('Corrupt translation', ex) return translated
async def node_init(generation, resource_version): from database import DatabaseConnector from database.DatabaseConnector import Node await DatabaseConnector.init() hostname = os.uname()[1] GearbotLogging.info( f"GearBot clusternode {hostname} (generation {generation}). Trying to figure out where i fit in" ) existing = await Node.filter(hostname=hostname, generation=generation).get_or_none() if existing is None: count = 0 while count < 100: try: await Node.create(hostname=hostname, generation=generation, resource_version=resource_version, shard=count) return count except Exception as ex: GearbotLogging.exception("did something go wrong?", ex) count += 1 else: return existing.shard
async def on_ready(): if not bot.STARTUP_COMPLETE: await Util.readyBot(bot) Emoji.on_ready(bot) Utils.on_ready(bot) Translator.on_ready(bot) bot.loop.create_task( keepDBalive()) # ping DB every hour so it doesn't run off #shutdown handler for clean exit on linux try: for signame in ('SIGINT', 'SIGTERM'): asyncio.get_event_loop().add_signal_handler( getattr(signal, signame), lambda: asyncio.ensure_future( Utils.cleanExit(bot, signame))) except Exception: pass #doesn't work on windows bot.aiosession = aiohttp.ClientSession() bot.start_time = datetime.datetime.utcnow() GearbotLogging.info("Loading cogs...") for extension in extensions: try: bot.load_extension("Cogs." + extension) except Exception as e: GearbotLogging.exception( f"Failed to load extention {extension}", e) GearbotLogging.info("Cogs loaded") if Configuration.getMasterConfigVar("CROWDIN_KEY") is not None: bot.loop.create_task(translation_task()) bot.STARTUP_COMPLETE = True await bot.change_presence( activity=discord.Activity(type=3, name='the gears turn'))
def translate(key, location, **kwargs): lang_key = "en_US" translated = key if key not in LANGS[lang_key]: if key not in untranlatable: BOT.loop.create_task(tranlator_log('WARNING', f'Untranslatable string detected in {lang_key}: {key}\n')) untranlatable.add(key) return key try: translated = format(LANGS[lang_key][key], kwargs, lang_key) except (KeyError, ValueError, ParseError, VisitationError) as ex: BOT.loop.create_task(tranlator_log('NO', f'Corrupt translation detected!\n**Lang code:** {lang_key}\n**Translation key:** {key}\n```\n{LANGS[lang_key][key]}```')) GearbotLogging.exception("Corrupt translation", ex) return translated
async def on_ready(bot): if not bot.STARTUP_COMPLETE: GearbotLogging.initialize_pump(bot) await GearbotLogging.onReady( bot, Configuration.get_master_var("BOT_LOG_CHANNEL")) info = await bot.application_info() await GearbotLogging.bot_log(message="Spinning up the gears!") await Util.readyBot(bot) Emoji.on_ready(bot) Utils.on_ready(bot) Translator.on_ready(bot) bot.loop.create_task( keepDBalive(bot)) # ping DB every hour so it doesn't run off #shutdown handler for clean exit on linux try: for signame in ('SIGINT', 'SIGTERM'): asyncio.get_event_loop().add_signal_handler( getattr(signal, signame), lambda: asyncio.ensure_future( Utils.cleanExit(bot, signame))) except Exception: pass #doesn't work on windows bot.aiosession = aiohttp.ClientSession() bot.start_time = datetime.datetime.utcnow() GearbotLogging.info("Loading cogs...") for extension in Configuration.get_master_var("COGS"): try: bot.load_extension("Cogs." + extension) except Exception as e: GearbotLogging.exception( f"Failed to load extention {extension}", e) GearbotLogging.info("Cogs loaded") if Configuration.get_master_var("CROWDIN_KEY") is not None: bot.loop.create_task(translation_task(bot)) await DocUtils.update_docs(bot) bot.STARTUP_COMPLETE = True await GearbotLogging.bot_log( message=f"All gears turning at full speed, {info.name} ready to go!" ) await bot.change_presence( activity=discord.Activity(type=3, name='the gears turn')) else: await bot.change_presence( activity=discord.Activity(type=3, name='the gears turn'))
async def on_command_error(bot, ctx: commands.Context, error): if isinstance(error, commands.NoPrivateMessage): await ctx.send("This command cannot be used in private messages.") elif isinstance(error, commands.BotMissingPermissions): GearbotLogging.error( f"Encountered a permission error while executing {ctx.command}.") await ctx.send(error) elif isinstance(error, commands.DisabledCommand): await ctx.send("Sorry. This command is disabled and cannot be used.") elif isinstance(error, commands.CheckFailure): if ctx.command.qualified_name is not "latest" and ctx.guild is not None and Configuration.getConfigVar( ctx.guild.id, "PERM_DENIED_MESSAGE"): await ctx.send( ":lock: You do not have the required permissions to run this command" ) elif isinstance(error, commands.CommandOnCooldown): await ctx.send(error) elif isinstance(error, commands.MissingRequiredArgument): await ctx.send( f"You are missing a required argument! (See {ctx.prefix}help {ctx.command.qualified_name} for info on how to use this command)." ) elif isinstance(error, commands.BadArgument): await ctx.send( f"Invalid argument given! (See {ctx.prefix}help {ctx.command.qualified_name} for info on how to use this commmand)." ) elif isinstance(error, commands.CommandNotFound): return elif isinstance(error, PeeweeException): await handle_database_error(bot) else: bot.errors = bot.errors + 1 # log to logger first just in case botlog logging fails as well GearbotLogging.exception( f"Command execution failed:\n" f" Command: {ctx.command}\n" f" Message: {ctx.message.content}\n" f" Channel: {'Private Message' if isinstance(ctx.channel, abc.PrivateChannel) else ctx.channel.name}\n" f" Sender: {ctx.author.name}#{ctx.author.discriminator}\n" f" Exception: {error}", error.original) # notify caller await ctx.send( ":rotating_light: Something went wrong while executing that command :rotating_light:" ) embed = discord.Embed(colour=discord.Colour(0xff0000), timestamp=datetime.datetime.utcfromtimestamp( time.time())) embed.set_author(name="Command execution failed:") embed.add_field(name="Command", value=ctx.command) embed.add_field(name="Original message", value=Utils.trim_message(ctx.message.content, 1024)) embed.add_field(name="Channel", value='Private Message' if isinstance( ctx.channel, abc.PrivateChannel) else f"{ctx.channel.name} ({ctx.channel.id})") embed.add_field(name="Sender", value=f"{ctx.author.name}#{ctx.author.discriminator}") embed.add_field(name="Exception", value=error.original) v = "" for line in traceback.format_tb(error.original.__traceback__): if len(v) + len(line) > 1024: embed.add_field(name="Stacktrace", value=v) v = "" v = f"{v}\n{line}" if len(v) > 0: embed.add_field(name="Stacktrace", value=v) await GearbotLogging.logToBotlog(embed=embed)