How to use Cogs - 10 common examples

To help you get started, we’ve selected a few Cogs examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github henry232323 / RPGBot / cogs / pets.py View on Github external
key = key.strip().casefold()
                            value = value.strip()
                            pet["stats"][key] = int(value)
                        else:
                            break
                    except:
                        await ctx.send(await _(ctx, "Invalid formatting! Try again"))
                        count += 1
                        if count >= 3:
                            await ctx.send(await _(ctx, "Too many failed attempts, cancelling!"))
                            return
                        continue
                    continue

            pet["meta"] = dict()
            await ctx.send(await _(ctx, "Any additional data? (Format like the above, for example "
                                        "nature: hasty, color: brown)"))
            count = 0
            while True:
                response = await self.bot.wait_for("message", check=check, timeout=120)
                if response.content.lower() == "cancel":
                    await ctx.send(await _(ctx, "Cancelling!"))
                    return
                elif response.content.lower() == "skip":
                    await ctx.send(await _(ctx, "Skipping!"))
                    break
                else:
                    try:
                        if "\n" in response.content:
                            res = response.content.split("\n")
                        else:
                            res = response.content.split(",")
github henry232323 / RPGBot / cogs / settings.py View on Github external
async def loadstarwarsshop(self, ctx):
        """This command will pre-load all Star Wars items and make them available in shop
        Requires Bot Moderator or Bot Admin"""
        items = {}
        for item, value in self.bot.switems.items():
            try:
                items[item] = dict(buy=int("".join(filter(str.isdigit, value["meta"]["Cost"].split(" ")[0]))), sell=0, level=0)
            except:
                continue

        await self.bot.di.add_shop_items(ctx.guild, items)
        await ctx.send(await _(ctx, "Successfully added all Star Wars items to shop!"))
github henry232323 / RPGBot / cogs / map.py View on Github external
return
            elif level < 1:
                await ctx.send(
                    await _(ctx, "Only Patrons may make more than 3 maps! See https://www.patreon.com/henry232323"))
                return

        await ctx.send(await _(ctx,
                               "What available tiles will there be? Say `done` when done. Use the * tile to describe all tiles "
                               "when adding what will spawn. One at a time send the name of the tile. i.e. grassland"))

        generators = []
        spawners = {}

        check = lambda x: x.channel.id == ctx.channel.id and x.author.id == ctx.author.id
        while True:
            await ctx.send(await _(ctx, "What kind of tile is it? Say `done` when done"))
            msg = await self.bot.wait_for("message", check=check, timeout=60)
            tile = msg.content.strip()
            if tile == "done":
                break
            elif tile != "*":
                generators.append(tile)
            await ctx.send(await _(ctx,
                                   "What things might spawn in those tiles? Split terms with commas. (Equal chance of each, repeat a term "
                                   "for greater chance) `skip` to skip"
                                   ))
            msg = await self.bot.wait_for("message", check=check, timeout=60)
            if msg.content.lower() == "skip":
                continue
            spawners[(len(generators) - 1) if tile != "*" else -1] = Counter(x.strip() for x in msg.content.split(","))

        new_map = self.create_map(xsize, ysize, generators, spawners)
github henry232323 / RPGBot / cogs / characters.py View on Github external
return
            elif response.content.lower() == "skip":
                await ctx.send(await _(ctx, "Skipping!"))
                break
            else:
                try:
                    if "\n" in response.content:
                        res = response.content.split("\n")
                    else:
                        res = response.content.split(",")
                    for val in res:
                        key, value = val.split(": ")
                        key = key.strip()
                        value = value.strip()
                        if len(key) + len(value) > 1024:
                            await ctx.send(await _(ctx, "Can't have an attribute longer than 1024 characters!"))
                            return
                        character["meta"][key] = value
                    else:
                        break
                except:
                    await ctx.send(await _(ctx, "Invalid formatting! Try again"))
                    count += 1
                    if count >= 3:
                        await ctx.send(await _(ctx, "Too many failed attempts, cancelling!"))
                        return
                    continue

        character["level"] = character["meta"].pop("level", None)
        if (len(ctx.message.mentions) > 0 and ouser is None) or (len(ctx.message.mentions) > 1 and ouser is not None):
            newname = character["name"].replace("!", "")
            data = await self.bot.db.get_guild_data(ctx.guild)
github CarlGroth / Carl-Bot / cogs / mod.py View on Github external
    @checks.admin_or_permissions(manage_server=True)
    async def add_word(self, ctx, *, to_be_blacklisted: str=None):
        if to_be_blacklisted is None:
            print(ctx)
            await ctx.channel.send("You need to specify a word to blacklist")
            return
        slugified_word = self.do_slugify(to_be_blacklisted)
        self.c.execute('''INSERT OR IGNORE INTO blacklist
                          VALUES (?, ?)''',
                          (ctx.guild.id, slugified_word))
        self.conn.commit()
        try:
            self.blacklist[str(ctx.guild.id)].append(slugified_word)
        except KeyError:
            self.blacklist[str(ctx.guild.id)] = [slugified_word]
        to_be_blacklisted = self.clean_string(to_be_blacklisted)
        await ctx.send(f'Added "{to_be_blacklisted}" to the blacklist')
