Exemple #1
0
 async def react(self, ctx, msg_id, *names):
     '''Reacts with any emoji from any server bot is connected to (No Nitro Required)'''
     converter = commands.EmojiConverter()
     msg = await ctx.fetch_message(msg_id)
     for name in names:
         emoji = await converter.convert(ctx, name)
         await msg.add_reaction(emoji)
Exemple #2
0
    async def retrieve_emoji(self):

        # TODO: use a function to convert emojis

        ctx = SimpleNamespace(bot=self, guild=self.modmail_guild)
        converter = commands.EmojiConverter()

        sent_emoji = self.config.get('sent_emoji', '✅')
        blocked_emoji = self.config.get('blocked_emoji', '🚫')

        if sent_emoji not in UNICODE_EMOJI:
            try:
                sent_emoji = await converter.convert(ctx,
                                                     sent_emoji.strip(':'))
            except commands.BadArgument:
                if sent_emoji != 'disable':
                    logger.warning(
                        info(f'Sent Emoji ({sent_emoji}) '
                             f'is not a valid emoji.'))
                    del self.config.cache['sent_emoji']
                    await self.config.update()

        if blocked_emoji not in UNICODE_EMOJI:
            try:
                blocked_emoji = await converter.convert(
                    ctx, blocked_emoji.strip(':'))
            except commands.BadArgument:
                if blocked_emoji != 'disable':
                    logger.warning(
                        info(f'Blocked emoji ({blocked_emoji}) '
                             'is not a valid emoji.'))
                    del self.config.cache['blocked_emoji']
                    await self.config.update()

        return sent_emoji, blocked_emoji
Exemple #3
0
    async def build_embed(self):
        """Build the Embed with the new data."""

        description = (
            f"**{self.random_chat}**\n"
            f"{self.ctx.author.display_name} ({self.ctx.author.mention}) "
            "sails today, join in on the plunder!")

        crew_list = "\n".join(
            [f"{m.display_name} ({m.mention})" for m in self.crew])

        converter = commands.EmojiConverter()
        emoji = await converter.convert(self.ctx, SEAOFTHEIVES_EMOJI)

        embed = discord.Embed(
            description=description,
            color=EMBED_COLOR,
        ).set_image(url=self.gif_url, ).set_thumbnail(url=SHIP_THUMBNAILS[min(
            len(self.crew), 4)], ).add_field(
                name="Crew",
                value=crew_list if crew_list else "No matey",
            ).set_footer(
                text="React to confirm your presence.",
                icon_url=emoji.url,
            )

        return embed
Exemple #4
0
 async def convert(self, ctx: Context, argument: str = None):
     try:
         member_converter = commands.MemberConverter()
         member = await member_converter.convert(ctx, argument)
         image = member.avatar.replace(format="png",
                                       static_format="png",
                                       size=1024)
         return str(image)
     except Exception:
         try:
             url = await emoji_to_url(argument)
             if re.match(regex_url, url):
                 image = str(url)
                 return image
             if re.match(regex_url, argument):
                 image = argument
                 return image
             if re.match(emoji_regex, argument):
                 emoji_converter = commands.EmojiConverter()
                 emoji = await emoji_converter.convert(ctx, argument)
                 image = emoji.url_as(format="png",
                                      static_format="png",
                                      size=1024)
                 return image
         except Exception:
             return None
     raise commands.MemberNotFound(argument)
Exemple #5
0
 async def emoji(self, ctx, *names):
     '''Sends any emoji from any server bot is connected to (No Nitro Required)'''
     converter = commands.EmojiConverter()
     content = ''
     for name in names:
         emoji = await converter.convert(ctx, name)
         content += str(emoji)
     await ctx.send(content)
Exemple #6
0
    async def convert_emoji(self, name):
        ctx = SimpleNamespace(bot=self, guild=self.modmail_guild)
        converter = commands.EmojiConverter()

        if name not in UNICODE_EMOJI:
            try:
                return await converter.convert(ctx, sent_emoji.strip(':'))
            except commands.BadArgument:
                pass
        return name
