Example #1
0
    def update_subreddit(self, sub, configs):
        # TODO: use before on this request
        r = requests.get('https://www.reddit.com/r/{}/new.json'.format(sub),
                         headers={
                             'User-Agent':
                             'discord:RowBoat:v0.0.1 (by /u/b1naryth1ef)'
                         })
        r.raise_for_status()

        data = list(
            reversed(map(lambda i: i['data'],
                         r.json()['data']['children'])))

        # TODO:
        #  1. instead of tracking per guild, just track globally per subreddit
        #  2. fan-out posts to each subscribed channel

        for gid, config in configs:
            guild = self.state.guilds.get(gid)
            if not guild:
                self.log.warning('Skipping non existant guild %s', gid)
                continue

            channel = self.get_channel(guild, config.channel)
            if not channel:
                self.log.warning(
                    'Skipping non existant channel %s for guild %s (%s)',
                    channel, guild.name, gid)
                continue
            last = float(
                rdb.get('rdt:lpid:{}:{}'.format(channel.id, sub)) or 0)

            item_count, high_time = 0, last
            for item in data:
                if item['created_utc'] > last:
                    try:
                        self.send_post(config, channel, item)
                    except:
                        self.log.exception(
                            'Failed to post reddit content from %s\n\n', item)
                    item_count += 1

                    if item['created_utc'] > high_time:
                        rdb.set('rdt:lpid:{}:{}'.format(channel.id, sub),
                                item['created_utc'])
                        high_time = item['created_utc']

                if item_count > 10:
                    break
Example #2
0
def get_dominant_colors_guild(guild):
    import requests
    from rowboat.redis import rdb
    from PIL import Image
    from six import BytesIO

    key = 'guild:color:{}'.format(guild.icon)
    if rdb.exists(key):
        return int(rdb.get(key))
    else:
        r = requests.get(guild.icon_url)
        try:
            r.raise_for_status()
        except:
            return 0
        color = int(get_dominant_colors(Image.open(BytesIO(r.content)))[0], 16)
        rdb.set(key, color)
        return color
Example #3
0
def get_dominant_colors_user(user, url=None):
    import requests
    from rowboat.redis import rdb
    from PIL import Image
    from six import BytesIO

    key = 'avatar:color:{}'.format(user.avatar)
    if rdb.exists(key):
        return int(rdb.get(key))
    else:
        r = requests.get(url or user.avatar_url)
        try:
            r.raise_for_status()
        except:
            return 0
        color = int(get_dominant_colors(Image.open(BytesIO(r.content)))[0], 16)
        rdb.set(key, color)
        return color
Example #4
0
def get_dominant_colors_user(user, url=None):
    import requests
    from rowboat.redis import rdb
    from PIL import Image
    from io import BytesIO

    key = 'avatar:color:{}'.format(user.avatar)
    if rdb.exists(key):
        return int(rdb.get(key))
    else:
        r = requests.get(url or user.get_avatar_url())
        try:
            r.raise_for_status()
        except:
            return 0

        rgbcolor = get_dominant_colors(Image.open(BytesIO(r.content)))[0]
        color = int('%02x%02x%02x' % (rgbcolor[0], rgbcolor[1], rgbcolor[2]),
                    16)  # Math is hard. https://stackoverflow.com/a/8340936
        rdb.set(key, color)

        return color
