示例#1
0
def add_global_admin(user_id):
    from rowboat.redis import rdb
    from rowboat.models.user import User
    init_db(ENV)
    rdb.sadd('global_admins', user_id)
    User.update(admin=True).where(User.user_id == user_id).execute()
    print 'Ok, added {} as a global admin'.format(user_id)
示例#2
0
def rmv_global_admin(user_id):
    from rowboat.redis import rdb
    from rowboat.models.user import User
    init_db(ENV)
    rdb.srem('global_admins', user_id)
    User.update(admin=False).where(User.user_id == user_id).execute()
    print 'Ok, removed {} as a global admin'.format(user_id)
示例#3
0
    def avatar(self, event, user=None):
        if user is None:
            user = event.author

        user_id = 0
        if isinstance(user, (int, long)):
            user_id = user
            user = self.state.users.get(user)

        if user and not user_id:
            user = self.state.users.get(user.id)

        if not user:
            if user_id:
                try:
                    user = self.client.api.users_get(user_id)
                except APIException:
                    raise CommandFail('unknown user')
                User.from_disco_user(user)
            else:
                raise CommandFail('unknown user')

        ext = 'gif' if user.avatar.startswith('a_') else 'png'
        url = user.get_avatar_url()
        r = requests.get(url)
        r.raise_for_status()
        event.msg.reply('', attachments=[('{}.{}'.format(user.id, ext), r.content)])
示例#4
0
    def from_disco_message(cls, obj, is_tag=False):
        msg = obj.with_proper_mentions
        if is_tag:
            msg = msg.replace('tags show ', '', 1)

        if not obj.author.bot:
            _, created = cls.get_or_create(
                id=obj.id,
                defaults=dict(
                    channel_id=obj.channel_id,
                    guild_id=(obj.guild and obj.guild.id),
                    author=User.from_disco_user(obj.author),
                    content=msg,
                    timestamp=obj.timestamp,
                    edited_timestamp=obj.edited_timestamp,
                    num_edits=(0 if not obj.edited_timestamp else 1),
                    mentions=list(obj.mentions.keys()),
                    emojis=list(map(int, EMOJI_RE.findall(obj.content))),
                    attachments=[i.url for i in obj.attachments.values()],
                    embeds=[
                        json.dumps(i.to_dict(), default=default_json)
                        for i in obj.embeds
                    ]))

            for user in obj.mentions.values():
                User.from_disco_user(user)

            return created
示例#5
0
    def infractions_archive(self, event):
        user = User.alias()
        actor = User.alias()

        q = Infraction.select(Infraction, user, actor).join(
            user,
            on=((Infraction.user_id == user.user_id).alias('user'))
        ).switch(Infraction).join(
            actor,
            on=((Infraction.actor_id == actor.user_id).alias('actor'))
        ).where(Infraction.guild_id == event.guild.id)

        buff = StringIO()
        w = csv.writer(buff)

        for inf in q:
            w.writerow([
                inf.id,
                inf.user_id,
                unicode(inf.user).encode('utf-8'),
                inf.actor_id,
                unicode(inf.actor).encode('utf-8'),
                unicode({i.index: i for i in Infraction.Types.attrs}[inf.type_]).encode('utf-8'),
                unicode(inf.reason).encode('utf-8'),
            ])

        event.msg.reply('Ok, here is an archive of all infractions', attachments=[
            ('infractions.csv', buff.getvalue())
        ])
示例#6
0
 def ensure(cls, guild, user, reason=None):
     User.ensure(user)
     obj, _ = cls.get_or_create(guild_id=guild.id,
                                user_id=user.id,
                                defaults=dict({
                                    'reason': reason,
                                }))
     return obj
示例#7
0
 def ensure(cls, guild, user, reason=None):
     from rowboat.models.user import User
     User.ensure(user)
     obj, _ = cls.get_or_create(guild_id=guild.id,
                                user_id=user.id,
                                defaults=dict({
                                    'reason': reason,
                                }))
     return obj
示例#8
0
    def infraction_search(self, event, query=None):
        q = (Infraction.guild_id == event.guild.id)

        if query and isinstance(query, list) and isinstance(
                query[0], DiscoUser):
            query = query[0].id
        elif query:
            query = ' '.join(query)

        if query and (isinstance(query, int) or query.isdigit()):
            q &= ((Infraction.id == int(query)) |
                  (Infraction.user_id == int(query)) |
                  (Infraction.actor_id == int(query)))
        elif query:
            q &= (Infraction.reason**query)

        user = User.alias()
        actor = User.alias()

        infractions = Infraction.select(Infraction, user, actor).join(
            user, on=((Infraction.user_id == user.user_id).alias('user')
                      )).switch(Infraction).join(
                          actor,
                          on=((Infraction.actor_id == actor.user_id
                               ).alias('actor'))).where(q).order_by(
                                   Infraction.created_at.desc()).limit(6)

        tbl = MessageTable()

        tbl.set_header('ID', 'Created', 'Type', 'User', 'Moderator', 'Active',
                       'Reason')
        last_tbl_str = None
        for inf in infractions:
            type_ = {i.index: i for i in Infraction.Types.attrs}[inf.type_]
            reason = inf.reason or ''
            if len(reason) > 256:
                reason = reason[:256] + '...'

            if inf.active:
                active = 'yes'
                if inf.expires_at:
                    active += ' (expires in {})'.format(
                        humanize.naturaldelta(inf.expires_at -
                                              datetime.utcnow()))
            else:
                active = 'no'

            tbl.add(inf.id, inf.created_at.isoformat(), str(type_),
                    unicode(inf.user), unicode(inf.actor), active,
                    clamp(reason, 128))
            tbl_str = tbl.compile()
            if len(tbl_str) >= 2000:
                break
            last_tbl_str = tbl_str

        event.msg.reply(last_tbl_str or "No infractions found.")
示例#9
0
    def search(self, event, query: str):
        queries = []

        if query.isdigit():
            queries.append((User.user_id == query))

        q = USER_MENTION_RE.findall(query)
        if len(q) and q[0].isdigit():
            queries.append((User.user_id == q[0]))
        else:
            queries.append(
                (User.username**'%{}%'.format(query.replace('%', ''))))

        if '#' in query:
            username, discrim = query.rsplit('#', 1)
            if discrim is not None:
                queries.append(((User.username == username) &
                                (User.discriminator == discrim)))

        users = User.select().where(reduce(operator.or_, queries)).limit(10)
        if len(users) == 0:
            raise CommandFail('No users found for query `{}`'.format(
                S(query, escape_codeblocks=True)))

        if len(users) == 1:
            if users[0].user_id in self.state.users:
                return self.info(event, self.state.users.get(users[0].user_id))

        raise CommandSuccess(
            'Found the following users for your query: ```{}```'.format(
                '\n'.join([
                    '{} ({})'.format(str(i), i.user_id) for i in users[:25]
                ])))
示例#10
0
def dash_index():
    if g.user:
        if g.user.admin:
            stats = json.loads(rdb.get('web:dashboard:stats') or '{}')

            if not stats or 'refresh' in request.args:
                stats['messages'] = pretty_number(Message.select().count())
                stats['guilds'] = pretty_number(Guild.select().count())
                stats['users'] = pretty_number(User.select().count())
                stats['channels'] = pretty_number(Channel.select().count())

                rdb.setex('web:dashboard:stats', json.dumps(stats), 300)

            guilds = Guild.select().order_by(Guild.guild_id)
        else:
            stats = {}
            guilds = Guild.select(
                Guild, Guild.config['web'][str(g.user.user_id)].alias('role')
            ).where(
                (Guild.enabled == 1) &
                (~(Guild.config['web'][str(g.user.user_id)] >> None))
            )

        return render_template(
            'dashboard.html',
            stats=stats,
            guilds=guilds,
        )
    return render_template('login.html')
示例#11
0
def search_users(query=None):
    queries = []

    if query.isdigit():
        queries.append((User.user_id == query))

    q = USER_MENTION_RE.findall(query)
    if len(q) and q[0].isdigit():
        ids = []
        ids.append(q[0])
        return ids
    else:
        queries.append((User.username**u'%{}%'.format(query.replace('%', ''))))

    if '#' in query:
        username, discrim = query.rsplit('#', 1)
        if discrim.isdigit():
            queries.append(((User.username == username) &
                            (User.discriminator == int(discrim))))

    users = User.select().where(reduce(operator.or_, queries))
    if len(users) == 0:
        return []

    return map(lambda i: i.user_id, users[:25])
示例#12
0
    def serialize_user(gcc):
        for i in gcc:
            user_raw = '''
                SELECT username, discriminator
                FROM users
                WHERE
                    user_id=%s AND
                    bot=false;
            '''

            user = list(User.raw(user_raw, i[1]).tuples())

            if user:
                return {
                    'user': {
                        'username': user[0][0],
                        'discrim': str(user[0][1]),
                        'id': i[1]
                    },
                    'user_count': int(i[0]),
                }

        return {
            'user': '******',
            'user_count': 0,
        }
示例#13
0
    def on_presence_update(self, event):
        updates = {}

        if event.user.avatar != UNSET:
            updates['avatar'] = event.user.avatar

        if event.user.username != UNSET:
            updates['username'] = event.user.username

        if event.user.discriminator != UNSET:
            updates['discriminator'] = int(event.user.discriminator)

        if not updates:
            return

        User.update(**updates).where((User.user_id == event.user.id)).execute()
示例#14
0
    def search(self, event, query):
        queries = []

        if query.isdigit():
            queries.append((User.user_id == query))

        q = USER_MENTION_RE.findall(query)
        if len(q) and q[0].isdigit():
            queries.append((User.user_id == q[0]))
        else:
            queries.append((User.username ** u'%{}%'.format(query.replace('%', ''))))

        if '#' in query:
            username, discrim = query.rsplit('#', 1)
            if discrim.isdigit():
                queries.append((
                    (User.username == username) &
                    (User.discriminator == int(discrim))))

        users = User.select().where(reduce(operator.or_, queries))
        if len(users) == 0:
            return event.msg.reply(u'No users found for query `{}`'.format(S(query, escape_codeblocks=True)))

        if len(users) == 1:
            if users[0].user_id in self.state.users:
                return self.info(event, self.state.users.get(users[0].user_id))

        return event.msg.reply(u'Found the following users for your query: ```{}```'.format(
            u'\n'.join(map(lambda i: u'{} ({})'.format(unicode(i), i.user_id), users[:25]))
        ))
示例#15
0
文件: auth.py 项目: s0hv/rowboat
def auth_discord_callback():
    if request.values.get('error'):
        return request.values['error']

    if 'state' not in session:
        return 'no state', 400

    discord = make_discord_session(state=session['state'])
    token = discord.fetch_token(
        current_app.config['discord']['TOKEN_URL'],
        client_id=current_app.config['discord']['CLIENT_ID'],
        client_secret=current_app.config['discord']['CLIENT_SECRET'],
        authorization_response=request.url)

    discord = make_discord_session(token=token)

    data = discord.get(current_app.config['discord']['API_BASE_URL'] +
                       '/users/@me').json()

    user = User.with_id(data['id'])
    #user = data

    if not user:
        return 'Unknown User', 403

    # if not user.admin:
    #     return 'Invalid User', 403

    g.user = user

    return redirect('/')
示例#16
0
 def convert_message(obj):
     return {
         'id':
         obj.id,
         'channel_id':
         obj.channel_id,
         'guild_id': (obj.guild and obj.guild.id),
         'author':
         User.from_disco_user(obj.author),
         'content':
         obj.with_proper_mentions,
         'timestamp':
         obj.timestamp,
         'edited_timestamp':
         obj.edited_timestamp,
         'num_edits': (0 if not obj.edited_timestamp else 1),
         'mentions':
         list(obj.mentions.keys()),
         'emojis':
         list(map(int, EMOJI_RE.findall(obj.content))),
         'attachments': [i.url for i in obj.attachments.values()],
         'embeds': [
             json.dumps(i.to_dict(), default=default_json)
             for i in obj.embeds
         ],
     }
示例#17
0
    def infraction_info(self, event, infraction):
        try:
            user = User.alias()
            actor = User.alias()

            infraction = Infraction.select(Infraction, user, actor).join(
                user, on=((Infraction.user_id == user.user_id).alias('user'))
            ).switch(Infraction).join(
                actor,
                on=((Infraction.actor_id == actor.user_id).alias('actor')
                    )).where((Infraction.id == infraction)
                             & (Infraction.guild_id == event.guild.id)).get()
        except Infraction.DoesNotExist:
            raise CommandFail(
                'cannot find an infraction with ID `{}`'.format(infraction))

        type_ = {i.index: i for i in Infraction.Types.attrs}[infraction.type_]
        embed = MessageEmbed()

        if type_ in (Infraction.Types.MUTE, Infraction.Types.TEMPMUTE,
                     Infraction.Types.TEMPROLE):
            embed.color = 0xfdfd96
        elif type_ in (Infraction.Types.KICK, Infraction.Types.SOFTBAN):
            embed.color = 0xffb347
        else:
            embed.color = 0xff6961

        embed.title = str(type_).title()
        embed.set_thumbnail(url=infraction.user.get_avatar_url())
        embed.add_field(name='User',
                        value=unicode(infraction.user),
                        inline=True)
        embed.add_field(name='Moderator',
                        value=unicode(infraction.actor),
                        inline=True)
        embed.add_field(name='Active',
                        value='yes' if infraction.active else 'no',
                        inline=True)
        if infraction.active and infraction.expires_at:
            embed.add_field(name='Expires',
                            value=humanize.naturaldelta(infraction.expires_at -
                                                        datetime.utcnow()))
        embed.add_field(name='Reason',
                        value=infraction.reason or '_No Reason Given',
                        inline=False)
        embed.timestamp = infraction.created_at.isoformat()
        event.msg.reply('', embed=embed)
示例#18
0
def add_global_admin(user_id):
    from rowboat.redis import rdb
    from rowboat.models.user import User
    init_db(ENV)
    rdb.sadd('global_admins', user_id)
    user = User.get_id(user_id)
    user.update(admin=True)
    print('Ok, added {} as a global admin'.format(
        str(user)))  # Not sure if I need to str here
示例#19
0
文件: sql.py 项目: DeJayDev/speedboat
    def on_presence_update(self, event):
        updates = {}

        if event.user.avatar is not None:
            updates['avatar'] = event.user.avatar

        if event.user.username is not None:
            updates['username'] = event.user.username

        if event.user.discriminator is not None:
            updates['discriminator'] = event.user.discriminator

        if event.user.bot:
            return

        if not updates:
            return

        User.update(**updates).where((User.user_id == event.user.id)).execute()
示例#20
0
文件: sql.py 项目: OGNova/airplane
    def update_users(self):
        already_updated = set()

        while True:
            # Only update so many at a time
            if len(already_updated) > 10000:
                return

            try:
                user_id, data = self.user_updates.get_nowait()
            except Empty:
                return

            if user_id in already_updated:
                continue

            already_updated.add(user_id)

            try:
                User.update(**data).where(User.user_id == user_id).execute()
            except:
                self.log.exception('Failed to update user %s: ', user_id)
示例#21
0
    def from_disco_message(cls, obj):
        _, created = cls.get_or_create(
            id=obj.id,
            defaults=dict(
                channel_id=obj.channel_id,
                guild_id=(obj.guild_id if obj.guild_id else None),
                author=User.from_disco_user(obj.author),
                content=obj.with_proper_mentions,
                timestamp=obj.timestamp,
                edited_timestamp=obj.edited_timestamp,
                num_edits=(0 if not obj.edited_timestamp else 1),
                mentions=list(obj.mentions.keys()),
                emojis=list(map(int, EMOJI_RE.findall(obj.content))),
                attachments=[i.url for i in list(obj.attachments.values())],
                embeds=[
                    json.dumps(i.to_dict(), default=default_json)
                    for i in obj.embeds
                ]))

        for user in list(obj.mentions.values()):
            User.from_disco_user(user)

        return created
示例#22
0
def stats():
    stats = json.loads(rdb.get('web:dashboard:stats') or '{}')

    if not stats or 'refresh' in request.args:
        # stats['messages'] = pretty_number(Message.select().count())
        # stats['guilds'] = pretty_number(Guild.select().count())
        # stats['users'] = pretty_number(User.select().count())
        # stats['channels'] = pretty_number(Channel.select().count())
        stats['messages'] = Message.select().count()
        stats['guilds'] = Guild.select().count()
        stats['users'] = User.select().count()
        stats['channels'] = Channel.select().count()

        rdb.setex('web:dashboard:stats', json.dumps(stats), 300)

    return jsonify(stats)
示例#23
0
    def xp_leaderboard(self, event, places=None, offset=None):
        places = places if places else 10
        offset = offset if offset else 0
        user = User.alias()

        leaderboard = GuildMemberLevel.select(GuildMemberLevel, user).join(
            user,
            on=((GuildMemberLevel.user_id == user.user_id).alias('user'))
        ).where(GuildMemberLevel.guild_id == event.guild.id,
                GuildMemberLevel.xp > 0).order_by(
                    GuildMemberLevel.xp.desc()).offset(offset).limit(places)

        tbl = MessageTable()
        tbl.set_header('Place', 'User', 'Level (XP)')
        for place, entry in enumerate(leaderboard,
                                      start=(offset if offset else 1)):
            tbl.add(place, str(entry.user),
                    '{} ({})'.format(self.level_from_xp(entry.xp), entry.xp))

        event.msg.reply(tbl.compile())
示例#24
0
    def info(self, event, user=None):
        if user is None:
            user = event.author

        user_id = 0
        if isinstance(user, (int, long)):
            user_id = user
            user = self.state.users.get(user)

        if user and not user_id:
            user = self.state.users.get(user.id)

        if not user:
            if user_id:
                try:
                    user = self.client.api.users_get(user_id)
                except APIException:
                    raise CommandFail('unknown user')
                User.from_disco_user(user)
            else:
                raise CommandFail('unknown user')

        self.client.api.channels_typing(event.channel.id)

        content = []
        content.append(u'**\u276F User Information**')
        content.append(u'**ID:** {}'.format(user.id))
        content.append(u'**Profile:** <@{}>'.format(user.id))

        if user.presence:
            emoji, status = get_status_emoji(user.presence)
            content.append('**Status:** {} <{}>'.format(status, emoji))

            game = user.presence.game
            if game and game.name:
                activity = ['Playing', 'Stream', 'Listening to', 'Watching', 'Custom Status'][int(game.type or 0)]
                if not game.type:
                    activity = None
                if activity:
                    game_name = game.state if game.type == GameType.CUSTOM_STATUS else game.name
                    content.append(u'**{}:** {}'.format(activity,
                        u'[{}]({})'.format(game_name, game.url) if game.url else game_name
                    ))

        if user.public_flags and user.public_flags != 0:
            flags = []
            for flag, emoji in BADGE_EMOJI.items():
                if user.public_flags.check(flag):
                    flags.append('<{}>'.format(emoji))

            if len(flags) > 0:
                content.append('**Badges**: {}'.format(' '.join(flags)))

        created_dt = to_datetime(user.id)
        content.append('**Created:** {} ago ({})'.format(
            humanize.naturaldelta(datetime.utcnow() - created_dt),
            created_dt.isoformat()
        ))

        member = event.guild.get_member(user.id) if event.guild else None
        if member:
            content.append(u'\n**\u276F Member Information**')

            if member.nick:
                content.append(u'**Nickname:** {}'.format(member.nick))

            content.append('**Joined:** {} ago ({})'.format(
                humanize.naturaldelta(datetime.utcnow() - member.joined_at),
                member.joined_at.isoformat(),
            ))


            if member.roles:
                content.append(u'**Roles:** {}'.format(
                    ' '.join((member.guild.roles.get(r).mention for r in sorted(member.roles, key=lambda r: member.guild.roles.get(r).position, reverse=True)))
                ))

            # "is not None" does not work with Unset types for some reason
            if bool(member.premium_since):
                content.append('**Boosting since:** {} ago ({})'.format(
                    humanize.naturaldelta(datetime.utcnow() - member.premium_since),
                    member.premium_since.isoformat(),
                ))

        # Execute a bunch of queries async
        newest_msg = Message.select(Message.timestamp).where(
            (Message.author_id == user.id) &
            (Message.guild_id == event.guild.id)
        ).limit(1).order_by(Message.timestamp.desc()).async()

        oldest_msg = Message.select(Message.timestamp).where(
            (Message.author_id == user.id) &
            (Message.guild_id == event.guild.id)
        ).limit(1).order_by(Message.timestamp.asc()).async()

        infractions = Infraction.select(
            Infraction.guild_id,
            fn.COUNT('*')
        ).where(
            (Infraction.user_id == user.id)
        ).group_by(Infraction.guild_id).tuples().async()

        voice = GuildVoiceSession.select(
            GuildVoiceSession.user_id,
            fn.COUNT('*'),
            fn.SUM(GuildVoiceSession.ended_at - GuildVoiceSession.started_at)
        ).where(
            (GuildVoiceSession.user_id == user.id) &
            (~(GuildVoiceSession.ended_at >> None))
        ).group_by(GuildVoiceSession.user_id).tuples().async()

        # Wait for them all to complete (we're still going to be as slow as the
        #  slowest query, so no need to be smart about this.)
        wait_many(newest_msg, oldest_msg, infractions, voice, timeout=10)
        tags = to_tags(guild_id=event.msg.guild.id)

        if newest_msg.value and oldest_msg.value:
            statsd.timing('sql.duration.newest_msg', newest_msg.value._query_time, tags=tags)
            statsd.timing('sql.duration.oldest_msg', oldest_msg.value._query_time, tags=tags)
            newest_msg = newest_msg.value.get()
            oldest_msg = oldest_msg.value.get()

            content.append(u'\n **\u276F Activity**')
            content.append('**Last Message:** {} ago ({})'.format(
                humanize.naturaldelta(datetime.utcnow() - newest_msg.timestamp),
                newest_msg.timestamp.isoformat(),
            ))
            content.append('**First Message:** {} ago ({})'.format(
                humanize.naturaldelta(datetime.utcnow() - oldest_msg.timestamp),
                oldest_msg.timestamp.isoformat(),
            ))

        if infractions.value:
            statsd.timing('sql.duration.infractions', infractions.value._query_time, tags=tags)
            infractions = list(infractions.value)
            total = sum(i[1] for i in infractions)
            content.append(u'\n**\u276F Infractions**')
            content.append('**Total Infractions:** {:,}'.format(total))
            content.append('**Unique Servers:** {}'.format(len(infractions)))

        if voice.value:
            statsd.timing('plugin.utilities.info.sql.voice', voice.value._query_time, tags=tags)
            voice = list(voice.value)
            content.append(u'\n**\u276F Voice**')
            content.append(u'**Sessions:** {:,}'.format(voice[0][1]))
            content.append(u'**Time:** {}'.format(humanize.naturaldelta(
                voice[0][2]
            )))

        embed = MessageEmbed()

        avatar = user.avatar
        if avatar:
            avatar = user.avatar_url
        else:
            avatar = u'https://cdn.discordapp.com/embed/avatars/{}.png'.format(
                int(user.discriminator) % 5
            )

        embed.set_author(name=u'{}#{}'.format(
            user.username,
            user.discriminator,
        ), icon_url=avatar)

        embed.set_thumbnail(url=user.avatar_url if user.avatar else avatar)

        embed.description = '\n'.join(content)
        embed.color = get_dominant_colors_user(user, user.get_avatar_url('png') if user.avatar else avatar)
        event.msg.reply('', embed=embed)
