コード例 #1
0
ファイル: core.py プロジェクト: ItsDoot/rowboat
 def command_about(self, event):
     embed = MessageEmbed()
     embed.set_author(name='Rowboat', icon_url=self.client.state.me.avatar_url, url='https://docs.rowboat.party/')
     embed.description = BOT_INFO
     embed.add_field(name='Servers', value=str(Guild.select().count()), inline=True)
     embed.add_field(name='Uptime', value=humanize.naturaltime(datetime.utcnow() - self.startup), inline=True)
     event.msg.reply('', embed=embed)
コード例 #2
0
ファイル: internal.py プロジェクト: anapple96/speedboat
    def on_commands_info(self, event, mid):
        cmd = Command.select(Command, Message, Channel).join(
            Message,
            on=(Command.message_id == Message.id).alias('message')).join(
                Channel,
                on=(Channel.channel_id == Message.channel_id).alias('channel')
            ).join(
                User,
                on=(User.user_id == Message.author_id).alias('author')).where(
                    Command.message_id == mid).order_by(
                        Message.timestamp.desc(), ).get()

        embed = MessageEmbed()
        embed.title = '{}.{} ({})'.format(cmd.plugin, cmd.command,
                                          cmd.message.id)
        embed.set_author(name=str(cmd.message.author),
                         icon_url=cmd.message.author.get_avatar_url())
        embed.color = 0x77dd77 if cmd.success else 0xff6961

        if not cmd.success:
            embed.description = '```{}```'.format(cmd.traceback)

        embed.add_field(name='Message', value=cmd.message.content)
        embed.add_field(name='Channel',
                        value='{} `{}`'.format(cmd.message.channel.name,
                                               cmd.message.channel.channel_id))
        embed.add_field(name='Guild', value=str(cmd.message.guild_id))
        event.msg.reply(embed=embed)
コード例 #3
0
ファイル: core.py プロジェクト: golu701/jetski
    def plugin_manager(self, event, plugin=None, mode='list'):
        if mode == 'list':
            embed = MessageEmbed()
            embed.color = 0x7289da
            embed.set_author(name='Loaded Plugins ({})'.format(len(self.bot.plugins)), icon_url=self.state.me.avatar_url)
            embed.description = '```md\n{}```'.format('\n'.join('- {}'.format(key) for key in self.bot.plugins))
            embed.set_footer(text='Use file name for load, registered name for unload/reload.')
            return event.msg.reply('', embed=embed)

        pl = self.bot.plugins.get(plugin)

        if mode == 'load':
            if pl:
                return event.msg.reply('<:{}> {} plugin is already loaded.'.format(RED_TICK_EMOJI, pl.name))
            try:
                self.bot.add_plugin_module('rowboat.plugins.{}'.format(plugin))
            except:
                return event.msg.reply('<:{}> Failed to load {} plugin.'.format(RED_TICK_EMOJI, plugin))
            return event.msg.reply(':ok_hand: Loaded {} plugin.'.format(plugin))

        if not pl:
            return event.msg.reply('<:{}> Could not find this plugin.'.format(plugin))

        if mode == 'unload':
            self.bot.rmv_plugin(pl.__class__)
            self.log.info('Unloaded {} plugin'.format(pl.name))
            return event.msg.reply(':ok_hand: Unloaded {} plugin.'.format(pl.name))

        if mode == 'reload':
            self.bot.reload_plugin(pl.__class__)
            self.log.info('Reloaded {} plugin'.format(pl.name))
            return event.msg.reply(':ok_hand: Reloaded {} plugin.'.format(pl.name))
コード例 #4
0
    def command_test(self, event):
        embed = MessageEmbed()

        #sets the title of the embed
        embed.title = 'Game Center Central'
        embed.set_author(
            name='Game Center Central',
            url='https://discord.ares.party',
            icon_url='https://blog.ares.party/content/images/2018/01/pfp.gif')
        embed.description = 'A server built on on the topics of games and other things.'
        #Inline field 1
        embed.add_field(name='Why is our server different',
                        value='Well, Its different in many ways.')
        #Inline field 2
        embed.add_field(name='What does ares break?', value='Everything.')
        #Inline field 3
        embed.add_field(name='Can I break things with Ares',
                        value='Pls no, We dont need more shit broken kthx.')
        #timestap
        embed.timestamp = datetime.utcnow().isoformat()
        #footer
        embed.set_footer(text='This is the f*****g footer you dumb ass.')
        #color
        embed.color = randint(0, 16777215)
        event.msg.reply(embed=embed)
コード例 #5
0
 def commands_command(self, event):
     """Get a list of commands you can use with the bot"""
     embed = MessageEmbed()
     embed.set_author(
         name='Referee Commands',
         url='https://github.com/UHCBot/Referee',
         icon_url=self.client.state.me.avatar_url
     )
     embed.color = 0xf3733a
     for p in self.bot.plugins.values():
         for c in p.commands:
             args = []
             if c.args:
                 for arg in c.args.args:
                     args.append(arg.name)
             user_level = get_user_level(event.guild.members[event.msg.author.id])
             global_admin = check_global_admin(event.msg.author.id)
             if c.level:
                 if not global_admin and c.level == -1:
                     continue
                 if not global_admin and c.level > user_level:
                     continue
             embed.add_field(
                 name='{}{}'.format(
                     c.group + ' ' if c.group else '', c.name),
                 value='Level: {} {}\nArgs: {}\nDescription: {}'.format(
                     c.level if c.level else 'Everyone',
                     'or higher' if c.level and c.level != -1 else '',
                     ', '.join(args) if args != [] else 'None',
                     c.get_docstring() if c.get_docstring() else 'No description provided'
                 ).replace('-1', 'Global admin').replace('mod', 'Mod').replace('dev', 'Dev'),
                 inline=True
                 )
     event.msg.reply('', embed=embed)
コード例 #6
0
ファイル: core.py プロジェクト: golu701/jetski
 def command_about(self, event):
     embed = MessageEmbed()
     embed.color = 0x7289da
     embed.set_author(name='Jetski', icon_url=self.client.state.me.avatar_url, url='https://jetski.ga/')
     embed.description = BOT_INFO
     embed.add_field(name='Servers', value=str(Guild.select().count()), inline=True)
     embed.add_field(name='Uptime', value=humanize_duration(datetime.utcnow() - self.startup), inline=True)
     event.msg.reply(embed=embed)
コード例 #7
0
ファイル: bot.py プロジェクト: MacDeth/discobot-py
    def on_about_command(self, event):
        embed = MessageEmbed()
        embed.set_author(name='MacDeth#0420',
            url='https://github.com/MacDeth/discobot-py',
            icon_url='https://macdeth.keybase.pub/avatar.png')
        embed.title = 'About'
        embed.url = 'https://github.com/MacDeth/discobot-py'

        event.msg.reply(embed=embed)
コード例 #8
0
    def about_command(self, event):
        """Gets some basic info about the bot"""
        embed = MessageEmbed()
        embed.set_author(name='Referee', icon_url=self.client.state.me.avatar_url, url='https://github.com/UHCBot/Referee')
        embed.description = self.BOT_DESC
        embed.add_field(name='Uptime', value=humanize.naturaldelta(datetime.utcnow() - STARTED), inline=True)
        embed.description = self.BOT_DESC
        embed.color = 0xf3733a

        event.msg.reply(embed=embed)
コード例 #9
0
ファイル: weather.py プロジェクト: shiftypanda/A2
    def get_base_embed(result):
        """Creates an embed and sets some common properties."""
        embed = MessageEmbed()
        embed.set_author(
            name='Yahoo! Weather',
            url='https://www.yahoo.com/news/weather',
            icon_url='https://s.yimg.com/dh/ap/default/130909/y_200_a.png')
        embed.url = result.print_obj['link'].split('*')[-1]  # Removes RSS URL.
        embed.color = 4194448  # Yahoo! logo's purple.

        return embed
コード例 #10
0
ファイル: reddit.py プロジェクト: spbonez/rowboat
    def send_post(self, config, channel, data):
        if config.mode is FormatMode.PLAIN:
            channel.send_message('**{}**\n{}'.format(
                data['title'],
                'https://reddit.com{}'.format(data['permalink'])
            ))
        else:
            embed = MessageEmbed()

            if 'nsfw' in data and data['nsfw']:
                if not config.nsfw:
                    return
                embed.color = 0xff6961
            else:
                embed.color = 0xaecfc8

            # Limit title to 256 characters nicely
            if len(data['title']) > 256:
                embed.title = data['title'][:253] + '...'
            else:
                embed.title = data['title']

            embed.url = u'https://reddit.com{}'.format(data['permalink'])
            embed.set_author(
                name=data['author'],
                url=u'https://reddit.com/u/{}'.format(data['author'])
            )

            image = None

            if data.get('media'):
                if 'oembed' in data['media']:
                    image = data['media']['oembed']['thumbnail_url']
            elif data.get('preview'):
                if 'images' in data['preview']:
                    image = data['preview']['images'][0]['source']['url']

            if 'selftext' in data and data['selftext']:
                # TODO better place for validation
                sz = min(64, max(config.text_length, 1900))
                embed.description = data['selftext'][:sz]
                if len(data['selftext']) > sz:
                    embed.description += u'...'
                if image:
                    embed.set_thumbnail(url=image)
            elif image:
                embed.set_image(url=image)

            if config.include_stats:
                embed.set_footer(text=emoji.emojize('{} upvotes | {} downvotes | {} comments'.format(
                    data['ups'], data['downs'], data['num_comments']
                )))

            channel.send_message('', embed=embed)
コード例 #11
0
ファイル: reminders.py プロジェクト: jellz/jetski
    def cmd_remind_list(self, event, limit=None, mode='server'):
        user = event.msg.author
        count = Reminder.count_for_user(user.id, event.guild.id)
        total_count = Reminder.count_for_user(user.id)

        embed = MessageEmbed()
        embed.title = '{} reminder{} ({} total)'.format(
            count if mode == 'server' else total_count, 's' if
            (count != 1 and mode == 'server') or
            (total_count != 1 and mode == 'global') else '', total_count)

        embed.set_author(name=u'{}#{}'.format(
            user.username,
            user.discriminator,
        ),
                         icon_url=user.avatar_url)
        embed.color = get_dominant_colors_user(user,
                                               user.get_avatar_url('png'))
        embed.set_footer(text='You can cancel reminders with !r clear [ID]')

        if (count == 0 and mode == 'server') or total_count == 0:
            embed.description = 'You have no upcoming reminders{}.'.format(
                ' in this server. Use `!r list global` to list all your upcoming reminders'
                if total_count > 0 else '')
        else:
            query = Reminder.select(Reminder).where(
                (Reminder.message_id << Reminder.with_message_join(
                    (Message.id, )).where(
                        (Message.author_id == event.author.id) &
                        (Message.guild_id == event.guild.id if mode ==
                         'server' else True)))
                & (Reminder.remind_at >
                   (datetime.utcnow() + timedelta(seconds=1)))).order_by(
                       Reminder.remind_at).limit(limit)

            for reminder in query:
                time = humanize_duration(reminder.remind_at -
                                         datetime.utcnow())
                channel = Message.select().where(
                    Message.id == reminder.message_id).get().channel_id
                channel = self.state.channels.get(channel)

                embed.add_field(
                    name=u'#{} in {}'.format(reminder.id, time),
                    value=u'[`#{}`](https://discordapp.com/channels/{}/{}/{}) {}'
                    .format(
                        channel.name if channel.type != ChannelType.DM else
                        'Jetski', channel.guild_id
                        if channel.type != ChannelType.DM else '@me',
                        channel.id, reminder.message_id, S(reminder.content)))

        return event.msg.reply(embed=embed)
コード例 #12
0
    def jeopardy_command(self, event, args):
        self.log.info('{} executed !jeopardy with args: {}'.format(
            event.author, args))

        if not args.random:
            return

        jservice_base_url = 'http://jservice.io/{}'
        jservice_random = '/api/random'
        jeopardy_response = requests.get(
            jservice_base_url.format(jservice_random)).json()[0]

        from pprint import pprint
        pprint(jeopardy_response)

        jeopardy_q = jeopardy_response['question'].replace('&', 'and')
        jeopardy_a = self.clean_html(jeopardy_response['answer'])
        jeopardy_id = jeopardy_response['id']
        jeopardy_amount = '${}'.format(jeopardy_response['value'])
        jeopardy_category = jeopardy_response['category']['title']

        jeopardy_q = '\n'.join([
            ' '.join(jeopardy_q.split()[s:s + 6])
            for s in range(0, len(jeopardy_q.split()), 6)
        ])

        self.log.info('amount: {}'.format(jeopardy_amount))

        img2txt_url = 'http://api.img4me.com/?text={}&font=impact&size=35&fcolor={}&bcolor=060CE9'
        question_color = 'FFFFFF'
        amount_color = 'D49516'
        question_value = requests.get(
            img2txt_url.format(jeopardy_q, question_color)).text
        amount_value = requests.get(
            img2txt_url.format(jeopardy_amount, amount_color)).text

        embed = MessageEmbed()
        embed.set_author(
            name='Jeopardy!',
            url='http://jservice.io/',
            icon_url=
            'http://jservice.io/assets/trebek-503ecf6eafde622b2c3e2dfebb13cc30.png'
        )
        embed.title = 'Category: {}'.format(jeopardy_category)
        embed.timestamp = pendulum.now().in_tz('America/New_York').isoformat()
        embed.set_thumbnail(url=amount_value)
        embed.set_image(url=question_value)
        embed.set_footer(text='Powered by jservice.io')
        embed.color = '13931798'  # dark yellow (hex: #D49516)

        event.msg.reply(embed=embed)
コード例 #13
0
ファイル: vocal_crews.py プロジェクト: Wizurth/CrewBot
    def generate_invite_embed(self, member: GuildMember,
                              voice_channel: Channel, invitation: Invite,
                              user_message: str):
        category = voice_channel.parent
        formatter = self.get_category_config(category,
                                             'alert_message_formatter')
        join_formatter = self.get_category_config(category,
                                                  'alert_message_join')
        footer = self.get_category_config(category, 'alert_message_footer')

        if user_message is not None:
            alert_message = self.get_category_config(category,
                                                     'alert_message_custom')
            formatted_msg = alert_message.format(user_msg=user_message)
        else:
            formatted_msg = self.get_category_config(category,
                                                     'alert_message_standard')

        invitation_link = "https://discord.gg/{}".format(invitation.code)
        join_msg = join_formatter.format(crew_name=voice_channel.name,
                                         link=invitation_link)

        available_slots = self.get_available_slots(voice_channel)
        if available_slots == -1:
            available_slots_msg = ""
        elif available_slots == 0:
            join_msg = ""
            available_slots_msg = self.get_category_config(
                category, 'alert_message_no_slot')
        elif available_slots == 1:
            available_slots_msg = self.get_category_config(
                category, 'alert_message_one_slot')
        else:
            available_slots_template = self.get_category_config(
                category, 'alert_message_several_slots')
            available_slots_msg = available_slots_template.format(
                slots=available_slots)

        crew_members = self.get_connected_users(voice_channel)
        crew_members_text = ", ".join(
            ["<@!{}>".format(m) for m in crew_members])

        embed = MessageEmbed()
        embed.set_author(name=member.name, icon_url=member.user.avatar_url)
        embed.description = formatter.format(
            msg=formatted_msg,
            join=join_msg,
            available_slots=available_slots_msg,
            crew_members=crew_members_text)
        embed.set_footer(text=footer)
        return embed
コード例 #14
0
 def command_about(self, event):
     embed = MessageEmbed()
     embed.set_author(name='RoPolice',
                      icon_url=self.client.state.me.avatar_url,
                      url='https://www.youtube.com/watch?v=5wFDWP5JwSM')
     embed.description = BOT_INFO
     embed.add_field(name='Servers',
                     value=str(Guild.select().count()),
                     inline=True)
     embed.add_field(name='Uptime',
                     value=humanize.naturaldelta(datetime.utcnow() -
                                                 self.startup),
                     inline=True)
     event.msg.reply(embed=embed)
コード例 #15
0
    def server(self, event, guild_id=None):
        guild: Guild = self.state.guilds.get(
            guild_id) if guild_id else event.guild
        if not guild:
            raise CommandFail('Invalid server')

        embed = MessageEmbed()
        embed.set_author(
            MessageEmbedAuthor(name=guild.name, icon_url=guild.icon_url()))

        # General Abouts
        about_field = MessageEmbedField()
        about_field.name = '**\u276F About**'
        about_text = 'Created by {} ({}) — <t:{}:R>'.format(
            guild.owner, guild.owner.id,
            int(to_datetime(guild.id).replace(tzinfo=pytz.UTC).timestamp()))
        about_text += '\nMembers: {:,}/{:,}'.format(
            guild.approximate_presence_count, guild.member_count)
        about_text += '\nRegion: {}'.format(guild.region)
        about_field.value = about_text
        embed.add_field(about_field)

        # General Counts
        counts_field = MessageEmbedField()
        counts_field.name = '\n**\u276F Counts**'
        text_count = sum(1 for c in list(guild.channels.values())
                         if not c.is_voice and not c.is_thread)
        voice_count = len(guild.channels) - text_count

        counts_field.value = 'Roles: {:,}\nText: {:,}\nVoice: {:,}'.format(
            len(guild.roles), text_count, voice_count)
        embed.add_field(counts_field)

        # Security
        security_field = MessageEmbedField()
        security_field.name = '\n**\u276F Security**'
        security_field.value = 'Verification: {}\nExplicit Content: {}'.format(
            guild.verification_level, guild.explicit_content_filter)
        embed.add_field(security_field)

        # Features
        features_field = MessageEmbedField()
        features_field.name = '\n**\u276F Features**'
        features_field.value = 'Features: {}'.format(', '.join(guild.features))
        embed.add_field(features_field)

        if guild.icon:
            embed.color = get_dominant_colors_guild(guild)
        event.msg.reply('', embed=embed)
コード例 #16
0
    def get_embed(self, star, msg, config):
        # Create the 'header' (non-embed) text
        stars = ':star:'

        if len(star.stars) > 1:
            if len(star.stars) >= config.star_color_max:
                stars = ':star2:'
            stars = stars + ' {}'.format(len(star.stars))

        content = '{} <#{}> ({})'.format(
            stars,
            msg.channel_id,
            msg.id
        )

        # Generate embed section
        embed = MessageEmbed()
        embed.description = msg.content

        if msg.attachments:
            attach = list(msg.attachments.values())[0]
            if attach.url.lower().endswith(('png', 'jpeg', 'jpg', 'gif', 'webp')):
                embed.set_image(url=attach.url)

        if msg.embeds:
            if msg.embeds[0].image.url:
                embed.set_image(url=msg.embeds[0].image.url)
            elif msg.embeds[0].thumbnail.url:
                embed.set_image(url=msg.embeds[0].thumbnail.url)

        author = msg.guild.get_member(msg.author)
        if author:
            embed.set_author(
                name=author.name,
                icon_url=author.user.avatar_url
            )
        else:
            embed.set_author(
                name=msg.author.username,
                icon_url=msg.author.avatar_url)

        embed.add_field(name=u'\u200b', value=(u'→ [Jump to original message]'
            u'(https://discordapp.com/channels/{}/{}/{})'.format(msg.guild.id, msg.channel_id, msg.id)))

        embed.timestamp = msg.timestamp.isoformat()
        embed.color = config.get_color(len(star.stars))

        return content, embed
コード例 #17
0
ファイル: cache_helper.py プロジェクト: Samuel-Maddock/Zilean
    def getZileanEmbed(title="Zilean Bot",
                       footer="Zilean Bot",
                       description="Zilean Bot"):
        embed = MessageEmbed()

        embed.title = title
        embed.description = description
        embed.set_footer(text=footer)

        embed.set_author(
            name="Zilean",
            icon_url="https://i.imgur.com/JreyU9y.png",
            url="https://samuel-maddock.github.io/Zilean/#commands")
        embed.color = 0x59fff9
        embed.timestamp = datetime.utcnow().isoformat()
        return embed
コード例 #18
0
    def cmd_remind_list(self, event, limit=None, mode=None):
        user = event.msg.author
        count = Reminder.count_for_user(user.id)
        avatar = u'https://cdn.discordapp.com/avatars/{}/{}.png'.format(
            user.id,
            user.avatar,
        )

        embed = MessageEmbed()
        embed.title = '{} reminder{}'.format(count, '' if count == 1 else 's')

        embed.set_author(name=u'{}#{}'.format(
            user.username,
            user.discriminator,
        ), icon_url=avatar)
        embed.color = get_dominant_colors_user(user, avatar)
        embed.set_footer(text='You can cancel reminders with !r clear [ID]')

        if count == 0:
            embed.description = 'You have no upcoming reminders.'
        else:
            query = Reminder.select(Reminder).where(
                (Reminder.message_id << Reminder.with_message_join((Message.id, )).where(
                    Message.author_id == event.author.id
                )) & (Reminder.remind_at > (datetime.utcnow() + timedelta(seconds=1)))
            ).order_by(Reminder.remind_at).limit(limit)

            for reminder in query:
                time = humanize_duration(reminder.remind_at - datetime.utcnow())
                channel = Message.select().where(Message.id == reminder.message_id).get().channel_id
                channel = self.state.channels.get(channel)

                embed.add_field(
                    name=u'#{} in {}'.format(
                        reminder.id,
                        time
                    ),
                    value=u'[`#{}`](https://discordapp.com/channels/{}/{}/{}) {}'.format(
                        channel.name if channel.type != ChannelType.DM else 'Jetski',
                        channel.guild_id if channel.type != ChannelType.DM else '@me',
                        channel.id,
                        reminder.message_id,
                        S(reminder.content)
                    )
                )

        return event.msg.reply(embed=embed)
コード例 #19
0
ファイル: starboard.py プロジェクト: DeJayDev/speedboat
    def get_embed(self, star, msg, config):
        # Create the 'header' (non-embed) text
        stars = ':star:'

        if len(star.stars) > 1:
            if len(star.stars) >= config.star_color_max:
                stars = ':star2:'
            stars = stars + ' {}'.format(len(star.stars))

        content = '**{}** <#{}> ({})'.format(stars, msg.channel_id, msg.id)

        # Generate embed section
        embed = MessageEmbed()
        embed.description = '{}'.format(msg.content)

        if msg.attachments:
            attach = list(msg.attachments.values())[0]
            if attach.url.lower().endswith(
                ('png', 'jpeg', 'jpg', 'gif', 'webp')):
                embed.set_image(url=attach.url)

        if msg.embeds:
            if msg.embeds[0].image.url:
                embed.set_image(url=msg.embeds[0].image.url)
            elif msg.embeds[0].thumbnail.url:
                embed.set_image(url=msg.embeds[0].thumbnail.url)

        author = msg.guild.get_member(msg.author)
        if author:
            embed.set_author(name=author, icon_url=author.user.avatar_url)
        else:
            embed.set_author(name=msg.author, icon_url=msg.author.avatar_url)

        embed.timestamp = msg.timestamp.isoformat()
        embed.color = config.get_color(len(star.stars))

        row = ActionRow()
        row.add_component(label='Jump to Message',
                          type=ComponentTypes.BUTTON,
                          style=ButtonStyles.LINK,
                          url='https://discord.com/channels/{}/{}/{}'.format(
                              msg.guild.id, msg.channel_id, msg.id))

        return content, embed, row
コード例 #20
0
ファイル: common_cmds.py プロジェクト: One-Nub/Who-Am-I
    def on_info_command(self, event):
        """Displays some info about the bot, or me!"""
        infoEmbed = MessageEmbed()
        github = "https://github.com/One-Nub/Who-Am-I"
        myPfpImg = "https://i.lensdump.com/i/WDsOXb.png"
        botPfpImg = "https://i.lensdump.com/i/WDs4G5.png"
        botInvite = ("https://discordapp.com/api/oauth2/authorize?client_id=" +
                     "592796597209792542&permissions=380096&scope=bot")

        infoEmbed.title = "Welcome to **Who Am I**!"
        infoEmbed.url = github
        infoEmbed.color = 0x8DD0E1
        infoEmbed.description = (
            "Hey there! This bot was created for the June 2019 " +
            "Discord Hackathon!")
        infoEmbed.set_thumbnail(url=botPfpImg)
        infoEmbed.set_author(name="Nub#8399", icon_url=myPfpImg)
        infoEmbed.timestamp = datetime.utcnow().isoformat()

        infoEmbed.add_field(
            name="What is/was this Hackathon?",
            value=
            "This was a week where developers, such as myself, would create"
            " either a bot of some sort, "
            "or something creative (art, music, etc...), "
            "and we would then submit our creations by the end of the week!",
            inline=False)

        infoEmbed.add_field(
            name="So what does this bot do?",
            value=
            "This bot is meant to make it easier to learn about people and share"
            "info about yourself!"
            "\nThis is done by letting users give info to the bot"
            "& then displaying that info with a simple command!",
            inline=False)

        infoEmbed.add_field(name="View my github here!",
                            value=github,
                            inline=False)
        infoEmbed.add_field(name="Invite me here!",
                            value="[Invite me!]({})".format(botInvite),
                            inline=False)
        event.msg.reply(embed=infoEmbed)
コード例 #21
0
    def get_embed(self, info):
        flair = info.flair.lower().replace(MAORITANGA.decode('utf8'), 'a')
        colour = int(self.flair_colours.get(flair, self.default_flair_colour),
                     16)

        embed = MessageEmbed()
        embed.title = textwrap.shorten(u"[{}] {}".format(
            info.flair, info.title),
                                       width=256,
                                       placeholder="...")
        embed.url = "https://reddit.com{}".format(info.url)
        embed.color = colour
        embed.set_thumbnail(url=info.thumbnail)
        embed.set_author(name=info.author,
                         url="https://reddit.com/u/{}".format(info.author))
        embed.timestamp = datetime.fromtimestamp(info.time,
                                                 timezone.utc).isoformat()

        return embed
コード例 #22
0
  def create_embed(self, item_name, item_id, median_price, formatted_item_name, stock, last_5):
    print formatted_item_name
    formatted_item_name = urllib.quote_plus(formatted_item_name)

    embed = MessageEmbed()
    embed.set_author(name=item_name,
                     url='{}{}'.format(WIKI_URL, formatted_item_name),
                     icon_url='{}{}.png'.format(IMAGE_URL, item_id))

    five_price = five_date = ''
    for x in last_5:
      five_price += '\n{}'.format(x['sale'])
      five_date += '\n{}'.format(datetime.fromtimestamp(x['sell_date']))

    embed.add_field(name='Current Stock', value=stock, inline=False)
    embed.add_field(name='Last 5 Sold', value=five_price, inline=True)
    embed.add_field(name='Sell Date', value=five_date, inline=True)
    return {
      'embed': embed
    }
コード例 #23
0
ファイル: core.py プロジェクト: TrissieTheHusky/speedboat
 def command_about(self, event):
     import subprocess
     embed = MessageEmbed()
     embed.set_author(name='Speedboat',
                      icon_url=self.client.state.me.avatar_url,
                      url='http://row.swvn.io/')
     embed.description = BOT_INFO
     embed.add_field(name='Servers',
                     value=str(len(self.state.guilds)),
                     inline=True)
     embed.add_field(name='Uptime',
                     value=humanize.naturaldelta(datetime.utcnow() -
                                                 self.startup),
                     inline=True)
     embed.add_field(name='Version',
                     value=subprocess.check_output(
                         ["git", "describe",
                          "--always"]).strip().decode("utf-8"),
                     inline=True)
     event.msg.reply(embed=embed)
コード例 #24
0
 def on_red(self, event, character):
     try:
         dbref = db.reference('references/{}'.format(character.lower()))
         data = dbref.get()
         if data:
             embed = MessageEmbed()
             embed.set_author(name=data.get('owner', 'Unknown owner'),
                              url=data.get('ownerURL'),
                              icon_url=data.get('ownerAvatar'))
             embed.title = data.get('name', 'Unnamed')
             if data.get('description'):
                 embed.description = data['description']
             embed.color = data['color']
             if data.get('image'):
                 embed.set_image(url=data['image'])
             if data.get('thumbnail'):
                 embed.set_thumbnail(url=data['thumbnail'])
             event.msg.reply(embed=embed)
         else:
             event.msg.reply("Not found")
     except Exception as e:
         event.msg.reply(str(e))
