Exemplo n.º 1
0
 async def on_message_edit(self, before: discord.Message,
                           after: discord.Message):
     "https://discordpy.readthedocs.io/en/latest/api.html#discord.on_message_edit"
     if before.author.bot or (not await self.has_logs(before.guild)):
         return
     if before.content == after.content:
         return  # when edition is only adding an embed, for example
     if 'messages' not in self.get_flags(before.guild.id):
         return
     embed = discord.Embed(
         timestamp=after.created_at,
         title="Message édité",
         description=
         f"Un message de {before.author.mention} **a été édité** dans {before.channel.mention}.",
         colour=discord.Colour(16294684))
     embed.set_author(name=str(before.author),
                      icon_url=before.author.avatar_url)
     embed.set_footer(
         text=f"Author ID: {before.author.id} • Message ID: {before.id}")
     if len(before.content) > 1024:
         before.content = before.content[:1020] + '...'
     if len(after.content) > 1024:
         after.content = after.content[:1020] + '...'
     embed.add_field(name='Avant', value=before.content, inline=False)
     embed.add_field(name="Après", value=after.content, inline=False)
     await self.send_embed(before.guild, embed)
Exemplo n.º 2
0
    async def on_message(self, message: discord.Message):
        """Called every time a message is sent on a visible channel."""
        # Ignore if message is from any bot
        if message.author.bot:
            return

        split = message.content.split(" ", 1)
        if split[0][:1] == "/" and split[0].lower()[1:] in self.command_list:
            if len(split) > 1:
                message.content = split[0].lower() + " " + split[1]
            else:
                message.content = message.content.lower()
        if len(split) == 2:
            if message.author.id != self.user.id and \
                    (not split[0].lower()[1:] in self.command_list or not split[0][:1] == "/") and \
                    not isinstance(message.channel, abc.PrivateChannel) and \
                    message.channel.name == config.ask_channel_name:
                await message.delete()
                return
        elif config.ask_channel_delete:
            # Delete messages in askchannel
            if message.author.id != self.user.id \
                    and (not message.content.lower()[1:] in self.command_list or not message.content[:1] == "/") \
                    and not isinstance(message.channel, abc.PrivateChannel) and message.channel.name == config.ask_channel_name:
                await message.delete()
                return
        await self.process_commands(message)
Exemplo n.º 3
0
    async def on_message(self, message: discord.Message):
        message.content = (message.content.replace("—", "--").replace(
            "'", "′").replace("‘", "′").replace("’", "′"))

        if message.content.lower().startswith("pan sell all"):
            message.content = "pan sellall" + message.content[12:]

        await self.process_commands(message)
Exemplo n.º 4
0
 async def on_message(self, message: discord.Message) -> None:
     if (not self.check_self or message.author.id == self.user.id):
         if message.content.startswith(self.prefix):
             try:
                 pipe = message.content.split('|')
                 result = ''
                 begin = True
                 for command, end in lookahead(pipe):
                     command = command.strip()
                     if begin:
                         command = command[len(self.prefix):]
                         begin = False
                     if matches := re.finditer(eval_re, command):
                         offset = 0
                         for m in matches:
                             match = m.group(0)
                             if match[0] == '\\':
                                 s = m.start() - offset
                                 command = command[:s] + command[1 + s:]
                                 offset += 1
                                 continue
                             if match[1:]:
                                 command = command.replace(
                                     match, str(eval(match[1:])), 1)
                     message.content = f'{command} {result}'.strip()
                     message_split = command.split(' ')
                     command_func = c.commands[message_split[0]]
                     result = await command_func(message, self)
                     if end and result is not None:
                         await message.channel.send(result)
             except Exception as e:
                 await send_error(f'error: {e}', message)
             finally:
                 try:
                     await message.delete()
                 except Exception:
                     pass
         elif self.convert_emoji_names_to_links:
             try:
                 message_split = message.content.split(' ')
                 links = []
                 for part in message_split:
                     for emoji in self.emojis:
                         if part == emoji.name:
                             links.append(str(emoji.url))
                             break
                 if links:
                     if len(message_split) > 1:
                         message.content += '\n' + '\n'.join(links)
                     else:
                         message.content = links[0]
                     await message.edit(content=message.content)
             except Exception as e:
                 await send_error(f'error: {e}', message)
Exemplo n.º 5
0
async def sonnet_map(message: discord.Message, args: List[str],
                     client: discord.Client, ctx: CommandCtx) -> Any:
    if not message.guild:
        return 1

    tstart: int = time.monotonic_ns()
    cmds_dict = ctx.cmds_dict

    try:
        targs, targlen, cmd, command, endlargs = await map_preprocessor(
            message, args, client, cmds_dict, ctx.conf_cache)
    except MapProcessError:
        return 1

    # Keep original message content
    keepref = message.content
    try:

        newctx = pycopy.copy(ctx)
        newctx.verbose = False

        for i in targs[targlen:]:

            message.content = f'{ctx.conf_cache["prefix"]}{command} {i} {" ".join(endlargs)}'

            try:
                suc = (await cmd.execute_ctx(message,
                                             i.split() + endlargs, client,
                                             newctx)) or 0
            except lib_sonnetcommands.CommandError as ce:
                await message.channel.send(ce)
                suc = 1

            if suc != 0:
                await message.channel.send(
                    f"ERROR: command `{command}` exited with non success status"
                )
                return 1

        # Do cache sweep on command
        do_cache_sweep(cmd.cache, ctx.ramfs, message.guild)

        tend: int = time.monotonic_ns()

        fmttime: int = (tend - tstart) // 1000 // 1000

        if ctx.verbose:
            await message.channel.send(
                f"Completed execution of {len(targs[targlen:])} instances of {command} in {fmttime}ms"
            )

    finally:
        message.content = keepref
Exemplo n.º 6
0
        async def on_message(message: Message):
            for command_group, prefix in self.local_prefix.items():
                if message.content.startswith(prefix.strip()):
                    if message.content == f"{prefix}help":
                        message.content = (
                            f"{self.global_prefix}help {command_group}")
                    else:
                        command = message.content.replace(prefix, "")
                        message.content = (
                            f"{self.global_prefix}{command_group} {command}")

            await self.bot.process_commands(message)
Exemplo n.º 7
0
    async def on_message(self, message: discord.Message):
        # Do not drop gifts on commands
        if message.content.startswith(".") or message.content.lower().startswith("confirm"): return

        immediate_time = datetime.utcnow()
        if message.author.id in self.current_gifters and not message.guild:
            async with self.bot.db.acquire() as conn:
                last_gift = await last_gift_from_db(conn, message.author.id)

                gift = await fetch_gift_nickname(conn, message.author.id)
                if message.content.lower().strip().replace(' ', '') == gift.lower().strip().replace(' ', ''):
                    calculated_time = (immediate_time - last_gift).total_seconds()
                    self.current_gifters.remove(message.author.id)
                    self.bot.loop.create_task(self.add_score(message.author, message.created_at))
                    self.bot.logger.info(
                        f"User {message.author.id} guessed gift ({gift}) in {calculated_time} seconds."
                    )
                else:
                    await message.add_reaction(self.bot.config.get('wrong_emoji'))
            return

        if message.channel.id not in self.bot.config.get("drop_channels", []): return
        self.users_last_channel[message.author.id] = {'name': message.channel.name, 'id': message.channel.id}

        # Remove custom emojis with regex
        message.content = re.sub(r"<a?:\w{2,32}:\d{15,21}>", "", message.content)
        # Remove markdown
        for pattern in ["*", "__", "~~", "||", "`", ">"]:
            message.content = message.content.replace(pattern, "")
        # Ignore messages that are more likely to be spammy, chain messages and emoji-only messages.
        if len(message.content) < 5 or self.last_user == message.author.id:
            return

        self.last_user = message.author.id

        if not message.author.id in self.users_last_message or (datetime.now()-self.users_last_message[message.author.id]).total_seconds() > self.bot.config.get("recovery_time", 10):
            self.users_last_message[message.author.id] = datetime.now()
            async with self.bot.db.acquire() as conn:
                last_gift = await last_gift_from_db(conn, message.author.id)
                if last_gift is not None:
                    if (datetime.utcnow() - last_gift).total_seconds() > self.bot.config.get("cooldown_time", 30):
                        drop_chance = self.bot.config.get("drop_chance", 0.1)

                        if not message.author.id in self.users_drop_stash or len(self.users_drop_stash[message.author.id]) == 0:
                            self.users_drop_stash[message.author.id] = [True]*int(20*drop_chance) + [False]*int(20*(1-drop_chance))

                        drop = self.users_drop_stash[message.author.id].pop(random.randrange(len(self.users_drop_stash[message.author.id])))

                        if drop:
                            self.users_drop_stash[message.author.id] = [True]*int(20*drop_chance) + [False]*int(20*(1-drop_chance))
                            self.bot.logger.info(f"A natural gift has dropped ({message.author.id})")
                            self.bot.loop.create_task(self.create_gift(message.author, message.created_at))
Exemplo n.º 8
0
async def on_message(message: Message):
    # If the message is by a bot thats not irc then ignore it
    if message.author.bot and message.author.id != CONFIG[
            "UWCS_DISCORD_BRIDGE_BOT_ID"]:
        return

    user = db_session.query(User).filter(
        User.user_uid == message.author.id).first()
    if not user:
        user = User(user_uid=message.author.id, username=str(message.author))
        db_session.add(user)
    else:
        user.last_seen = message.created_at
    # Commit the session so the user is available now
    try:
        db_session.commit()
    except (ScalarListException, SQLAlchemyError):
        db_session.rollback()
        # Something very wrong, but not way to reliably recover so abort
        return

    # Only log messages that were in a public channel
    if isinstance(message.channel, GuildChannel):
        # Log the message to the database
        logged_message = LoggedMessage(
            message_uid=message.id,
            message_content=message.clean_content,
            author=user.id,
            created_at=message.created_at,
            channel_name=message.channel.name,
        )
        db_session.add(logged_message)
        try:
            db_session.commit()
        except (ScalarListException, SQLAlchemyError):
            db_session.rollback()
            return

        # Get all specified command prefixes for the bot
        command_prefixes = bot.command_prefix(bot, message)
        # Only process karma if the message was not a command (ie did not start with a command prefix)
        if True not in [
                message.content.startswith(prefix)
                for prefix in command_prefixes
        ]:
            reply = process_karma(message, logged_message.id, db_session,
                                  CONFIG["KARMA_TIMEOUT"])
            if reply:
                await message.channel.send(reply)

    # allow irc users to use commands by altering content to remove the nick before sending for command processing
    # note that clean_content is *not* altered and everything relies on this fact for it to work without having to go back and lookup the message in the db
    # if message.content.startswith("**<"): <-- FOR TESTING
    if message.author.id == CONFIG["UWCS_DISCORD_BRIDGE_BOT_ID"]:
        # Search for first "> " and strip the message from there (Since irc nicks cant have <, > in them
        idx = message.content.find(">** ")
        idx += 4
        message.content = message.content[idx:]

    await bot.process_commands(message)
Exemplo n.º 9
0
async def on_message(message: discord.Message):
    if bot.database is None or not bot.database.ready or message.author.bot:
        return
    if " && " in message.content:
        cmds_run_before = []
        failed_to_run = {}
        messages = message.content.split(" && ")
        for msg in messages:
            message.content = msg
            ctx = await bot.get_context(message, cls=cc.KernContext)
            if ctx.valid:
                if msg.strip(ctx.prefix) not in cmds_run_before:
                    await bot.invoke(ctx)
                    cmds_run_before.append(msg.strip(ctx.prefix))
                else:
                    failed_to_run[msg.strip(ctx.prefix)] = "This command has been at least once before."
            else:
                if ctx.prefix is not None:
                    failed_to_run[msg.strip(ctx.prefix)] = "Command not found."

        if failed_to_run and len(failed_to_run) != len(message.content.split(" && ")):
            errors = ""
            for fail, reason in failed_to_run.items():
                errors += f"{fail}: {reason}\n"
            await ctx.error(f"```{errors}```", "These failed to run:")

    else:
        # is a command returned
        ctx = await bot.get_context(message, cls=cc.KernContext)
        await bot.invoke(ctx)
Exemplo n.º 10
0
    async def on_message(self, message: discord.Message):
        await self.process_commands(message)
        gm = self.models[message.guild.name]
        
        if should_ignore_message(message, gm.config, self):
            return
        
        # Don't do anything unless models are ready
        if not self.ready:
            print(self._format_message(message, "NOSPEAK:NOTREADY"))
            return

        addressed = True if self.user.name.lower() in message.content.lower() else False
        message.content = clean_text(message.content, self)

        if gm.config['learn_enabled']:
            self.learn(message)
        if gm.config['really_stfu']:
            print(self._format_message(message, "NOSPEAK:RLYSTFU"))
            return
        if gm.config['stfu'] and not addressed:
            print(self._format_message(message, "NOSPEAK:STFU"))
            return
        if gm.config['ignore_bots'] and message.author.bot:
            print(self._format_message(message, "NOSPEAK:BOT"))
            return
        if not random.randint(1, 100) <= gm.config['speak_probability'] and not addressed:
            print(self._format_message(message, "NOSPEAK:PROBABILITY"))
            return
        else:
            await self.speak(message)
Exemplo n.º 11
0
async def on_message(message: Message):
    # we do not want the bot to reply to itself
    if message.author == client.user:
        return
    if message.content.startswith(client.command_prefix):
        await client.process_commands(message)
        return

    give_message_to_bot: bool = False
    message_to_give: str = message.content
    if message.content.startswith("Bubble Bot Fysallida"):
        message_to_give = message_to_give.replace("Bubble Bot Fysallida ", '',
                                                  1)
        give_message_to_bot = True
    elif message.content.startswith("Fysallida"):
        message_to_give = message_to_give.replace("Fysallida ", '', 1)
        give_message_to_bot = True
    elif message.content.startswith("Bubble Bot"):
        message_to_give = message_to_give.replace("Bubble Bot ", '', 1)
        give_message_to_bot = True
    elif message.content.startswith(client.user.mention):
        message_to_give = message_to_give.replace(client.user.mention + " ",
                                                  '', 1)
        give_message_to_bot = True

    if give_message_to_bot:
        message.content = "+" + message_to_give
        await client.process_commands(message)
Exemplo n.º 12
0
 async def check_afk(self, msg: discord.Message):
     """Check if someone pinged is afk"""
     ctx = await self.bot.get_context(msg)
     for member in msg.mentions:
         c = member.display_name.endswith(
             ' [AFK]') or member.id in self.afk_guys.keys()
         if c and member != msg.author:
             if member.id not in self.afk_guys or len(
                     self.afk_guys[member.id]) == 0:
                 await msg.channel.send(await self.translate(
                     msg.guild.id, "fun", "afk-user-2"))
             else:
                 reason = await self.bot.cogs['UtilitiesCog'].clear_msg(
                     str(await self.translate(msg.guild.id, "fun",
                                              "afk-user-1")).format(
                                                  self.afk_guys[member.id]),
                     everyone=True,
                     ctx=ctx)
                 await msg.channel.send(reason)
     if (not await checks.is_a_cmd(
             msg, self.bot)) and (ctx.author.display_name.endswith(' [AFK]')
                                  or ctx.author.id in self.afk_guys.keys()):
         user_config = await self.bot.cogs['UtilitiesCog'].get_db_userinfo(
             ["auto_unafk"], [f'`userID`={ctx.author.id}'])
         if not user_config['auto_unafk']:
             return
         msg = copy.copy(msg)
         msg.content = (await self.bot.get_prefix(msg))[-1] + 'unafk'
         new_ctx = await self.bot.get_context(msg)
         await self.bot.invoke(new_ctx)
Exemplo n.º 13
0
    async def get_context(
        self,
        msg: discord.Message,
        *,
        cls=Context,
    ) -> Context:
        """Return command invocation context."""
        ctx: Context = await super().get_context(msg, cls=Context)

        if ctx.command is None and msg.guild:
            alias = await Alias.get(
                guild_id=msg.guild.id,
                src=ctx.invoked_with,
            )
            if alias:
                msg.content = re.sub(
                    '^{}{}'.format(ctx.prefix, alias['src']),
                    '{}{}'.format(ctx.prefix, alias['dst']),
                    msg.content,
                )
                ctx = await super().get_context(
                    msg,
                    cls=Context,
                )

        return ctx
Exemplo n.º 14
0
 async def process_message(self, message: discord.Message):
     if message.guild is None:
         return message, False
     deleteMessage = False
     if message.content.lower().endswith("-del"):
         deleteMessage = True
         message.content = message.content[:-4].strip()
     guild_id = message.guild.id
     prefixes = self.message_prefixes.get(guild_id, [])
     if prefixes is None:
         prefixes = []
     for prefix in prefixes:
         match = re.match(prefix, message.content)
         if match:
             message.content = message.content[match.end() :]
             break
     return message, deleteMessage
Exemplo n.º 15
0
async def loop_command(message: discord.Message) -> None:
    parts = message.content.split(' ')
    cmd = parts[2]
    times = parts[1]
    args = ' '.join(parts[3:])
    message.content = f'{cfg.prefix}{cmd} {args}'
    for _ in range(int(times)):
        await on_message(message)
Exemplo n.º 16
0
    async def get_context(self,
                          message: discord.Message,
                          *,
                          cls=None) -> ContextPlus:
        ctx: ContextPlus = await super().get_context(message, cls=ContextPlus)

        if (ctx is None or not ctx.valid) and (user_aliases := search_for(
                self.config.Users, message.author.id, "aliases")):
            # noinspection PyUnboundLocalVariable
            for alias, command in user_aliases.items():
                back_content = message.content
                message.content = message.content.replace(alias, command, 1)

                if (ctx := await super().get_context(
                        message, cls=ContextPlus)) is None or not ctx.valid:
                    message.content = back_content
                else:
                    break
Exemplo n.º 17
0
async def on_message(message: discord.Message):
    await bot.wait_until_ready()
    message.content = (message.content.replace("—",
                                               "--").replace("'", "′").replace(
                                                   "‘", "′").replace("’", "′"))
    if message.content.startswith(settings.prefix):
        logging.info(f'[{str(message.author)}] Command: "{message.content}"')

    await bot.process_commands(message)
Exemplo n.º 18
0
    async def on_message(self, message: discord.Message):
        message.content = (
            message.content.replace("—", "--")
            .replace("'", "′")
            .replace("‘", "′")
            .replace("’", "′")
        )

        await self.process_commands(message)
Exemplo n.º 19
0
async def on_message(message: discord.Message):
    await client.wait_until_ready()
    message.content = (
        message.content.replace("—", "--")
        .replace("'", "′")
        .replace("‘", "′")
        .replace("’", "′")
    )

    await client.process_commands(message)
Exemplo n.º 20
0
    async def handle_aliases(self, message: discord.Message) -> discord.Message:
        content: str = message.content
        if message.guild.id not in self.aliases:
            return message

        if content.split(" ")[0] in self.aliases[message.guild.id]:
            message.content = " ".join([self.aliases[message.guild.id][content.split(" ")[0]]] +
                                       content.split(" ")[1:])
            return message
        return message