示例#25
0
    def info(self, event, user):
        if isinstance(user, (int, long)):
            try:
                r = self.bot.client.api.http(Routes.USERS_GET, dict(user=user)) # hacky method cause this old version of Disco doesn't have a method for this and we're too lazy to update
                data = r.json()
                User = namedtuple('User', [
                    'avatar',
                    'discriminator',
                    'id',
                    'username',
                    'presence'
                ])
                user = User(
                    avatar=data["avatar"],
                    discriminator=data["discriminator"],
                    id=int(data["id"]),
                    username=data["username"],
                    presence=None
                )
            except APIException as e:
                raise CommandFail('invalid user')
        
        content = []
        content.append(u'**\u276F User Information**')
        content.append(u'ID: {}'.format(user.id))
        content.append(u'Profile: <@{}>'.format(user.id))

        if user.presence:
            emoji, status = get_status_emoji(user.presence)
            content.append('Status: {} <{}>'.format(status, emoji))
            if user.presence.game and user.presence.game.name:
                if user.presence.game.type == GameType.DEFAULT:
                    content.append(u'Game: {}'.format(user.presence.game.name))
                else:
                    content.append(u'Stream: [{}]({})'.format(user.presence.game.name, user.presence.game.url))

        created_dt = to_datetime(user.id)
        content.append('Created: {} ago ({})'.format(
            humanize.naturaldelta(datetime.utcnow() - created_dt),
            created_dt.isoformat()
        ))

        member = event.guild.get_member(user.id) if event.guild else None
        if member:
            content.append(u'\n**\u276F Member Information**')

            if member.nick:
                content.append(u'Nickname: {}'.format(member.nick))

            content.append('Joined: {} ago ({})'.format(
                humanize.naturaldelta(datetime.utcnow() - member.joined_at),
                member.joined_at.isoformat(),
            ))

            if member.roles:
                content.append(u'Roles: {}'.format(
                    ', '.join((member.guild.roles.get(r).name for r in member.roles))
                ))

        # Execute a bunch of queries async
        newest_msg = Message.select(Message.timestamp).where(
            (Message.author_id == user.id) &
            (Message.guild_id == event.guild.id)
        ).limit(1).order_by(Message.timestamp.desc()).async()

        oldest_msg = Message.select(Message.timestamp).where(
            (Message.author_id == user.id) &
            (Message.guild_id == event.guild.id)
        ).limit(1).order_by(Message.timestamp.asc()).async()

        infractions = Infraction.select(
            Infraction.guild_id,
            fn.COUNT('*')
        ).where(
            (Infraction.user_id == user.id)
        ).group_by(Infraction.guild_id).tuples().async()

        voice = GuildVoiceSession.select(
            GuildVoiceSession.user_id,
            fn.COUNT('*'),
            fn.SUM(GuildVoiceSession.ended_at - GuildVoiceSession.started_at)
        ).where(
            (GuildVoiceSession.user_id == user.id) &
            (~(GuildVoiceSession.ended_at >> None))
        ).group_by(GuildVoiceSession.user_id).tuples().async()

        # Wait for them all to complete (we're still going to be as slow as the
        #  slowest query, so no need to be smart about this.)
        wait_many(newest_msg, oldest_msg, infractions, voice, timeout=10)
        tags = to_tags(guild_id=event.msg.guild.id)

        if newest_msg.value and oldest_msg.value:
            statsd.timing('sql.duration.newest_msg', newest_msg.value._query_time, tags=tags)
            statsd.timing('sql.duration.oldest_msg', oldest_msg.value._query_time, tags=tags)
            newest_msg = newest_msg.value.get()
            oldest_msg = oldest_msg.value.get()

            content.append(u'\n **\u276F Activity**')
            content.append('Last Message: {} ago ({})'.format(
                humanize_duration(datetime.utcnow() - newest_msg.timestamp),
                newest_msg.timestamp.isoformat(),
            ))
            content.append('First Message: {} ago ({})'.format(
                humanize_duration(datetime.utcnow() - oldest_msg.timestamp),
                oldest_msg.timestamp.isoformat(),
            ))

        if infractions.value:
            statsd.timing('sql.duration.infractions', infractions.value._query_time, tags=tags)
            infractions = list(infractions.value)
            total = sum(i[1] for i in infractions)
            content.append(u'\n**\u276F Infractions**')
            content.append('Total Infractions: {}'.format(total))
            content.append('Unique Servers: {}'.format(len(infractions)))

        if voice.value:
            statsd.timing('plugin.utilities.info.sql.voice', voice.value._query_time, tags=tags)
            voice = list(voice.value)
            content.append(u'\n**\u276F Voice**')
            content.append(u'Sessions: {}'.format(voice[0][1]))
            content.append(u'Time: {}'.format(humanize.naturaldelta(
                voice[0][2]
            )))

        embed = MessageEmbed()

        avatar = u'https://cdn.discordapp.com/avatars/{}/{}.png'.format(
            user.id,
            user.avatar,
        )

        embed.set_author(name=u'{}#{}'.format(
            user.username,
            user.discriminator,
        ), icon_url=avatar)

        embed.set_thumbnail(url=avatar)

        embed.description = '\n'.join(content)
        embed.color = get_dominant_colors_user(user, avatar)
        event.msg.reply('', embed=embed)