Example #5
0
    def server(self, event, guild_id=None):
        guild = self.state.guilds.get(guild_id) if guild_id else event.guild
        if not guild:
            raise CommandFail('invalid server')

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

        embed = MessageEmbed()

        # Server Information
        content_server = []

        created_at = to_datetime(guild.id)
        content_server.append(u'**Created:** {} ago ({})'.format(
            humanize.naturaldelta(datetime.utcnow() - created_at),
            created_at.isoformat(),
        ))
        content_server.append(u'**Members:** {:,}'.format(guild.member_count))
        if len(guild.features) > 0:
            content_server.append(u'**Features:** {}'.format(', '.join(guild.features) or 'none'))
        content_server.append(u'**Voice region:** {}'.format(guild.region))

        if not rdb.exists('gmm:{}'.format(guild.id)):
            self.state.guilds[guild.id].inplace_update(self.client.api.guilds_get(guild.id), ignored=[
                'channels',
                'members',
                'voice_states',
                'presences',
            ])
            rdb.set('gmp:{}'.format(guild.id), self.state.guilds[guild.id].max_presences)
            rdb.set('gmm:{}'.format(guild.id), self.state.guilds[guild.id].max_members)

        content_server.append(u'**Max presences:** {:,}'.format(int(rdb.get('gmp:{}'.format(guild.id)))))
        content_server.append(u'**Max members:** {:,}'.format(int(rdb.get('gmm:{}'.format(guild.id)))))

        embed.add_field(name=u'\u276F Server Information', value='\n'.join(content_server), inline=False)

        # Counts
        content_counts = []
        count = {}
        for c in guild.channels.values():
            if not c.type:
                continue
            ctype = c.type.name.split('_')[1]
            count[ctype] = count.get(ctype, 0) + 1
        content_counts.append(u'<{}> {} channel categories'.format(CHANNEL_CATEGORY_EMOJI, count.get('category', 0)))
        content_counts.append(u'<{}> {} text channels'.format(TEXT_CHANNEL_EMOJI, count.get('text', 0)))
        content_counts.append(u'<{}> {} voice channels'.format(VOICE_CHANNEL_EMOJI, count.get('voice', 0)))
        embed.add_field(name=u'\u276F Counts', value='\n'.join(content_counts), inline=True)

        content_counts2 = []
        content_counts2.append(u'<{}> {} roles'.format(ROLE_EMOJI, len(guild.roles)))
        static_emojis = len(filter(lambda e: not guild.emojis.get(e).animated, guild.emojis))
        animated_emojis = len(filter(lambda e: guild.emojis.get(e).animated, guild.emojis))
        content_counts2.append(u'<{}> {}/{total} static emojis'.format(
            EMOJI_EMOJI,
            static_emojis,
            total=self.get_max_emoji_slots(guild))
        )
        content_counts2.append(u'<{}> {}/{total} animated emojis'.format(
            EMOJI_EMOJI,
            animated_emojis,
            total=self.get_max_emoji_slots(guild))
        )
        embed.add_field(name=u'\u200B', value='\n'.join(content_counts2), inline=True)

        # Members
        invite = guild.get_preview()

        status_online = None
        if invite:
            if not rdb.exists('apc:{}'.format(guild.id)):
                rdb.set('apc:{}'.format(guild.id), invite.approximate_presence_count, 900)
            status_online = int(rdb.get('apc:{}'.format(guild.id)))

            content_members = []
            content_members.append('<{}> {}'.format(STATUS_EMOJI[Status.ONLINE], status_online))
            content_members.append('<{}> {}'.format(STATUS_EMOJI[Status.OFFLINE], (guild.member_count - status_online)))

            # status_counts = defaultdict(int)
            # for member in guild.members.values():
            #     if not member.user.presence:
            #         status = Status.OFFLINE
            #     else:
            #         status = member.user.presence.status
            #     status_counts[status] += 1

            # for status, count in sorted(status_counts.items(), key=lambda i: Status[i[0]]):
            #     content_members.append(u'<{}> - {}'.format(
            #         STATUS_EMOJI[status], count
            #     ))

            embed.add_field(name=u'\u276F Members', value='\n'.join(content_members), inline=True)

        # Boosts
        content_boosts = []
        content_boosts.append(u'<{}> Level {}'.format(PREMIUM_GUILD_TIER_EMOJI[guild.premium_tier], int(guild.premium_tier)))
        # real_boost_count = len(filter(lambda y: guild.members.get(y).premium_since, guild.members))
        content_boosts.append(u'<{}> {} boosts'.format(
            PREMIUM_GUILD_ICON_EMOJI,
            guild.premium_subscription_count,
            # '({} members)'.format(real_boost_count) if real_boost_count < guild.premium_subscription_count else ''
        ))
        embed.add_field(name=u'\u276F Server Boost', value='\n'.join(content_boosts), inline=True)

        if guild.icon:
            embed.set_thumbnail(url=guild.icon_url)
            embed.color = get_dominant_colors_guild(guild, guild.get_icon_url('png'))
        event.msg.reply('', embed=embed)
Example #6
0
 def set_guild_state(self, guild_id, channel_id, state):
     rdb.set(TWITCH_GUILD_STATE_KEY.format(
         guild_id,
         channel_id
     ), json.dumps(state))
Example #7
0
 def set_stream_state(self, channel_id, data):
     rdb.set(TWITCH_STREAM_STATE_KEY.format(channel_id), json.dumps(data))