Exemplo n.º 21
0
    async def on_message_without_command(self, message: discord.Message):
        """
        Credit to https://github.com/Twentysix26/26-Cogs/blob/master/cleverbot/cleverbot.py
        for on_message recognition of @bot

        Credit to:
        https://github.com/Cog-Creators/Red-DiscordBot/blob/V3/develop/redbot/cogs/customcom/customcom.py#L508
        for the message filtering
        """
        ###########

        if len(message.content) < 2 or message.author.bot:
            return

        guild: discord.Guild = getattr(message, "guild", None)

        if await self.bot.cog_disabled_in_guild(self, guild):
            return

        ctx: commands.Context = await self.bot.get_context(message)

        if ctx.prefix is not None:  # Probably unnecessary, we're in on_message_without_command
            return

        ###########
        # Thank you Cog-Creators

        def my_local_get_prefix(prefixes, content):
            for p in prefixes:
                if content.startswith(p):
                    return p
            return None

        when_mentionables = commands.when_mentioned(self.bot, message)

        prefix = my_local_get_prefix(when_mentionables, message.content)

        if prefix is None:
            # print("not mentioned")
            return

        channel: discord.TextChannel = message.channel

        message.content = message.content.replace(prefix, "", 1)
        text = message.clean_content

        async with channel.typing():
            future = await self.loop.run_in_executor(None,
                                                     self.chatbot.get_response,
                                                     text)

            if future and str(future):
                await channel.send(str(future))
            else:
                await channel.send(":thinking:")
Exemplo n.º 22
0
    async def on_message(self, message: Message):
        # allow irc users to use commands by altering content to remove the nick before sending for command processing
        # note that clean_content is *not* altered and everything relies on this fact for it to work without having to go back and lookup the message in the db
        # if message.content.startswith("**<"): # <-- FOR TESTING
        if user_is_irc_bot(message):
            # Search for first "> " and strip the message from there (Since irc nicks cant have <, > in them
            idx = message.content.find(">** ")
            idx += 4
            message.content = message.content[idx:]

            await self.bot.process_commands(message)
Exemplo n.º 23
0
async def on_message(message: discord.Message):
    global INPUT_GIVEN
    global INPUT_TEXT
    if message.author.id == SELF_ID:
        return
    if message.channel != GAME_CHANNEL:
        return
    # If no input is being processed, write the current input. Later,
    # The bot can read from INPUT_TEXT to replicate input() statements
    if not INPUT_GIVEN:
        INPUT_GIVEN = True
        INPUT_TEXT = message.content()
Exemplo n.º 24
0
    def parse_cmd(self, event: DiscordEvent, message: discord.Message) -> None:
        try:
            if self.contains_keyword(msg=message.content):
                message.content = message.content.replace(
                    f"{self.__keyword} ", '')

            if ' ' in message.content:
                event.parsed_command = message.content.split(' ')[0]
            else:
                event.parsed_command = ''
        except Exception as e:
            event.parsed_command = ''
Exemplo n.º 25
0
    async def on_message(self, message: discord.Message) -> None:
        """
        Event method that gets called when the Discord client receives a new message.
        :param message: The Discord.Message that was received.
        """
        # Ignore messages from bots.
        if message.author.bot:
            return

        # Find the appropriate prefix for a server.
        prefix: str = 'wk!'
        if message.guild:
            found_guild = self._dataStorage.find_guild_prefix(
                guild_id=message.guild.id)
            if found_guild:
                prefix = found_guild['prefix']

        #############################
        # UNCOMMENT FOR MAINTENANCE #
        #############################
        """
        # Replace the ID to your Discord User ID to allow access only for you.
        if message.author.id != 209076181365030913 and message.content.startswith(prefix):
            await message.channel.send(
                content='Crabigator is being operated on. '
                        'Please try again later or contact the Lord of All <@!209076181365030913>.')
            return
        """

        # Always allow help by using wk!help.
        if message.content == 'wk!help':
            await self.get_help(words=['help'],
                                channel=message.channel,
                                prefix=prefix)

        if message.content.startswith(prefix):
            print('\n{0}'.format(message))
            print(
                'Message in {0.guild} - #{0.channel} from {0.author}: {0.content}'
                .format(message))
            message.content = message.content[len(prefix):]
            # Prevent empty commands.
            if message.content:
                self.command_count += 1
                await message.channel.trigger_typing()
                try:
                    await self.handle_command(message=message, prefix=prefix)
                except Exception as ex:
                    print(ex)
                    await self.oopsie(
                        channel=message.channel,
                        attempted_command=message.content.split(' ')[0],
                        prefix=prefix)