示例#26
0
 def is_global_admin(self, userid):
     global_admin = rdb.sismember('global_admins', userid)
     _usr = User.select().where(User.user_id == userid)
     if len(_usr) == 1:
         global_admin = _usr[0].admin
     return global_admin
示例#27
0
def check_auth():
    g.user = None

    if 'uid' in session:
        g.user = User.with_id(session['uid'])
示例#28
0
def guild_infractions(guild):
    user = User.alias()
    actor = User.alias()

    page = int(request.values.get('page', 1))
    if page < 1:
        page = 1

    limit = int(request.values.get('limit', 1000))
    if limit < 1 or limit > 1000:
        limit = 1000

    q = Infraction.select(Infraction, user, actor).join(
        user,
        on=((Infraction.user_id == user.user_id).alias('user')
            )).switch(Infraction).join(
                actor,
                on=((Infraction.actor_id == actor.user_id).alias('actor')))

    queries = []
    if 'filtered' in request.values:
        filters = json.loads(request.values['filtered'])

        for f in filters:
            if f['id'] not in CAN_FILTER:
                continue

            if f['id'] == 'type':
                queries.append(
                    Infraction.type_ == Infraction.Types.get(f['value']))
            elif f['id'] == 'reason':
                queries.append(
                    Infraction.reason**('%' +
                                        f['value'].lower().replace('%', '') +
                                        '%'))
            else:
                queries.append(getattr(Infraction, f['id']) == f['value'])

    if queries:
        q = q.where((Infraction.guild_id == guild.guild_id)
                    & reduce(operator.and_, queries))
    else:
        q = q.where((Infraction.guild_id == guild.guild_id))

    sorted_fields = []
    if 'sorted' in request.values:
        sort = json.loads(request.values['sorted'])

        for s in sort:
            if s['id'] not in CAN_SORT:
                continue

            if s['desc']:
                sorted_fields.append(getattr(Infraction, s['id']).desc())
            else:
                sorted_fields.append(getattr(Infraction, s['id']))

    if sorted_fields:
        q = q.order_by(*sorted_fields)
    else:
        q = q.order_by(Infraction.id.desc())

    q = q.paginate(
        page,
        limit,
    )

    return jsonify(
        [i.serialize(guild=guild, user=i.user, actor=i.actor) for i in q])
