Ejemplo n.º 1
0
    async def on_message_edit(self, before: discord.Message, after: discord.Message):
        if before.content != after.content:
            if after.guild and not isinstance(after.author, discord.Member):
                # Cache bug, after.author is User while before.author is Member
                after.author = await after.guild.fetch_member(after.author.id)

            await self.process_commands(after)
Ejemplo n.º 2
0
def startup(dispatcher):
    """
    This method is ran when the bot starts up. Currently used to persist aliases that are created
    @param dispatcher: command_dispatcher.CommandDispatcher
    """
    logger.info("Initializing saved commands")
    msg = Message(content="!alias !d !dankmemes")
    msg.server = Server(id='108769127627280384')
    dispatcher.run_command(msg)
    msg = Message(content="!alias !cf !cowsay $fortune=True")
    msg.server = Server(id='108769127627280384')
    dispatcher.run_command(msg)
    msg = Message(content="!alias !cf !cowsay $fortune=True")
    msg.author = User(id='108768204184113152')
    dispatcher.run_command(msg)
    msg = Message(content="!alias !d !dankmemes")
    msg.author = User(id='108768204184113152')
    dispatcher.run_command(msg)
Ejemplo n.º 3
0
 async def command_spoof(self, message: discord.Message):
     author = await self.register_user(message.author)
     _, spoof, content = message.content.split(" ", 2)
     if author.admin:
         if len(spoof) > 3 and spoof[2:-1].isnumeric():
             user = self.client.get_user(int(spoof[2:-1]))
             if user:
                 message.author = user
                 message.content = content
                 command = message.content.split()[0][1:]
                 if hasattr(self, f"command_{command}"):
                     await getattr(self, f"command_{command}")(message)
                 else:
                     await message.channel.send("command not found")
             else:
                 await message.channel.send("user not found")
         else:
             await message.channel.send("user not found")
Ejemplo n.º 4
0
    async def on_message(self, message: discord.Message):
        if message.guild is None:
            return
        if message.author.bot:
            return
        if message.guild.id != self.bot.settings.guild_id:
            return
        message.author = message.guild.get_member(message.author.id)
        if self.bot.settings.permissions.hasAtLeast(message.guild,
                                                    message.author, 5):
            return

        if await self.ping_spam(message):
            await self.handle_raid_detection(message, RaidType.PingSpam)
        elif await self.raid_phrase_detected(message):
            await self.handle_raid_detection(message, RaidType.RaidPhrase)
        elif await self.message_spam(message):
            await self.handle_raid_detection(message, RaidType.MessageSpam)
        elif await self.detect_scam_link(message):
            await self.report_possible_raid_phrase(message)
Ejemplo n.º 5
0
    async def on_message(self, message: discord.Message):
        """ Message handler. Auto-upvotes valid resource messages. """

        # resource channel only
        if message.channel != self.cog_config.channel:
            return

        # don't react to self
        if message.author == self.bot.user:
            return

        if not self.is_resource_post(message):
            return

        message.author = message.author  # type: discord.Member
        logger.info("New #resources message from {} ({})".format(
            message.author.nick or message.author.name, message.author.id))

        for reaction in self.cog_config.reactions:
            logger.info("Adding reaction '{}'".format(reaction))
            await self.bot.add_reaction(message, reaction)
Ejemplo n.º 6
0
async def do_as(message: discord.Message, member: discord.Member, command: Annotate.Content):
    """ Execute a command as the specified member. """
    message.author = member
    message.content = command
    await client.on_message(message)