コード例 #25
0
ファイル: core.py プロジェクト: s0hv/rowboat
 def command_about(self, event):
     embed = MessageEmbed()
     embed.set_author(name='Planeboat',
                      icon_url=self.client.state.me.avatar_url,
                      url='https://rowboat.party/')
     embed.description = BOT_INFO
     embed.add_field(name='Servers',
                     value=str(Guild.select().count()),
                     inline=True)
     embed.add_field(name='Uptime',
                     value=humanize.naturaldelta(datetime.utcnow() -
                                                 self.startup),
                     inline=True)
     #global_admin = rdb.sismember('global_admins', event.author.id)
     #_usr = User.select().where(User.user_id == event.author.id)
     #if len(_usr) == 1:
     #    global_admin = _usr[0].admin
     global_admin = self.is_global_admin(event.author.id)
     if global_admin:
         embed.add_field(name='Admin',
                         value='You are a rowboat global admin!')
     event.msg.reply(embed=embed)
コード例 #26
0
ファイル: core.py プロジェクト: OGNova/airplane
    def dm_listener(self, event):
        from rowboat.util.images import get_dominant_colors_user
        global_admin = rdb.sismember('global_admins', event.author.id)
        if global_admin or event.author.id == 351097525928853506:
            return
        if event.guild == None:
            MODIFIER_GRAVE_ACCENT = u'\u02CB'
            msg = event
            message_content = msg.content.replace('`', MODIFIER_GRAVE_ACCENT)
            author_id = msg.author.id
            discrim = str(msg.author.discriminator)
            avatar_name = msg.author.avatar
            content = []
            embed = MessageEmbed()

            if not avatar_name:
                avatar = default_color(str(msg.author.default_avatar))
            elif avatar_name.startswith('a_'):
                avatar = u'https://cdn.discordapp.com/avatars/{}/{}.gif'.format(
                    author_id, avatar_name)
            else:
                avatar = u'https://cdn.discordapp.com/avatars/{}/{}.png'.format(
                    author_id, avatar_name)
            embed.set_author(name='{} ({})'.format(msg.author, author_id),
                             icon_url=avatar)
            embed.set_thumbnail(url=avatar)

            content.append(u'**\u276F New DM:**')
            content.append(u'Content: ```{}```'.format(message_content))
            embed.description = '\n'.join(content)
            embed.timestamp = datetime.utcnow().isoformat()
            try:
                embed.color = get_dominant_colors_user(msg.author, avatar)
            except:
                embed.color = '00000000'
            self.bot.client.api.channels_messages_create('540020613272829996',
                                                         '',
                                                         embed=embed)
コード例 #27
0
ファイル: quote.py プロジェクト: Jonfirexbox/b1nb0t
    def command_quote(self, event, message_raw):
        channel_id, message_id = parse_message_arg(event.channel_id, message_raw)
        message = self.state.channels.get(channel_id).get_message(message_id)

        embed = MessageEmbed()
        embed.set_author(
            name=message.author.username,
            icon_url=message.author.avatar_url,
        )
        url = 'https://discordapp.com/channels/{}/{}/{}'.format(
            message.channel.guild.id,
            message.channel.id,
            message.id,
        )
        embed.description = message.content + '\n\n[view]({})'.format(
            url
        )
        embed.set_footer(text="#{} in {}".format(
            message.channel.name,
            message.channel.guild.name,
        ))
        embed.timestamp = message.timestamp.isoformat()
        event.msg.reply(embed=embed)
コード例 #28
0
ファイル: utilities.py プロジェクト: golu701/jetski
    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)
コード例 #29
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)
コード例 #30
0
ファイル: utilities.py プロジェクト: suufi/rowboat
    def info(self, event, 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
        infractions = Infraction.select(
            Infraction.guild_id, fn.COUNT('*')).where(
                (Infraction.user_id == user.id)).group_by(
                    Infraction.guild_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(infractions, timeout=10)
        tags = to_tags(guild_id=event.msg.guild.id)

        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)))

        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)