How to use the cogs.utils.db function in Cogs

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 Rapptz / RoboDanny / cogs / api.py View on Github external
if role is None:
            return False

        return ctx.author.top_role >= role
    return commands.check(predicate)

class Feeds(db.Table):
    id = db.PrimaryKeyColumn()
    channel_id = db.Column(db.Integer(big=True))
    role_id = db.Column(db.Integer(big=True))
    name = db.Column(db.String)

class RTFM(db.Table):
    id = db.PrimaryKeyColumn()
    user_id = db.Column(db.Integer(big=True), unique=True, index=True)
    count = db.Column(db.Integer, default=1)

class SphinxObjectFileReader:
    # Inspired by Sphinx's InventoryFileReader
    BUFSIZE = 16 * 1024

    def __init__(self, buffer):
        self.stream = io.BytesIO(buffer)

    def readline(self):
        return self.stream.readline().decode('utf-8')

    def skipline(self):
        self.stream.readline()

    def read_compressed_chunks(self):
        decompressor = zlib.decompressobj()
github Rapptz / RoboDanny / cogs / profile.py View on Github external
from discord.ext import commands
from .utils import db
from .utils.formats import plural
from collections import defaultdict

import discord
import re

class Profiles(db.Table):
    # this is the user_id
    id = db.Column(db.Integer(big=True), primary_key=True)
    nnid = db.Column(db.String)
    squad = db.Column(db.String)

    # merger from the ?fc stuff
    fc_3ds = db.Column(db.String)
    fc_switch = db.Column(db.String)

    # extra Splatoon data is stored here
    extra = db.Column(db.JSON, default="'{}'::jsonb", nullable=False)

class DisambiguateMember(commands.IDConverter):
    async def convert(self, ctx, argument):
        # check if it's a user ID or mention
        match = self._get_id_match(argument) or re.match(r'<@!?([0-9]+)>$', argument)
github Rapptz / RoboDanny / cogs / config.py View on Github external
class ChannelOrMember(commands.Converter):
    async def convert(self, ctx, argument):
        try:
            return await commands.TextChannelConverter().convert(ctx, argument)
        except commands.BadArgument:
            return await commands.MemberConverter().convert(ctx, argument)

class Plonks(db.Table):
    id = db.PrimaryKeyColumn()
    guild_id = db.Column(db.Integer(big=True), index=True)

    # this can either be a channel_id or an author_id
    entity_id = db.Column(db.Integer(big=True), index=True, unique=True)

class CommandConfig(db.Table, table_name='command_config'):
    id = db.PrimaryKeyColumn()

    guild_id = db.Column(db.Integer(big=True), index=True)
    channel_id = db.Column(db.Integer(big=True))

    name = db.Column(db.String)
    whitelist = db.Column(db.Boolean)

    @classmethod
    def create_table(cls, *, exists_ok=True):
        statement = super().create_table(exists_ok=exists_ok)
        # create the unique index
        sql = "CREATE UNIQUE INDEX IF NOT EXISTS command_config_uniq_idx ON command_config (channel_id, name, whitelist);"
        return statement + '\n' + sql

class CommandName(commands.Converter):
github Rapptz / RoboDanny / cogs / reminder.py View on Github external
from .utils import checks, db, time, formats
from discord.ext import commands
import discord
import asyncio
import asyncpg
import datetime
import textwrap

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

    expires = db.Column(db.Datetime, index=True)
    created = db.Column(db.Datetime, default="now() at time zone 'utc'")
    event = db.Column(db.String)
    extra = db.Column(db.JSON, default="'{}'::jsonb")

class Timer:
    __slots__ = ('args', 'kwargs', 'event', 'id', 'created_at', 'expires')

    def __init__(self, *, record):
        self.id = record['id']

        extra = record['extra']
        self.args = extra.get('args', [])
        self.kwargs = extra.get('kwargs', {})
github Rapptz / RoboDanny / cogs / emoji.py View on Github external
return cls(animated=partial.animated, url=str(partial.url))

def usage_per_day(dt, usages):
    tracking_started = datetime.datetime(2017, 3, 31)
    now = datetime.datetime.utcnow()
    if dt < tracking_started:
        base = tracking_started
    else:
        base = dt

    days = (now - base).total_seconds() / 86400 # 86400 seconds in a day
    if int(days) == 0:
        return usages
    return usages / days

class EmojiStats(db.Table, table_name='emoji_stats'):
    id = db.Column(db.Integer(big=True, auto_increment=True), primary_key=True)

    guild_id = db.Column(db.Integer(big=True), index=True)
    emoji_id = db.Column(db.Integer(big=True), index=True)
    total = db.Column(db.Integer, default=0)

    @classmethod
    def create_table(cls, *, exists_ok=True):
        statement = super().create_table(exists_ok=exists_ok)

        # create the indexes
        sql = "CREATE UNIQUE INDEX IF NOT EXISTS emoji_stats_uniq_idx ON emoji_stats (guild_id, emoji_id);"
        return statement + '\n' + sql

class Emoji(commands.Cog):
    """Custom emoji tracking"""
github Rapptz / RoboDanny / cogs / tags.py View on Github external
# create the indexes
        sql = "CREATE INDEX IF NOT EXISTS tags_name_trgm_idx ON tags USING GIN (name gin_trgm_ops);\n" \
              "CREATE INDEX IF NOT EXISTS tags_name_lower_idx ON tags (LOWER(name));\n" \
              "CREATE UNIQUE INDEX IF NOT EXISTS tags_uniq_idx ON tags (LOWER(name), location_id);"

        return statement + '\n' + sql