github CarlGroth / Carl-Bot / cogs / twitch.py View on Github external
    @checks.admin_or_permissions(manage_server=True)
    async def twitch_limit(self, ctx, limit: int=0):
        self.c.execute('''INSERT OR IGNORE INTO twitch_config VALUES (?, ?, ?, ?, ?)''', (ctx.guild.id, 0, 1, 0, 0))
        self.c.execute('''UPDATE twitch_config SET max_ownership = ? WHERE guild_id=?''', (limit, ctx.guild.id))
        self.conn.commit()
        self.c.execute('''SELECT max_ownership FROM twitch_config WHERE guild_id=?''', (ctx.guild.id,))
        howmany = self.c.fetchone()[0]
        if howmany != 0:
            return await ctx.send(f"Users (non-mods) are now limited to {howmany} streams added")
        await ctx.send("Users can now add as many twitch streamers as they want")
github Godavaru / Godavaru / cogs / nsfw.py View on Github external
    @checks.is_nsfw()
    async def rule34(self, ctx, tag: str):
        """Search for an image on rule34!
        Note: To use this command, the channel must be NSFW."""
        try:
            url = 'https://rule34.xxx/index.php?page=dapi&s=post&q=index&json=1&tags=' + tag
            async with self.bot.session.get(url) as resp:
                js = json.loads(await resp.text())
            non_loli = list(filter(lambda x: 'loli' not in x['tags'] and 'shota' not in x['tags'], js))
            if len(non_loli) == 0:
                return await ctx.send(":warning: All results included loli/shota content; this search is invalid.")
            response = non_loli[random.randint(0, len(non_loli) - 1)]
            img = f"https://img.rule34.xxx/images/{response['directory']}/{response['image']}"
            tags = ', '.join(response['tags'].split(' '))
            em = discord.Embed(
                description=f'{"`" + tags + "`" if len(tags) < 5000 else "[Click me for the tags](" + self.bot.post_to_haste(tags)})`',
                colour=0xff0000)
github Rapptz / RoboDanny / cogs / stats.py View on Github external
def filter(self, record):
        return record.name == 'discord.gateway' or 'Shard ID' in record.msg or 'Websocket closed ' in record.msg

    def emit(self, record):
        self.cog.add_record(record)

class Commands(db.Table):
    id = db.PrimaryKeyColumn()

    guild_id = db.Column(db.Integer(big=True), index=True)
    channel_id = db.Column(db.Integer(big=True))
    author_id = db.Column(db.Integer(big=True), index=True)
    used = db.Column(db.Datetime, index=True)
    prefix = db.Column(db.String)
    command = db.Column(db.String, index=True)
    failed = db.Column(db.Boolean, index=True)

_INVITE_REGEX = re.compile(r'(?:https?:\/\/)?discord(?:\.gg|\.com|app\.com\/invite)?\/[A-Za-z0-9]+')

def censor_invite(obj, *, _regex=_INVITE_REGEX):
    return _regex.sub('[censored-invite]', str(obj))

def hex_value(arg):
    return int(arg, base=16)

def object_at(addr):
    for o in gc.get_objects():
        if id(o) == addr:
            return o
    return None

class Stats(commands.Cog):
github Rapptz / RoboDanny / cogs / stats.py View on Github external
class GatewayHandler(logging.Handler):
    def __init__(self, cog):
        self.cog = cog
        super().__init__(logging.INFO)

    def filter(self, record):
        return record.name == 'discord.gateway' or 'Shard ID' in record.msg or 'Websocket closed ' in record.msg

    def emit(self, record):
        self.cog.add_record(record)

class Commands(db.Table):
    id = db.PrimaryKeyColumn()

    guild_id = db.Column(db.Integer(big=True), index=True)
    channel_id = db.Column(db.Integer(big=True))
    author_id = db.Column(db.Integer(big=True), index=True)
    used = db.Column(db.Datetime, index=True)
    prefix = db.Column(db.String)
    command = db.Column(db.String, index=True)
    failed = db.Column(db.Boolean, index=True)

_INVITE_REGEX = re.compile(r'(?:https?:\/\/)?discord(?:\.gg|\.com|app\.com\/invite)?\/[A-Za-z0-9]+')

def censor_invite(obj, *, _regex=_INVITE_REGEX):
    return _regex.sub('[censored-invite]', str(obj))

def hex_value(arg):
    return int(arg, base=16)

def object_at(addr):
    for o in gc.get_objects():
github CarlGroth / Carl-Bot / cogs / mod.py View on Github external
    @checks.admin_or_permissions(manage_server=True)
    async def plonk(self, ctx, user: discord.Member=None, command: str=None, subcommand: str = None):
        if user is None:
            return ctx.send("You need to mention a user to plonk")
        if command is None:
            #global PLONK
            a = self.c.execute(
                'SELECT plonked FROM userconfig WHERE (guild_id=? AND user_id=?)', (ctx.guild.id, user.id))
            a = a.fetchone()
            if a is not None:
                if a[0]:
                    #user is plonked
                    self.c.execute(
                        'UPDATE userconfig SET plonked=? WHERE (guild_id=? AND user_id=?)', (False, ctx.guild.id, user.id))
                    self.conn.commit()
                    return await ctx.send(f"**{user.name}** is no longer banned from using the bot in this server.")
                else: