Example #1
0
async def on_guild_join(bot, guild: Guild):
    if guild.id in Utils.from_config("BLOCKED_GUILDS"):
        await Logging.bot_log(
            bot,
            f"Someone tried adding me to blocked guild {guild.name} ({guild.id})",
            None)
        await guild.leave()
    else:
        bot.missing_guilds.add(guild.id)
        await guild.chunk(cache=True)
        bot.missing_guilds.remove(guild.id)
        DBUtils.insert(db.configs, Schemas.guild_schema(guild))
        await Logging.guild_log(
            bot, f"I was added to a new guild: {guild.name} ({guild.id}).")
Example #2
0
 async def create(self, ctx, trigger: str, *, reply: str = None):
     """create_help"""
     if len(trigger) == 0:
         await ctx.send(Translator.translate(ctx.guild, "no_trigger", _emote="THINK"))
     elif reply is None or reply == "":
         await ctx.send(Translator.translate(ctx.guild, "no_reply", _emote="THINK"))
     elif len(trigger) > 20:
         await ctx.send(Translator.translate(ctx.guild, "trigger_too_long"))
     else:
         trigger = trigger.lower()
         if trigger in ["{}".format(x["cmdId"].split("-")[1]) for x in db.commands.find() if x["cmdId"].split("-")[0] == str(ctx.guild.id)]:
             await ctx.send(Translator.translate(ctx.guild, "command_already_exists"))
         else:
             DBUtils.insert(db.commands, Schemas.command_schema(ctx.guild, trigger, reply, ctx.message.author))
             try:
                 self.command_cache[str(ctx.guild.id)].append({"trigger": trigger, "reply": reply})
             except Exception:
                 self.command_cache[str(ctx.guild.id)] = [{"trigger": trigger, "reply": reply}]
             finally:
                 await ctx.send(Translator.translate(ctx.guild, "command_added", _emote="YES", command=trigger))
Example #3
0
async def fill_cache(bot):
    try:
        while len(bot.missing_guilds) > 0:
            start_time = time.time()
            old = len(bot.missing_guilds)
            while len(bot.missing_guilds) > 0:
                try:
                    tasks = [
                        asyncio.create_task(cache_guild(bot, guild_id))
                        for guild_id in bot.missing_guilds
                    ]
                    await asyncio.wait_for(await asyncio.gather(*tasks), 600)
                except (CancelledError,
                        concurrent.futures._base.CancelledError,
                        asyncio.exceptions.CancelledError):
                    pass
                except concurrent.futures._base.TimeoutError:
                    if old == len(bot.missing_guilds):
                        log.info(
                            "[Caching] Timed out while fetching member chunks."
                        )
                        for t in tasks:
                            t.cancel()
                        await asyncio.sleep(1)
                        continue
                except Exception as e:
                    log.error(f"[Caching] Fetching member info failed: \n{e}")
                else:
                    if old == len(bot.missing_guilds):
                        log.error(
                            "[Caching] Timed out while fetching member chunks."
                        )
                        for t in tasks:
                            t.cancel()
                        continue
            end_time = time.time()
            time_needed = (end_time - start_time)
            log.info("[Caching] Finished fetching members in {}".format(
                time_needed))

            # check for guilds that aren't in the DB for some reason (added during downtime etc)
            log.info("[Caching] Filling up missing guilds")
            for g in bot.guilds:
                if not DBUtils.get(db.configs, "guildId", f"{g.id}", "prefix"):
                    try:
                        DBUtils.insert(db.configs, Schemas.guild_schema(g))
                        log.info(f"[Caching] Filled missing guild: {g}")
                    except Exception as ex:
                        log.error(
                            f"[Caching] Error while trying to fill up missing guild {g}: \n{ex}"
                        )
            log.info("[Caching] Fill-up task completed!")
            end_time2 = time.time()
            t = datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")
            await Logging.bot_log(
                f"``[{t} UTC]`` {SALUTE} Finished building the internal cache in {round(end_time2 - start_time, 2)} seconds"
            )
            bot.initial_fill_complete = True
    except Exception as e:
        await log.error(f"[Caching] Guild fetching failed \n{e}")
    finally:
        bot.loading_task = None
Example #4
0
 async def _update_data(guild_id, lvl_id, user_id):
     if not DBUtils.get(db.levels, "levelId", lvl_id, "xp"):
         DBUtils.insert(db.levels, level_schema(guild_id, user_id))