class TagLookup(db.Table, table_name='tag_lookup'):
    id = db.PrimaryKeyColumn()

    # we will create more indexes manually
    name = db.Column(db.String, index=True)
    location_id = db.Column(db.Integer(big=True), index=True)

    owner_id = db.Column(db.Integer(big=True))
    created_at = db.Column(db.Datetime, default="now() at time zone 'utc'")
    tag_id = db.Column(db.ForeignKey('tags', 'id'))

    @classmethod
    def create_table(cls, *, exists_ok=True):
        statement = super().create_table(exists_ok=exists_ok)

        # create the indexes
        sql = "CREATE INDEX IF NOT EXISTS tag_lookup_name_trgm_idx ON tag_lookup USING GIN (name gin_trgm_ops);\n" \
              "CREATE INDEX IF NOT EXISTS tag_lookup_name_lower_idx ON tag_lookup (LOWER(name));\n" \
              "CREATE UNIQUE INDEX IF NOT EXISTS tag_lookup_uniq_idx ON tag_lookup (LOWER(name), location_id);"

        return statement + '\n' + sql

class TagName(commands.clean_content):
    def __init__(self, *, lower=False):
        self.lower = lower
github Rapptz / RoboDanny / cogs / tournament.py View on Github external
import asyncio
import asyncpg
import enum
import re

from .utils import db, config, time

class Players(db.Table):
    id = db.PrimaryKeyColumn()
    discord_id = db.Column(db.Integer(big=True), unique=True, index=True)
    challonge = db.Column(db.String)
    switch = db.Column(db.String, unique=True)

class Teams(db.Table):
    id = db.PrimaryKeyColumn()
    active = db.Column(db.Boolean, default=True)
    challonge = db.Column(db.String, index=True)
    logo = db.Column(db.String)

class TeamMembers(db.Table, table_name='team_members'):
    id = db.PrimaryKeyColumn()
    team_id = db.Column(db.ForeignKey('teams', 'id'), index=True)
    player_id = db.Column(db.ForeignKey('players', 'id'), index=True)
    captain = db.Column(db.Boolean, default=False)

class ChallongeError(commands.CommandError):
    pass

class TournamentState(enum.IntEnum):
    invalid     = 0
    pending     = 1
    checking_in = 2
github Rapptz / RoboDanny / cogs / config.py View on Github external
self._cache = resolved.mention
        return self._cache

class ChannelOrMember(commands.Converter):
    async def convert(self, ctx, argument):
        try:
            return await commands.TextChannelConverter().convert(ctx, argument)
        except commands.BadArgument:
            return await commands.MemberConverter().convert(ctx, argument)

class Plonks(db.Table):
    id = db.PrimaryKeyColumn()
    guild_id = db.Column(db.Integer(big=True), index=True)

    # this can either be a channel_id or an author_id
    entity_id = db.Column(db.Integer(big=True), index=True, unique=True)

class CommandConfig(db.Table, table_name='command_config'):
    id = db.PrimaryKeyColumn()

    guild_id = db.Column(db.Integer(big=True), index=True)
    channel_id = db.Column(db.Integer(big=True))

    name = db.Column(db.String)
    whitelist = db.Column(db.Boolean)

    @classmethod
    def create_table(cls, *, exists_ok=True):
        statement = super().create_table(exists_ok=exists_ok)
        # create the unique index
        sql = "CREATE UNIQUE INDEX IF NOT EXISTS command_config_uniq_idx ON command_config (channel_id, name, whitelist);"
        return statement + '\n' + sql
github Rapptz / RoboDanny / cogs / tournament.py View on Github external
import datetime
import discord
import asyncio
import asyncpg
import enum
import re

from .utils import db, config, time

class Players(db.Table):
    id = db.PrimaryKeyColumn()
    discord_id = db.Column(db.Integer(big=True), unique=True, index=True)
    challonge = db.Column(db.String)
    switch = db.Column(db.String, unique=True)

class Teams(db.Table):
    id = db.PrimaryKeyColumn()
    active = db.Column(db.Boolean, default=True)
    challonge = db.Column(db.String, index=True)
    logo = db.Column(db.String)

class TeamMembers(db.Table, table_name='team_members'):
    id = db.PrimaryKeyColumn()
    team_id = db.Column(db.ForeignKey('teams', 'id'), index=True)
    player_id = db.Column(db.ForeignKey('players', 'id'), index=True)
    captain = db.Column(db.Boolean, default=False)

class ChallongeError(commands.CommandError):
    pass

class TournamentState(enum.IntEnum):
    invalid     = 0
github Godavaru / Godavaru / cogs / currency.py View on Github external
async def inventory(self, ctx, *, member: discord.Member = None):
        """Check your own inventory or the inventory of another user."""
        if member is None:
            member = ctx.author
        if member.bot:
            return await ctx.send(resolve_emoji('ERROR', ctx) + " Bots don't have profiles.")
        if str(member.id) in self.bot.blacklist.keys():
            return await ctx.send(resolve_emoji('ERROR', ctx) + " That user is blacklisted.")
        results = self.bot.query_db(f'''SELECT items FROM users WHERE userid={member.id}''')
        if results:
            profile = list(results)[0]
        else:
            profile = db.default_profile_values
        itms = json.loads(profile[0].replace("'", '"')) if profile[0] else json.loads('{}')
        msg = []
        for i in itms:
            if itms[i] != 0:
                msg.append(f"{items.all_items[i]['emoji']} x{itms[i]}")
        await ctx.send(f'**{member.display_name}\'s Inventory:** ' + (", ".join(msg) if len(msg) > 0 else "None (yet!)"))