Ejemplo n.º 7
0
async def __main__(client: Client, _event: int, message: Message):
    try:
        if message.guild is None or DATA.debug:
            return

        try:
            user = int(message.content.split()[-1].replace("<", "").replace(
                "@", "").replace("!", "").replace(">", ""))
            message.author = await client.fetch_user(user)
        except (ValueError, NotFound, IndexError):
            user = message.author.id

        db = connect("levels.sqlite")
        cursor = db.cursor()

        cursor.execute(f"SELECT * FROM lvl WHERE user=={user}")

        fetched = cursor.fetchone()
        if fetched is None:
            cursor.execute(f"INSERT INTO lvl VALUES ({user}, 0, 0)")
            db.commit()

        data: Tuple[int, int, int] = fetched or (user, 0, 0)

        cursor.execute("SELECT * from lvl ORDER BY xp DESC LIMIT 10")
        rank = cursor.fetchall()

        ranking = {
            "inline":
            False,
            "name":
            f"__Ranking #{len(rank)}:__",
            "value":
            "\n".join(f"LVL **{l}**; "
                      f"XP **{x}**; "
                      f"<@{u}>" for u, l, x in rank)
        }

        cursor.execute("SELECT null from lvl")
        len_user = len(cursor.fetchall())

        xp = data[2]
        lvl = data[1]

        if message.content.startswith(("!!", "++", "..", "??")):
            """
            `!!` -> prefix for <@714477299042615361> (Josef#0189)
            `++` -> prefix for <@772085213987209226> (Red-Rainbow#0836)
            `..` -> prefix for <@751157545728606239> (Alberto-X3#9164)
            `??` -> prefix for <@756196727748296855> (CardGifter2020#2871)
            """
            if not message.content.startswith(".."):
                return

            user_level = xp**formula
            user_progress = int(str(user_level).split(".")[1][:2])
            len_filled = int(len_bar * user_progress / 100)

            bar = f"{'#' * len_filled:-<{len_bar}}"
            bar = bar.replace("#", full)
            bar = bar.replace("-", free)

            cursor.execute(f"SELECT level FROM lvl where xp>{xp}")
            rank = len(cursor.fetchall()) + 1

            embed = Embed(
                color=0x275591,
                description=
                f"You are the number __**#{rank}**__ {message.author.mention}!"
            )
            embed.set_author(name=message.author.name,
                             icon_url=message.author.avatar_url)
            embed.set_footer(text=f"total {len_user} user in ranking")

            embed.add_field(inline=False, name="__Your LVL:__", value=str(lvl))
            embed.add_field(inline=False,
                            name="__Your XP:__",
                            value=f"{xp}\n{bar}")
            embed.add_field(**ranking)
            embed.add_field(name="__Info:__", value=needed_info, inline=False)

            await message.channel.send(embed=embed)
            return

        # below is only without prefix and just leveling
        if message.channel.slowmode_delay:
            return

        author: Member = message.guild.get_member(message.author.id)

        try:
            if recent[user] + latency > datetime.utcnow():
                if not message.content.startswith("\u200B"):
                    if recent[user] + latency / 2 > datetime.utcnow():
                        return
                else:
                    return
        except KeyError:
            pass

        recent[user] = datetime.utcnow()

        xp += choice(possible_xps)
        old_lvl = lvl
        lvl = int(xp**formula) - 1

        cursor.execute(f"UPDATE lvl SET level={lvl} WHERE user=={user}")
        cursor.execute(f"UPDATE lvl SET xp={xp} WHERE user=={user}")

        db.commit()
        db.close()

        if lvl != old_lvl:
            await client.get_channel(831625194803298314).send(
                f"Congratulations __**{message.author.mention}**__!\n"
                f"You are now __*Level {lvl}*__ {lvl*'🥳'}\n")

            if str(lvl) in lvl_rewards:
                reward: Role = message.guild.get_role(lvl_rewards[str(lvl)])
                await author.add_roles(reward, reason="Leveling reward")

    except Exception as e:
        await send_exception(client=client, exception=e, source_name=__name__)
Ejemplo n.º 8
0
    async def from_interaction(cls, interaction: Interaction, /) -> Self:
        """|coro|

        Creates a context from a :class:`discord.Interaction`. This only
        works on application command based interactions, such as slash commands
        or context menus.

        On slash command based interactions this creates a synthetic :class:`~discord.Message`
        that points to an ephemeral message that the command invoker has executed. This means
        that :attr:`Context.author` returns the member that invoked the command.

        In a message context menu based interaction, the :attr:`Context.message` attribute
        is the message that the command is being executed on. This means that :attr:`Context.author`
        returns the author of the message being targetted. To get the member that invoked
        the command then :attr:`discord.Interaction.user` should be used instead.

        .. versionadded:: 2.0

        Parameters
        -----------
        interaction: :class:`discord.Interaction`
            The interaction to create a context with.

        Raises
        -------
        ValueError
            The interaction does not have a valid command.
        TypeError
            The interaction client is not derived from :class:`Bot` or :class:`AutoShardedBot`.
        """

        # Circular import
        from .bot import BotBase

        if not isinstance(interaction.client, BotBase):
            raise TypeError(
                'Interaction client is not derived from commands.Bot or commands.AutoShardedBot'
            )

        command = interaction.command
        if command is None:
            raise ValueError('interaction does not have command data')

        bot: BotT = interaction.client  # type: ignore
        data: ApplicationCommandInteractionData = interaction.data  # type: ignore
        if interaction.message is None:
            synthetic_payload = {
                'id':
                interaction.id,
                'reactions': [],
                'embeds': [],
                'mention_everyone':
                False,
                'tts':
                False,
                'pinned':
                False,
                'edited_timestamp':
                None,
                'type':
                MessageType.chat_input_command if data.get('type', 1) == 1 else
                MessageType.context_menu_command,
                'flags':
                64,
                'content':
                '',
                'mentions': [],
                'mention_roles': [],
                'attachments': [],
            }

            if interaction.channel_id is None:
                raise RuntimeError(
                    'interaction channel ID is null, this is probably a Discord bug'
                )

            channel = interaction.channel or PartialMessageable(
                state=interaction._state, id=interaction.channel_id)
            message = Message(state=interaction._state,
                              channel=channel,
                              data=synthetic_payload)  # type: ignore
            message.author = interaction.user
            message.attachments = [
                a for _, a in interaction.namespace
                if isinstance(a, Attachment)
            ]
        else:
            message = interaction.message

        prefix = '/' if data.get('type',
                                 1) == 1 else '\u200b'  # Mock the prefix
        return cls(
            message=message,
            bot=bot,
            view=StringView(''),
            args=[],
            kwargs={},
            prefix=prefix,
            interaction=interaction,
            invoked_with=command.name,
            command=
            command,  # type: ignore # this will be a hybrid command, technically
        )