Exemple #7
0
    async def convert_emoji(self, name):
        ctx = SimpleNamespace(bot=self, guild=self.modmail_guild)
        converter = commands.EmojiConverter()

        if name not in UNICODE_EMOJI:
            try:
                name = await converter.convert(ctx, name.strip(':'))
            except commands.BadArgument:
                logger.warning(f'{name} is not a valid emoji.')
        return name
Exemple #8
0
    async def convert_emoji(self, name: str) -> str:
        ctx = SimpleNamespace(bot=self, guild=self.modmail_guild)
        converter = commands.EmojiConverter()

        if name not in UNICODE_EMOJI:
            try:
                name = await converter.convert(ctx, name.strip(":"))
            except commands.BadArgument as e:
                logger.warning("%s is not a valid emoji. %s.", e)
                raise
        return name
Exemple #9
0
 async def about_emoji(self, ctx, *emojis):
     '''Sends some useful info of emoji(s)'''
     converter = commands.EmojiConverter()
     for emoji in emojis:
         info = f'Encoded :: {emoji.encode("ascii", "namereplace")}'
         try:
             e = await converter.convert(ctx, emoji)
         except:
             continue
         else:
             info += f'\nEmojiID :: {e.id}\nURL     :: {e.url}'
         finally:
             await ctx.send(f'```asciidoc\n{info}```')
Exemple #10
0
async def fetch_one(self, ctx, thing: str):
    converter = commands.EmojiConverter()
    # TODO: Cache this
    indexed_guilds = [
        self.bot.get_guild(rec['guild_id'])
        for rec in await self.bot.conn.fetch(
            'SELECT guild_id FROM guild_prefs WHERE index_emojis=TRUE')
    ]
    available_emojis = list()
    for guild in indexed_guilds:
        available_emojis.extend(guild.emojis)
    choice = process.extractOne(thing, [e.name for e in available_emojis])[0]
    return await converter.convert(ctx, choice)
Exemple #11
0
    async def process_modmail(self, message):
        """Processes messages sent to the bot."""

        ctx = SimpleNamespace(bot=self, guild=self.modmail_guild)
        converter = commands.EmojiConverter()

        blocked_emoji = self.config.get('blocked_emoji', '🚫')
        sent_emoji = self.config.get('sent_emoji', '✅')

        if blocked_emoji not in emoji.UNICODE_EMOJI:
            try:
                blocked_emoji = await converter.convert(
                    ctx, blocked_emoji.strip(':'))
            except:
                pass

        if sent_emoji not in emoji.UNICODE_EMOJI:
            try:
                sent_emoji = await converter.convert(ctx,
                                                     sent_emoji.strip(':'))
            except:
                pass

        reaction = blocked_emoji if str(
            message.author.id) in self.blocked_users else sent_emoji

        try:
            await message.add_reaction(reaction)
        except:
            pass

        blocked_em = discord.Embed(
            title='Message not sent!',
            color=discord.Color.red(),
            description='You have been blocked from using modmail.')

        if str(message.author.id) in self.blocked_users:
            await message.author.send(embed=blocked_em)
        else:
            thread = await self.threads.find_or_create(message.author)
            await thread.send(message)
Exemple #12
0
    async def process_modmail(self, message):
        """Processes messages sent to the bot."""

        ctx = SimpleNamespace(bot=self, guild=self.modmail_guild)
        converter = commands.EmojiConverter()

        blocked_emoji = self.config.get('blocked_emoji', '🚫')
        sent_emoji = self.config.get('sent_emoji', '✅')

        if blocked_emoji not in UNICODE_EMOJI:
            try:
                blocked_emoji = await converter.convert(
                    ctx, blocked_emoji.strip(':')
                )
            except commands.BadArgument:
                pass

        if sent_emoji not in UNICODE_EMOJI:
            try:
                sent_emoji = await converter.convert(
                    ctx, sent_emoji.strip(':')
                )
            except commands.BadArgument:
                pass

        if str(message.author.id) in self.blocked_users:
            reaction = blocked_emoji
        else:
            reaction = sent_emoji

        try:
            await message.add_reaction(reaction)
        except (discord.HTTPException, discord.InvalidArgument):
            pass

        if str(message.author.id) not in self.blocked_users:
            thread = await self.threads.find_or_create(message.author)
            await thread.send(message)
