Python discord.Emoji() Examples

The following are 28 code examples of discord.Emoji(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module discord , or try the search function .
Example #1
Source File: emote.py    From apex-sigma-core with GNU General Public License v3.0 7 votes vote down vote up
def get_emote(emoji):
    """
    Gets a specific emote by lookup.
    :param emoji: The emote to get.
    :type emoji: str or discord.Emoji
    :return:
    :rtype: (str, int)
    """
    lookup, eid = emoji, None
    if ':' in emoji:
        # matches custom emote
        server_match = re.search(r'<a?:(\w+):(\d+)>', emoji)
        # matches global emote
        custom_match = re.search(r':(\w+):', emoji)
        if server_match:
            lookup, eid = server_match.group(1), server_match.group(2)
        elif custom_match:
            lookup, eid = custom_match.group(1), None
        else:
            lookup, eid = emoji.split(':')
        try:
            eid = int(eid)
        except (ValueError, TypeError):
            eid = None
    return lookup, eid 
Example #2
Source File: rolereaction.py    From modmail-plugins with GNU General Public License v3.0 6 votes vote down vote up
def add(self, ctx, emoji: discord.Emoji, role: discord.Role):
        emote = emoji.name if emoji.id is None else emoji.id

        if emote in self.roles:
            updated = True
        else:
            updated = False
        self.roles[emote] = role.id

        await self.db.find_one_and_update(
            {"_id": "config"}, {"$set": {"roles": self.roles}}, upsert=True
        )

        await ctx.send(
            f"Successfully {'updated'if updated else 'pointed'} {emoji} towards {role.name}"
        ) 
Example #3
Source File: raffleicon.py    From apex-sigma-core with GNU General Public License v3.0 6 votes vote down vote up
def get_matching_emote(guild, emote):
    """
    Gets a matching emote from the given guild.
    :param guild: The guild to search.
    :type guild: discord.Guild
    :param emote: The full emote string to look for.
    :type emote: str
    :return:
    :rtype: discord.Emoji
    """
    emote_name = emote.split(':')[1]
    matching_emote = None
    for emote in guild.emojis:
        if emote.name == emote_name:
            matching_emote = emote
    return matching_emote 
Example #4
Source File: fetch.py    From apex-sigma-core with GNU General Public License v3.0 6 votes vote down vote up
def make_emoji_data(emj):
        """
        Makes a data dict for storage for a custom emoji.
        :param emj: The emoji to store.
        :type emj: discord.Emoji
        :rtype: dict
        """
        data = {
            "available": emj.available,
            "managed": emj.managed,
            "name": emj.name,
            "roles": [FetchHelper.make_role_data(role) for role in emj.roles],
            "require_colons": emj.require_colons,
            "animated": emj.animated,
            "id": str(emj.id)
        }
        return data 
Example #5
Source File: role-assignment.py    From modmail-plugins with GNU General Public License v3.0 6 votes vote down vote up
def remove(self, ctx, emoji: discord.Emoji):
        """Remove a clickable emoji from each new message."""

        config = await self.db.find_one({"_id": "role-config"})

        if config is None:
            return await ctx.send("There are no emoji set for this server.")

        emoji_dict = config["emoji"]

        try:
            del emoji_dict[f"<:{emoji.name}:{emoji.id}>"]
        except KeyError:
            return await ctx.send("That emoji is not configured")

        await self.db.update_one({"_id": "role-config"}, {"$set": {"emoji": emoji_dict}})

        await ctx.send(f"I successfully deleted <:{emoji.name}:{emoji.id}>.") 
Example #6
Source File: starboard.py    From Trusty-cogs with MIT License 6 votes vote down vote up
def set_emoji(
        self, ctx: commands.Context, starboard: StarboardExists, emoji: Union[discord.Emoji, str]
    ) -> None:
        """
            Set the emoji for the starboard

            `<name>` is the name of the starboard to change the emoji for
            `<emoji>` must be an emoji on the server or a default emoji
        """
        guild = ctx.guild
        if type(emoji) == discord.Emoji:
            if emoji not in guild.emojis:
                await ctx.send(_("That emoji is not on this guild!"))
                return
        self.starboards[ctx.guild.id][starboard.name].emoji = str(emoji)
        await self._save_starboards(guild)
        msg = _("{emoji} set for starboard {name}").format(emoji=emoji, name=starboard.name)
        await ctx.send(msg) 
Example #7
Source File: serverlog.py    From NabBot with Apache License 2.0 6 votes vote down vote up
def on_guild_emojis_update(self, guild: discord.Guild, before: List[discord.Emoji],
                                     after: List[discord.Emoji]):
        """Called every time an emoji is created, deleted or updated."""
        def emoji_repr(_emoji: discord.Emoji):
            fix = ":" if _emoji.require_colons else ""
            return f"{fix}{_emoji.name}{fix}"
        embed = discord.Embed(colour=COLOUR_EMOJI_UPDATE)
        emoji: discord.Emoji = None
        # Emoji deleted
        if len(before) > len(after):
            emoji = discord.utils.find(lambda e: e not in after, before)
            if emoji is None:
                return
            embed.set_author(name=f"{emoji_repr(emoji)} (ID: {emoji.id})", icon_url=emoji.url)
            embed.description = f"Emoji deleted."
            action = discord.AuditLogAction.emoji_delete
        # Emoji added
        elif len(after) > len(before):
            emoji = discord.utils.find(lambda e: e not in before, after)
            if emoji is None:
                return
            embed.set_author(name=f"{emoji_repr(emoji)} (ID: {emoji.id})", icon_url=emoji.url)
            embed.description = f"Emoji added."
            action = discord.AuditLogAction.emoji_create
        else:
            old_name = ""
            for new_emoji in after:
                for old_emoji in before:
                    if new_emoji == old_emoji and new_emoji.name != old_emoji.name:
                        old_name = old_emoji.name
                        emoji = new_emoji
                        break
            if emoji is None:
                return
            embed.set_author(name=f"{emoji_repr(emoji)} (ID: {emoji.id})", icon_url=emoji.url)
            embed.description = f"Emoji renamed from `{old_name}` to `{emoji.name}`"
            action = discord.AuditLogAction.emoji_update
        if emoji:
            entry = await self.get_audit_entry(guild, action, emoji)
            if entry:
                embed.set_footer(text="{0.name}#{0.discriminator}".format(entry.user),
                                 icon_url=get_user_avatar(entry.user))
            await self.bot.send_log_message(guild, embed=embed) 
Example #8
Source File: emoji.py    From Penny-Dreadful-Tools with GNU General Public License v3.0 5 votes vote down vote up
def find_emoji(emoji: str, client: Client) -> Optional[Emoji]:
    try:
        for guild in client.guilds:
            emojis = guild.emojis
            res = next((x for x in emojis if x.name == emoji), None)
            if res is not None:
                return res
        return None
    except AttributeError:
        return None 
Example #9
Source File: rolereaction.py    From modmail-plugins with GNU General Public License v3.0 5 votes vote down vote up
def remove(self, ctx, emoji: discord.Emoji):
        """Remove a role from the role reaction list"""
        emote = emoji.name if emoji.id is None else emoji.id

        if emote not in self.roles:
            await ctx.send("The Given Emote Was Not Configured")
            return

        self.roles.pop(emote)

        await self.db.find_one_and_update(
            {"_id": "config"}, {"$set": {"roles": self.roles}}, upsert=True
        )

        await ctx.send(f"Removed {emoji} from rolereaction list")
        return 
Example #10
Source File: role-assignment.py    From modmail-plugins with GNU General Public License v3.0 5 votes vote down vote up
def add(self, ctx, emoji: discord.Emoji, *, role: discord.Role):
        """Add a clickable emoji to each new message."""

        config = await self.db.find_one({"_id": "role-config"})

        if config is None:
            await self.db.insert_one({"_id": "role-config", "emoji": {}})

            config = await self.db.find_one({"_id": "role-config"})

        emoji_dict = config["emoji"]

        try:
            emoji_dict[str(emoji.id)]
            failed = True
        except KeyError:
            failed = False

        if failed:
            return await ctx.send("That emoji already assigns a role.")

        emoji_dict[f"<:{emoji.name}:{emoji.id}>"] = role.name

        await self.db.update_one({"_id": "role-config"}, {"$set": {"emoji": emoji_dict}})

        await ctx.send(f'I successfully pointed <:{emoji.name}:{emoji.id}> to "{role.name}"') 
Example #11
Source File: stats.py    From nano-chan with MIT License 5 votes vote down vote up
def stats_emoji(self, ctx):
        found_emojis = []
        total_reactions = defaultdict(int)
        emoji_count = defaultdict(int)
        check_date = datetime.datetime.now() + datetime.timedelta(-30)
        for channel in ctx.message.guild.channels:
            if isinstance(channel, discord.TextChannel):
                self.bot.logger.info(f'Starting on channel: {channel.name}')
                if channel.id in self.bot.emoji_ignore_channels:
                    continue
                try:
                    message_history = channel.history(
                        limit=None, after=check_date)
                except Exception as e:
                    self.bot.logger.warning(
                        f'Issue getting channel history: {e}')
                self.bot.logger.info(f'Parsing messages: {channel.name}')        
                async for message in message_history:
                    for word in message.content.split():
                        if '<:' in word:
                            found_emojis.append(word)
                    for reaction in message.reactions:
                        total_reactions[reaction.emoji] += reaction.count
        self.bot.logger.info(f'Counting emojis: {channel.name}')
        for emoji_id in found_emojis:
            for emoji in ctx.message.guild.emojis:
                if emoji_id == str(emoji):
                    emoji_count[emoji] += 1
        for emoji in ctx.message.guild.emojis:
            if emoji in total_reactions:
                emoji_count[emoji] += total_reactions[emoji]
        temp_str = 'Emoji use over last 30 days:\n'
        for key in sorted(emoji_count, key=emoji_count.get, reverse=True):
            temp_str += f'{key}: {emoji_count[key]}\n'
        await ctx.send(temp_str) 
Example #12
Source File: stats.py    From nano-chan with MIT License 5 votes vote down vote up
def emojis(self, ctx, days: int=1):
        count_dict = defaultdict(int)
        desc_over = None
        for emoji in ctx.guild.emojis:
            try:
                count_dict[emoji] = await \
                    self.bot.pg_controller.get_emoji_count(
                        emoji, days, self.bot.logger
                    )
            except Exception as e:
                self.bot.logger(f'Error getting emoji info:{e}')
        desc = ''
        for key in sorted(count_dict, key=count_dict.get, reverse=True):
            desc += f'{key}: {count_dict[key]}\n'
        if len(desc) > 2048:
            desc_over = ''
            count = 0
            temp = desc.split('\n')
            desc = ''
            for emoji in temp:
                count += len(emoji) + 1
                if count > 2047:
                    desc_over += f'{emoji}\n'
                else:
                    desc += f'{emoji}\n'
        local_embed = discord.Embed(
            title=f'Emoji use over the past {days} day/s:',
            description=desc
        )
        if desc_over:
            local_embed.add_field(
                name='------cont-----',
                value=desc_over
            )
        await ctx.send(embed=local_embed) 
Example #13
Source File: stats.py    From nano-chan with MIT License 5 votes vote down vote up
def emoji(self, ctx, emoji: discord.Emoji, days: int=-1):
        """
        Returns stats on an Emoji
        """
        emoji_stats = await self.bot.pg_controller.get_emoji_stats(emoji, days)
        user_count = defaultdict(int)
        target_count = defaultdict(int)
        total_count = 0
        reaction_count = 0
        for row in emoji_stats:
            if row['channel_id'] in [297834395945926667, 329500167118258176, 294248007422181376, 148606162810568704, 227385793637777408, 264704915845283840, 191102386633179136, 378684962934751239, 232371423069339648, 343953048940314625]: #nsfw-roleplay, meta, brainpower
                continue
            user_count[row['user_id']] += 1
            total_count += 1
            if row['reaction']:
                target_count[row['target_id']] += 1
                reaction_count += 1
        day_str = f'in the last {days} days' if days != -1 else f'since forever'
        temp_str = f'Emoji used in messages {day_str}: {total_count-reaction_count}\n'
        temp_str += f'Emoji used in reactions {day_str}: {reaction_count}\n\n'
        temp_str += f'Top 5 users {day_str}:\n--------\n'
        for key in sorted(user_count, key=user_count.get, reverse=True)[:5]:
            user_t = self.bot.get_user(key)
            if user_t:
                temp_str += f'**{user_t.name}**#{user_t.discriminator}: {user_count[key]}\n'
            else:
                temp_str += f'**{key}**: {user_count[key]}\n'
        temp_str += f'\n\nTop 5 targets {day_str}:\n--------\n'
        for key in sorted(target_count, key=target_count.get, reverse=True)[:5]:
            user_t = self.bot.get_user(key)
            if user_t:
                temp_str += f'**{user_t.name}**#{user_t.discriminator}: {target_count[key]}\n'
            else:
                temp_str += f'**{key}**: {target_count[key]}\n'
        local_embed = discord.Embed(
            title=f'Emoji usage for {emoji}',
            description=temp_str
        )
        await ctx.send(embed=local_embed) 
Example #14
Source File: serverstats.py    From Trusty-cogs with MIT License 5 votes vote down vote up
def emoji(
        self, ctx: commands.Context, emoji: Union[discord.Emoji, discord.PartialEmoji, str]
    ) -> None:
        """
            Post a large size emojis in chat
        """
        await ctx.channel.trigger_typing()
        if type(emoji) in [discord.PartialEmoji, discord.Emoji]:
            d_emoji = cast(discord.Emoji, emoji)
            ext = "gif" if d_emoji.animated else "png"
            url = "https://cdn.discordapp.com/emojis/{id}.{ext}?v=1".format(id=d_emoji.id, ext=ext)
            filename = "{name}.{ext}".format(name=d_emoji.name, ext=ext)
        else:
            try:
                """https://github.com/glasnt/emojificate/blob/master/emojificate/filter.py"""
                cdn_fmt = "https://twemoji.maxcdn.com/2/72x72/{codepoint:x}.png"
                url = cdn_fmt.format(codepoint=ord(str(emoji)))
                filename = "emoji.png"
            except TypeError:
                await ctx.send(_("That doesn't appear to be a valid emoji"))
                return
        try:
            async with aiohttp.ClientSession() as session:
                async with session.get(url) as resp:
                    image = BytesIO(await resp.read())
        except Exception:
            await ctx.send(_("That doesn't appear to be a valid emoji"))
            return
        file = discord.File(image, filename=filename)
        await ctx.send(file=file) 
Example #15
Source File: db.py    From EmoteCollector with GNU Affero General Public License v3.0 5 votes vote down vote up
def __eq__(self, other):
		return self.id == other.id and isinstance(other, (type(self), discord.PartialEmoji, discord.Emoji)) 
Example #16
Source File: context.py    From EmoteCollector with GNU Affero General Public License v3.0 5 votes vote down vote up
def try_add_reaction(self,
		emoji: discord.Emoji,
		message: discord.Message = None,
		fallback_message=''
	):
		"""Try to add a reaction to the message. If it fails, send a message instead."""
		if message is None:
			message = self.message

		try:
			await message.add_reaction(strip_angle_brackets(emoji))
		except discord.Forbidden:
			await self.send(f'{emoji} {fallback_message}') 
Example #17
Source File: command.py    From apex-sigma-core with GNU General Public License v3.0 5 votes vote down vote up
def respond_with_emote(message, icon):
        """
        Responds to a message with an emote reaction.
        :type message: discord.Message
        :type icon: discord.Emoji or str
        :param message: The message to respond to with an emote.
        :param icon: The emote to react with to the message.
        :return:
        """
        try:
            await message.add_reaction(icon)
        except discord.DiscordException:
            pass 
Example #18
Source File: karma.py    From rubbergod with GNU General Public License v3.0 5 votes vote down vote up
def test_emoji(db_emoji: bytearray, server_emoji: Emoji):
    try:
        custom_emoji = int(db_emoji)
        return custom_emoji == server_emoji.id
    except ValueError:
        return False 
Example #19
Source File: converter.py    From discord.py with MIT License 5 votes vote down vote up
def convert(self, ctx, argument):
        match = self._get_id_match(argument) or re.match(r'<a?:[a-zA-Z0-9\_]+:([0-9]+)>$', argument)
        result = None
        bot = ctx.bot
        guild = ctx.guild

        if match is None:
            # Try to get the emoji by name. Try local guild first.
            if guild:
                result = discord.utils.get(guild.emojis, name=argument)

            if result is None:
                result = discord.utils.get(bot.emojis, name=argument)
        else:
            emoji_id = int(match.group(1))

            # Try to look up emoji by id.
            if guild:
                result = discord.utils.get(guild.emojis, id=emoji_id)

            if result is None:
                result = discord.utils.get(bot.emojis, id=emoji_id)

        if result is None:
            raise BadArgument('Emoji "{}" not found.'.format(argument))

        return result 
Example #20
Source File: converters.py    From Trusty-cogs with MIT License 4 votes vote down vote up
def convert(self, ctx: commands.Context, argument: str) -> Union[discord.Emoji, str]:
        match = self._get_id_match(argument) or re.match(
            r"<a?:[a-zA-Z0-9\_]+:([0-9]+)>$|(:[a-zA-z0-9\_]+:$)", argument
        )
        result = None
        bot = ctx.bot
        guild = ctx.guild
        if match is None:
            # Try to get the emoji by name. Try local guild first.
            if guild:
                result = discord.utils.get(guild.emojis, name=argument)

            if result is None:
                result = discord.utils.get(bot.emojis, name=argument)
        elif match.group(1):
            emoji_id = int(match.group(1))

            # Try to look up emoji by id.
            if guild:
                result = discord.utils.get(guild.emojis, id=emoji_id)

            if result is None:
                result = discord.utils.get(bot.emojis, id=emoji_id)
        else:
            emoji_name = str(match.group(2)).replace(":", "")

            if guild:
                result = discord.utils.get(guild.emojis, name=emoji_name)

            if result is None:
                result = discord.utils.get(bot.emojis, name=emoji_name)
        if type(result) is discord.Emoji:
            result = str(result)[1:-1]

        if result is None:
            try:
                await ctx.message.add_reaction(argument)
                result = argument
            except Exception:
                raise BadArgument(_("`{}` is not an emoji I can use.").format(argument))

        return result 
Example #21
Source File: extendedmodlog.py    From Trusty-cogs with MIT License 4 votes vote down vote up
def _set_event_emoji(
        self, ctx: commands.Context, emoji: Union[discord.Emoji, str], *events: EventChooser,
    ) -> None:
        """
            Set the emoji used in text modlogs.

            `new_emoji` can be any discord emoji or unicode emoji the bot has access to use.

            `[events...]` must be one of the following options (more than one event can be provided at once):
                `message_edit`
                `message_delete`
                `user_change`
                `role_change`
                `role_create`
                `role_delete`
                `voice_change`
                `user_join`
                `user_left`
                `channel_change`
                `channel_create`
                `channel_delete`
                `guild_change`
                `emoji_change`
                `commands_used`

                **Requires Red 3.3 and discord.py 1.3**
                `invite_created`
                `invite_deleted`
        """
        if len(events) == 0:
            return await ctx.send(_("You must provide which events should be included."))
        if ctx.guild.id not in self.settings:
            self.settings[ctx.guild.id] = inv_settings
        if isinstance(emoji, str):
            try:
                await ctx.message.add_reaction(emoji)
            except discord.errors.HTTPException:
                return await ctx.send(_("{emoji} is not a valid emoji.").format(emoji=emoji))
        new_emoji = str(emoji)
        for event in events:
            self.settings[ctx.guild.id][event]["emoji"] = new_emoji
            await self.config.guild(ctx.guild).set_raw(
                event, value=self.settings[ctx.guild.id][event]
            )
        await ctx.send(
            _("{event} emoji has been set to {new_emoji}").format(
                event=humanize_list(events), new_emoji=str(new_emoji)
            )
        ) 
Example #22
Source File: starboard.py    From Trusty-cogs with MIT License 4 votes vote down vote up
def setup_starboard(
        self,
        ctx: commands.Context,
        name: str,
        channel: discord.TextChannel = None,
        emoji: Union[discord.Emoji, str] = "⭐",
    ) -> None:
        """
            Create a starboard on this server

            `<name>` is the name for the starboard and will be lowercase only
            `[channel]` is the channel where posts will be made defaults to current channel
            `[emoji=⭐]` is the emoji that will be used to add to the starboard defaults to ⭐
        """
        guild = ctx.message.guild
        name = name.lower()
        if channel is None:
            channel = ctx.message.channel
        if type(emoji) == discord.Emoji:
            if emoji not in guild.emojis:
                await ctx.send(_("That emoji is not on this guild!"))
                return
        if not channel.permissions_for(guild.me).send_messages:
            send_perms = _("I don't have permission to post in ")

            await ctx.send(send_perms + channel.mention)
            return

        if not channel.permissions_for(guild.me).embed_links:
            embed_perms = _("I don't have permission to embed links in ")
            await ctx.send(embed_perms + channel.mention)
            return
        if guild.id not in self.starboards:
            self.starboards[guild.id] = {}
        starboards = self.starboards[guild.id]
        if name in starboards:
            await ctx.send(_("{name} starboard name is already being used").format(name=name))
            return
        starboard = StarboardEntry(name, channel.id, str(emoji))
        starboards[name] = starboard
        await self._save_starboards(guild)
        msg = _("Starboard set to {channel} with emoji {emoji}").format(
            channel=channel.mention, emoji=emoji
        )
        await ctx.send(msg) 
Example #23
Source File: info.py    From NabBot with Apache License 2.0 4 votes vote down vote up
def emoji_info(self, ctx: NabCtx, *, emoji: discord.Emoji = None):
        """Shows information about an emoji, or shows all emojis.

        If the command is used with no arguments, all the server emojis are shown.

        If an emoji, its id or name is provided, it will show more information about it.

        Only emojis in the current servers can be checked."""
        if emoji is not None:
            embed = discord.Embed(title=emoji.name, timestamp=emoji.created_at, color=discord.Color.blurple())
            embed.set_thumbnail(url=emoji.url)
            embed.set_footer(text="Created at")
            embed.add_field(name="ID", value=emoji.id)
            embed.add_field(name="Usage", value=f"`{emoji}`")
            embed.add_field(name="Attributes", inline=False,
                            value=f"{ctx.tick(emoji.managed)} Twitch managed\n"
                                  f"{ctx.tick(emoji.require_colons)} Requires colons\n"
                                  f"{ctx.tick(len(emoji.roles) > 0)} Role limited")
            return await ctx.send(embed=embed)

        emojis: List[discord.Emoji] = ctx.guild.emojis
        if not emojis:
            return await ctx.send("This server has no custom emojis.")
        normal = [str(e) for e in emojis if not e.animated]
        animated = [str(e) for e in emojis if e.animated]
        embed = discord.Embed(title="Custom Emojis", color=discord.Color.blurple())
        if normal:
            emojis_str = "\n".join(normal)
            fields = split_message(emojis_str, FIELD_VALUE_LIMIT)
            for i, value in enumerate(fields):
                if i == 0:
                    name = f"Regular ({len(normal)})"
                else:
                    name = "\u200F"
                embed.add_field(name=name, value=value.replace("\n", ""))
        if animated:
            emojis_str = "\n".join(animated)
            fields = split_message(emojis_str, FIELD_VALUE_LIMIT)
            for i, value in enumerate(fields):
                if i == 0:
                    name = f"Animated (Nitro required) ({len(animated)})"
                else:
                    name = "\u200F"
                embed.add_field(name=name, value=value.replace("\n", ""))
        await ctx.send(embed=embed)

    # TODO: Implement this command the proper discord.py way 
Example #24
Source File: exception_handling.py    From jishaku with MIT License 4 votes vote down vote up
def attempt_add_reaction(msg: discord.Message, reaction: typing.Union[str, discord.Emoji])\
        -> typing.Optional[discord.Reaction]:
    """
    Try to add a reaction to a message, ignoring it if it fails for any reason.

    :param msg: The message to add the reaction to.
    :param reaction: The reaction emoji, could be a string or `discord.Emoji`
    :return: A `discord.Reaction` or None, depending on if it failed or not.
    """
    try:
        return await msg.add_reaction(reaction)
    except discord.HTTPException:
        pass 
Example #25
Source File: stats.py    From nano-chan with MIT License 4 votes vote down vote up
def top_emoij(self, ctx, emoji: discord.Emoji, days: int=-1, channel=None):
        """
        Returns top post in timespan with reacts
        """
        day_str = f'in the last {days} days' if days != -1 else f'since forever'
        all_records = await self.bot.pg_controller.get_top_post_by_emoji(
            emoji, days, channel
        )
        l_embed = discord.Embed(
            title=f'Top 3 Posts with {emoji} reacts {day_str}',
            desc=f'___'
        )
        for index, record in enumerate(all_records):
            channel = self.bot.get_channel(record['ch_id'])
            embed_image = False
            if channel.id in [183215451634008065]: 
                embed_image = True
            if channel.id in [259728514914189312, 220762067739738113, 230958006701916160, 304366022276939776]:
                return
            try:
                message = await channel.fetch_message(record['id'])
                if len(message.clean_content) > 600:
                    msg_content = f'{message.clean_content[:500]} ... `(message shortened)`'
                else:
                    msg_content = f'{message.clean_content[:500]}' if message.content != '' else ''
                msg_str = f'`Author`: {message.author.mention} ({message.author})\n'\
                          f'`Channel`: {message.channel.mention}\n'\
                          f'`Reacts`: {record["count"]}\n`Text`:\n{msg_content}\n'\
                          f'`Message Link`: {message.jump_url}\n'
                if message.attachments:
                    desc = ''
                    for file in message.attachments:
                        if embed_image:
                            desc += f'{file.url}'
                        else:
                            desc += f'**(!!might be nsfw!!)**:\n'\
                                    f'<{file.url}>\n**(!!might be nsfw!!)**'
                    msg_str += f'`Attachments` \n{desc}'
            except discord.errors.NotFound:
                msg_str = f'Message not found, probably deleted.'
            l_embed.add_field(
                name=f'**{index+1}.**',
                value=msg_str,
                inline=True,
            )
        await ctx.send(embed=l_embed) 
Example #26
Source File: stats.py    From nano-chan with MIT License 4 votes vote down vote up
def top_user(self, ctx, user: discord.Member, emoji: discord.Emoji, days: int=-1, channel: discord.TextChannel=None):
        """
        Returns top post in timespan with reacts
        """
        channel_id = channel.id if channel else None
        day_str = f'in the last {days} days' if days != -1 else f'since forever'
        all_records = await self.bot.pg_controller.get_top_post_by_emoji_and_user(
             user.id, emoji, days, channel_id
        )
        l_embed = discord.Embed(
            title=f'Top 3 Posts with {emoji} reacts {day_str} on {user.name}',
            desc=f'___'
        )
        for index, record in enumerate(all_records):
            channel = self.bot.get_channel(record['ch_id'])
            embed_image = False
            if channel.id in [183215451634008065]: 
                embed_image = True
            if channel.id in [259728514914189312, 220762067739738113, 230958006701916160, 304366022276939776]:
                return
            try:
                message = await channel.fetch_message(record['id'])
                if len(message.clean_content) > 600:
                    msg_content = f'{message.clean_content[:500]} ... `(message shortened)`'
                else:
                    msg_content = f'{message.clean_content[:500]}' if message.content != '' else ''
                msg_str = f'`Author`: {message.author.mention} ({message.author})\n'\
                          f'`Channel`: {message.channel.mention}\n'\
                          f'`Reacts`: {record["count"]}\n`Text`:\n{msg_content}\n'\
                          f'`Message Link`: {message.jump_url}\n'
                if message.attachments:
                    desc = ''
                    for file in message.attachments:
                        if embed_image:
                            desc += f'{file.url}'
                        else:
                            desc += f'**(!!might be nsfw!!)**:\n'\
                                    f'<{file.url}>\n**(!!might be nsfw!!)**'
                    msg_str += f'`Attachments` \n{desc}'
            except discord.errors.NotFound:
                msg_str = f'Message not found, probably deleted.'
            l_embed.add_field(
                name=f'**{index+1}.**',
                value=msg_str,
                inline=True,
            )
        await ctx.send(embed=l_embed) 
Example #27
Source File: misc.py    From Discord-SelfBot with MIT License 4 votes vote down vote up
def regional(self, ctx, *, msg: str):
        """Convert a Text to emotes."""
        regional_list = self.to_regionals(msg, False)
        regional_output = []
        for i in regional_list:
            regional_output.append(" ")
            if isinstance(i, discord.Emoji):
                regional_output.append(str(i))
            else:
                regional_output.append(i)
        await edit(ctx, content=''.join(regional_output)) 
Example #28
Source File: react-to-contact.py    From modmail-plugins with GNU General Public License v3.0 4 votes vote down vote up
def setreaction(self, ctx: commands.Context, link: str):
        """
        Set the message on which the bot will look reactions on.
        Creates an __interactive session__ to use emoji **(Supports Unicode Emoji Too)**
        Before using this command, make sure there is a reaction on the message you want the plugin to look at.

        **Usage:**
        {prefix}setreaction <message_url>
        """

        def check(reaction, user):
            return user == ctx.message.author

        regex = r"discordapp\.com"

        if bool(re.search(regex, link)) is True:
            sl = link.split("/")
            msg = sl[-1]
            channel = sl[-2]

            await ctx.send(
                "React to this message with the emoji."
                " `(The reaction should also be on the message or it won't work.)`"
            )
            reaction, user = await self.bot.wait_for("reaction_add", check=check)

            await self.db.find_one_and_update(
                {"_id": "config"},
                {
                    "$set": {
                        "channel": channel,
                        "message": msg,
                        "reaction": f"{reaction.emoji.name if isinstance(reaction.emoji, discord.Emoji) else reaction.emoji}",
                    }
                },
                upsert=True,
            )
            await ctx.send("Done!")

        else:
            await ctx.send("Please give a valid message link")
            return