Exemplo n.º 26
0
	async def transfer(self, ctx, delete: typing.Optional[bool], message: discord.Message, to: discord.TextChannel, no_ping: bool = False):
		"""transfer a message from one channel to another!"""
		delete=delete if delete is not None else True
		if not dict(to.permissions_for(ctx.guild.me))['send_messages'] and not dict(to.permissions_for(ctx.guild.me))['embed_links']:
			return await ctx.send(f"I can't send messages to {to.mention}!")
		if not message.author.bot and message.author != ctx.author:
			return await ctx.send("You can only move messages by bots or by yourself!")
		try:
			m = await ctx.send("Copying content...")
			if no_ping or not dict(to.permissions_for(ctx.author))['mention_everyone']:
				message.content = message.clean_content
			if message.author != self.bot.user:
				message.content = f"*transferred*\n{message.content}"
			embed = message.embeds[0] if len(message.embeds) > 0 else None
			await m.edit(content="Sending to channel..")
			await to.send(message.content, embed=embed)
			if delete:
				await message.delete(delay=1)
			await m.edit(content="Success!")
		except Exception as e:
			await ctx.send(f"Unhandled error: `{e}`")
Exemplo n.º 27
0
    async def handle_prefix(self, message: discord.Message):
        if message.guild:
            logging.info('[message event] u=%s, g=%s : %s', message.author.id, message.guild.id, message.clean_content)
        else:
            logging.info('[message event] u=%s, g=None : %s', message.author.id, message.clean_content)

        if message.content.lower() in self.help_triggers:
            return await self.handle_help(message)
        splitter = message.content.split(' && ')
        for cmd in splitter:
            message.content = cmd
            await self.bot.process_commands(message)
Exemplo n.º 28
0
async def on_message(message: discord.Message) -> None:

    # Don't trigger on our own messages
    if message.author.id == bot.user.id:
        return

    if message.content.startswith(bot.user.mention):  # someone tagged moobot
        message.content = message.content.split(bot.user.mention +
                                                ' ')[1] + ' '
        # catch the space after the @moobot, and add a space at the end
        # saying that this isn't a hack would be a bit misrepresentative
        logging.debug('Someone tagged moobot %s ', message.content)
        await bot.process_commands(message)
Exemplo n.º 29
0
    async def on_message(self, message: discord.Message):
        if not message.content.startswith(self.prefix) or message.content == config.PREFIX \
                or message.author.bot or (self.maintenance and message.author.id != OWNER_ID):
            return
        message.content = message.content[len(self.prefix):]
        cmd = self.cmds.get_command(message.content.split(" ")[0])

        if self.cmds.is_in_cooldown(message.author, cmd.name) and message.author.id != OWNER_ID:
            m = await message.channel.send(f'{EMOJIS["x"]} **This command has a cooldown of {cmd.cooldown}s !**')
            await m.delete(delay=5)
        else:
            self.cmds.add_in_cooldown(message.author, cmd)
            await cmd.run(Context(self, message))
Exemplo n.º 30
0
    async def on_message(self, message: discord.Message):
        if not message.content:
            return

        ctx = await self.get_context(message, cls=BotContext)
        if not ctx.command and message.content[0] == PREFIX:
            message.content = f'{PREFIX}{GET} {message.content[1:]}'
            ctx = await self.get_context(message, cls=BotContext)

        if IS_DEV and not await ctx.bot.is_owner(ctx.author):
            return
        else:
            await self.invoke(ctx)