Exemple #13
0
    async def role_update(self):
        """
        Update roles stored every 30 minutes
        :return:
        """
        await self.__bot.wait_until_ready()
        logger.info("Updating role messages...")

        async with session_lock:
            with Session() as session:

                # Go through all visible guilds
                for guild in self.__bot.guilds:

                    server = server_crud.get_by_discord(session, guild.id)

                    # Skip if server is not found
                    if server is None:
                        continue

                    # Get all roles for server
                    roles = role_crud.get_multi_by_server_uuid(
                        session, server.uuid
                    )

                    temp_roles = {}

                    for r in roles:
                        temp_roles[r.discord_id] = r

                    # Go through all roles of a guild
                    for r in guild.roles:

                        # Skip roles that are default or premium
                        if r.is_default or r.is_premium_subscriber:
                            continue

                        # Check that role is registered, otherwise skip
                        if r.id not in temp_roles:
                            continue

                        # If the name is the same, then skip
                        if r.name == temp_roles[r.id].name:
                            continue

                        role_update = UpdateRole(**{
                            "name": r.name
                        })

                        # Update role
                        role_crud.update(
                            session, temp_roles[r.id], role_update
                        )

                    # Update role message if it exists
                    if server.role_message is not None and \
                            server.role_channel is not None:
                        channel = self.__bot.get_channel(
                            int(server.role_channel)
                        )

                        # Continue if channel wasn't found
                        if channel is None:
                            logger.info(f"No channel found for {server.name}.")
                            continue

                        # Channel must not be bloated with messages
                        message = utils.find(
                            lambda m: (m.id == int(server.role_message)),
                            await channel.history(limit=10).flatten()
                        )

                        # Continue if message wasn't found
                        if message is None:
                            logger.info(f"No message found for {server.name}.")
                            continue

                        # Get context
                        ctx = await self.__bot.get_context(message)

                        embed = Embed()
                        embed.title = f"Assignable roles for " \
                                      f"**{message.guild.name}**"
                        embed.description = "Use reactions inorder to get " \
                                            "roles assigned to you, or use " \
                                            "`!role add roleName`"

                        converter = commands.EmojiConverter()
                        pconverter = commands.PartialEmojiConverter()

                        # Get all roles of a server
                        roles = role_crud.get_multi_by_server_uuid(
                            session, server.uuid
                        )

                        # Gather all used emojis for future reactions
                        emojis = []

                        for ro in roles:

                            emoji = emoji_crud.get_by_role(session, ro.uuid)

                            try:
                                # Convert into actual emoji
                                e = await converter.convert(
                                    ctx, emoji.identifier
                                )
                            except commands.EmojiNotFound:
                                # Try partial emoji instead
                                try:
                                    e = await pconverter.convert(
                                        ctx, emoji.identifier
                                    )
                                except commands.PartialEmojiConversionFailure:
                                    # Assume that it is an unicode emoji
                                    e = emoji.identifier

                            # Add to message
                            embed.add_field(
                                name=f"{str(e)}  ==  {ro.name}",
                                value=ro.description,
                                inline=False
                            )

                            emojis.append(e)

                        await message.edit(embed=embed)

                        # Check old reactions
                        old_emojis = []
                        for r in message.reactions:
                            old_emojis.append(r.emoji)

                        # Add new reactions to message
                        for e in emojis:
                            if isinstance(e, discord.partial_emoji.PartialEmoji):
                                logger.error(f"Emoji not cannot be used! Emoji: {e}")
                            elif e not in old_emojis:
                                await message.add_reaction(e)

                        logger.info(f"Message updated for {server.name}.")