示例#29
0
def guild_infractions_list(guild):
    user = User.alias()
    actor = User.alias()

    columns = [
        Infraction.id,
        Infraction.type_,
        user.user_id,
        user.username,
        actor.user_id,
        actor.username,
        Infraction.reason,
        Infraction.created_at,
        Infraction.expires_at,
    ]

    def serialize(inf):
        type_ = {i.index: i for i in Infraction.Types.attrs}[inf.type_]
        return {
            'id':
            inf.id,
            'user':
            serialize_user(inf.user),
            'actor':
            serialize_user(inf.actor),
            'type':
            str(type_),
            'reason':
            inf.reason,
            'metadata':
            inf.metadata,
            'expires_at':
            (inf.expires_at.isoformat() if inf.expires_at else None)
            if inf.active else 'Expired',
            'created_at':
            inf.created_at.isoformat() if inf.created_at else None
        }

    sort_order = []
    for idx in xrange(32):
        ch = 'order[{}][column]'.format(idx)
        if ch not in request.values:
            break

        cd = 'order[{}][dir]'.format(idx)
        column = columns[int(request.values.get(ch))]
        order = request.values.get(cd)

        if order == 'asc':
            column = column.asc()
        else:
            column = column.desc()

        sort_order.append(column)

    base_q = Infraction.select(Infraction, user, actor).join(
        user,
        on=(Infraction.user_id == user.user_id).alias('user'),
    ).switch(Infraction).join(
        actor,
        on=(Infraction.actor_id == actor.user_id).alias('actor'),
    ).where(Infraction.guild_id == guild.guild_id).order_by(*sort_order)

    search = request.values.get('search[value]')
    opts = []
    if search:
        opts.append(user.username**u'%{}%'.format(search))
        opts.append(actor.username**u'%{}%'.format(search))
        opts.append(Infraction.reason**u'%{}%'.format(search))

        if search.isdigit():
            opts.append(user.user_id == int(search))
            opts.append(actor.user_id == int(search))
            opts.append(Infraction.id == int(search))

    if opts:
        filter_q = base_q.where(reduce(operator.or_, opts))
    else:
        filter_q = base_q

    final_q = filter_q.offset(int(request.values.get('start'))).limit(
        int(request.values.get('length')))

    return jsonify({
        'draw': int(request.values.get('draw')),
        'recordsTotal': base_q.count(),
        'recordsFiltered': filter_q.count(),
        'data': map(serialize, final_q),
    })
示例#30
0
    def info(self, event, user: User = None):
        if not user:
            user = event.author
        else:
            if not isinstance(user, DiscoUser):
                try:
                    user = self.state.guilds[event.guild.id].members[user].user
                except KeyError:
                    try:
                        user = self.state.users[user]
                    except KeyError:
                        try:
                            user = self.bot.client.api.users_get(user)
                        except APIException:
                            return event.msg.reply(
                                ':eyes: User not found').after(3).delete()

        self.client.api.channels_typing(event.channel.id)

        content = []
        content.append('**\u276F User Information**')
        content.append('Profile: <@{}>'.format(user.id))

        created_dt = to_datetime(user.id)
        content.append('Created: <t:{0}:R> (<t:{0}:f>)'.format(
            int(created_dt.replace(tzinfo=pytz.UTC).timestamp())))

        member = event.guild.get_member(user.id) if event.guild else None

        if user.public_flags:
            badges = ''
            user_badges = list(UserFlags(user.public_flags))
            for badge in user_badges:
                badges += '<{}> '.format(BADGE_EMOJI[badge])

            content.append('Badges: {}'.format(badges))

        if member:
            content.append('\n**\u276F Member Information**')

            if member.nick:
                content.append('Nickname: {}'.format(member.nick))

            content.append('Joined: <t:{0}:R> (<t:{0}:f>)'.format(
                int(member.joined_at.replace(tzinfo=pytz.UTC).timestamp())))

            content.append('Messages: {}'.format(
                int(
                    Message.select(fn.Count(
                        Message.id)).where((Message.author_id == user.id)
                                           & (Message.guild_id == event.guild.
                                              id)).tuples()[0][0])))

            if member.roles:
                content.append('Roles: {}'.format(', '.join(
                    ('<@&{}>'.format(r) for r in member.roles))))

        # Execute a bunch of queries
        newest_msg = Message.select(fn.MAX(Message.id)).where(
            (Message.author_id == user.id)
            & (Message.guild_id == event.guild.id)).tuples()[0][0]

        infractions = Infraction.select(Infraction.id).where(
            (Infraction.user_id == user.id)
            & (Infraction.guild_id == event.guild.id)).tuples()

        if newest_msg:
            content.append('\n **\u276F Activity**')
            content.append('Last Message: <t:{0}:R> (<t:{0}:f>)'.format(
                int((to_datetime(newest_msg).replace(
                    tzinfo=pytz.UTC)).timestamp())))
            # content.append('First Message: {} ({})'.format(
            #    humanize.naturaltime(datetime.utcnow() - to_datetime(oldest_msg)),
            #    to_datetime(oldest_msg).strftime("%b %d %Y %H:%M:%S"),
            # ))

        if len(infractions) > 0:
            content.append('\n**\u276F Infractions**')
            total = len(infractions)
            content.append('Total Infractions: **{:,}**'.format(total))

        embed = MessageEmbed()

        try:
            avatar = User.with_id(user.id).get_avatar_url()
        except APIException:
            avatar = user.get_avatar_url(
            )  # This fails if the user has never been seen by speedboat.

        embed.set_author(name='{} ({})'.format(
            str(user),
            user.id,
        ),
                         icon_url=avatar)

        embed.set_thumbnail(url=avatar)

        embed.description = '\n'.join(content)
        embed.color = get_dominant_colors_user(user, avatar)
        event.msg.reply('', embed=embed)