Exemple #14
0
import discord
import pymongo as mg
import requests
from discord.ext import commands

# Setting up Database
MONGO_CLIENT = mg.MongoClient("mongodb://localhost:27017")
DATABASE = MONGO_CLIENT["Emojis"]
PREFIX_LIST = DATABASE["prefixes"]
SETTINGS = DATABASE["settings"]
APPROVAL_QUEUES = DATABASE["verification_queues"]

BOTS_GG_TOKEN = ""

# stuff for replacing emojis
EMOJI_CONVERTER = commands.EmojiConverter()


class CustomCommandError(Exception):
    pass


# Colors used in the Bot
class Colours:
    base = discord.Color(16027908)  # normal: 16562199
    success = discord.Color(3066993)
    fail = discord.Color(15742004)
    warn = discord.Color(16707936)


async def replace_unparsed_emojis(message: discord.Message):
Exemple #15
0
 async def emoji(self, ctx, *, arg):
     converter = commands.EmojiConverter()
     emoji = await converter.convert(ctx, arg)
     embed = discord.Embed(title=f"Emoji {emoji.name}")
     embed.set_image(url=emoji.url)
     await ctx.send(embed=embed)
Exemple #16
0
 def __init__(self, bot):
     self.bot = bot
     self.emoji_converter = commands.EmojiConverter()
     self.nsp = NumericStringParserForPython3()
    async def create(self, ctx: Context, alias: str, *initial_mappings: str):
        """
        Creates a new reaction role embed entry and create message in management channel.

        :param ctx: The command execution context
        :param alias: The human readable name for this reaction role embed
        :param initial_mappings: a list of initial mappings to create the embed with; must be an even length list
        with an emote followed by a role e.g. ["emote", "role", "emote", "role", ...]
        """
        # creating dictionary mapping emoji to roles from trailing arguments
        initial_map_dict = {}  # type: Dict[Emoji, Role]
        initial_id_map_dict = {}  # type: Dict[int, int]
        if len(initial_mappings) > 0:
            # trailing arguments must have an even length
            if len(initial_mappings) % 2 != 0:
                await ctx.channel.send(
                    f'{ctx.author.mention} Uneven number of initial mapping parameters given!'
                )
                return
            emoji_converter = commands.EmojiConverter()
            role_converter = commands.RoleConverter()
            for idx in range(0, len(initial_mappings), 2):
                try:
                    emoji_arg, role_arg = initial_mappings[idx:idx + 2]
                except IndexError:
                    await ctx.channel.send(
                        f'{ctx.author.mention} Uneven number of initial mapping parameters given!'
                    )
                    return
                try:
                    emoji = await emoji_converter.convert(ctx, emoji_arg)
                    role = await role_converter.convert(ctx, role_arg)
                except commands.EmojiNotFound:
                    await ctx.channel.send(
                        f'{ctx.author.mention} Unable to convert {emoji_arg} to an emoji.'
                    )
                    return
                except commands.RoleNotFound:
                    await ctx.channel.send(
                        f'{ctx.author.mention} Unable to convert {role_arg} to a role.'
                    )
                    return
                initial_map_dict[emoji] = role
                initial_id_map_dict = {
                    emoji.id: role.id
                    for emoji, role in initial_map_dict.items()
                }
        message = await ctx.channel.send(
            content='Creating new reaction role message....')  # type: Message
        err = await self._create_on_backend(message, ctx.guild, alias,
                                            ctx.author, initial_id_map_dict)
        if err is not None:
            msg = f'{ctx.author.mention} Encountered an error creating mapping embed on backend: {err}'
            await message.edit(content=msg)
            return
        sub_content = f'{ctx.author.mention} Reaction Role message created:\nID=`{ctx.channel.id}-{message.id}`\n'
        sub_content += f'alias=`{alias}`\n'
        sub_content += f'{message.jump_url}'
        generated_description = [
            '{} -> {}'.format(e, r.mention)
            for e, r in initial_map_dict.items()
        ]
        reaction_role_embed = Embed(
            title='Reaction Role Embed',
            description='\n'.join(generated_description))
        await message.edit(content=sub_content, embed=reaction_role_embed)
        for emoji in initial_map_dict.keys():
            await message.add_reaction(emoji)
Exemple #18
0
import aiohttp
import discord
from discord.ext import commands

from CyberTron5000.utils.converter import ImageConverter

member_converter = commands.MemberConverter()
emoji_converter = commands.EmojiConverter()


class Images(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @property
    def daggy(self):
        return self.bot.get_user(491174779278065689)

    @property
    def dagpi_token(self):
        return self.bot.config.dagpi_token

    @commands.command(name='wanted')
    async def _static_wanted(self, ctx, *, url: ImageConverter = None):
        """
        Wanted...
        """
        if not url:
            if ctx.message.attachments:
                url = str(ctx.message.attachments[0].url)
            else:
Exemple #19
0
    async def init(self, ctx):
        """
        Initialize role message for current channel

        :param ctx: Context
        :return:
        """
        async with session_lock:
            with Session() as session:
                db_server = get_create_ctx(ctx, session, server_crud)

                embed = Embed()
                embed.title = f"Assignable roles for **{ctx.guild.name}**"
                embed.description = "Use reactions inorder to get " \
                                    "roles assigned to you, or use " \
                                    "`!role add roleName`"

                converter = commands.EmojiConverter()
                pconverter = commands.PartialEmojiConverter()

                # Get all roles on the server
                roles = role_crud.get_multi_by_server_uuid(
                    session, get_create_ctx(ctx, session, server_crud).uuid
                )

                # Gather all used emojis for future reactions
                emojis = []

                for r in roles:

                    emoji = emoji_crud.get_by_role(
                        session, r.uuid
                    )

                    if emoji is not None:

                        try:
                            # Convert into actual emoji
                            e = await converter.convert(
                                ctx, emoji.identifier
                            )
                        except commands.EmojiNotFound:
                            # Try partial emoji instead
                            try:
                                e = await pconverter.convert(
                                    ctx, emoji.identifier
                                )
                            except commands.PartialEmojiConversionFailure:
                                # Assume that it is an unicode emoji
                                e = emoji.identifier

                        # Add to message
                        embed.add_field(
                            name=f"{str(e)}  ==  {r.name}",
                            value=r.description,
                            inline=False
                        )

                        emojis.append(e)

                # Send message
                role_message = await ctx.send(embed=embed)

                # Add reaction to message with all used emojis
                for e in emojis:
                    await role_message.add_reaction(e)

                # Update server object to include role message data
                server_update = UpdateServer(**{
                    "role_message": str(role_message.id),
                    "role_channel": str(ctx.channel.id)
                })

                server_crud.update(
                    session, db_obj=db_server, obj_in=server_update
                )
Exemple #20
0
    async def create(
            self, ctx, discord_id: int, description: str, emoji: str = None
    ):
        """
        Create assignable role

        :param ctx: Context
        :param discord_id: Role Discord ID
        :param description: Description of role usage
        :param emoji: Emoji for assignment via reactions
        :return:
        """
        embed = Embed()
        embed.set_author(name=self.__bot.user.name,
                         url=settings.URL,
                         icon_url=self.__bot.user.avatar_url)
        async with session_lock:
            with Session() as session:
                d_role = ctx.guild.get_role(discord_id)
                db_role = role_crud.get_by_discord(session, discord_id)

                # TODO Add emoji parsing

                if d_role is None:
                    embed.title = "Role not found."
                    embed.colour = Colors.error
                elif db_role is not None:
                    embed.title = "Role already exists!"
                    embed.colour = Colors.other
                else:
                    role = CreateRole(**{
                        "discord_id": discord_id,
                        "name": d_role.name,
                        "description": description,
                        "server_uuid": get_create_ctx(
                            ctx, session, server_crud
                        ).uuid
                    })

                    db_role = role_crud.create(session, obj_in=role)

                    if emoji is not None:
                        converter = commands.EmojiConverter()
                        pconverter = commands.PartialEmojiConverter()

                        try:
                            # Convert into actual emoji
                            e = await converter.convert(
                                ctx, emoji
                            )
                        except commands.EmojiNotFound:
                            # Try partial emoji instead
                            try:
                                e = await pconverter.convert(
                                    ctx, emoji
                                )
                            except commands.PartialEmojiConversionFailure:
                                # Assume that it is an unicode emoji
                                e = emoji
                    else:
                        e = None

                    if e is not None and not isinstance(e, discord.partial_emoji.PartialEmoji):

                        if hasattr(e, 'name'):
                            e = e.name

                        db_e = CreateRoleEmoji(**{
                            "identifier": e,
                            "role_uuid": db_role.uuid
                        })
                        emoji_crud.create(session, obj_in=db_e)
                    elif isinstance(emoji, discord.partial_emoji.PartialEmoji):
                        embed.description = "**Note**: Role was created" \
                                            " without an emoji, because the bot " \
                                            "cannot use provided emoji..."
                    else:
                        embed.description = "**Note**: Role was created" \
                                            " without an emoji, so it " \
                                            "cannot be assigned with " \
                                            "reactions!"

                    embed.title = f"Role *{db_role.name}* created."
                    embed.colour = Colors.success
        embed.timestamp = datetime.utcnow()
        await ctx.send(embed=embed)
Exemple #21
0
 def __init__(gh, bot):
     gh.bot = bot
     gh.emoji_converter = commands.EmojiConverter()
     gh.nsp = NumericStringParserForPython3()
Exemple #22
0
 def __init__(self, bot):
     self.bot = bot
     self.emoji_converter = commands.EmojiConverter()
Exemple #23
0
import dbl
import discord
import requests
from discord.ext import commands
from discord.ext.commands import has_permissions

from main import Colours
from main import CustomCommandError
from main import emoji_categories, browse_messages, emoji_list
from main import invite_message, numbers
from main import send_error
from main import send_warning
from main import time_warning_embed

conv = commands.EmojiConverter()
help_embed_test = discord.Embed()
help_embed_test.colour = Colours.base

pride_flags = {
    "gay": "https://discordemoji.com/assets/emoji/1429_gay_pride_heart.png",
    "bisexual":
    "https://discordemoji.com/assets/emoji/1210_bi_pride_heart.png",
    "pansexual": "https://discordemoji.com/assets/emoji/5264_Heart_Pan.png",
    "nonbinary":
    "https://discordemoji.com/assets/emoji/9084_nonbinary_pride_heart.png",
    "transgender":
    "https://discordemoji.com/assets/emoji/7574_Heart_Trans.png",
    "asexual": "https://discordemoji.com/assets/emoji/7949_Heart_ase.png",
    "lesbian":
    "https://discordemoji.com/assets/emoji/3347_lesbian_pride_heart.png"
Exemple #24
0
    return converter


type_to_converter = {
    # Builtins
    bool: commands.core._convert_to_bool,
    int: built_in_converter(int),
    str: str,
    # Discord objects
    Role: commands.RoleConverter(),
    User: commands.UserConverter(),
    Member: commands.MemberConverter(),
    Color: commands.ColorConverter(),
    Invite: commands.InviteConverter(),
    Emoji: commands.EmojiConverter(),
    Message: commands.MessageConverter(),
    PartialEmoji: commands.PartialEmojiConverter(),
    TextChannel: commands.TextChannelConverter(),
    VoiceChannel: commands.VoiceChannelConverter(),
    CategoryChannel: commands.CategoryChannelConverter(),
}

_to_str = {
    Message: lambda m: f"Message with id {m.id} in {m.channel.mention}",
}


def to_str(argument: UserInputable) -> str:
    _type = type(argument)
    if issubclass(_type, Enum):