当前位置: 首页>>代码示例>>Python>>正文


Python discord.Message方法代码示例

本文整理汇总了Python中discord.Message方法的典型用法代码示例。如果您正苦于以下问题:Python discord.Message方法的具体用法?Python discord.Message怎么用?Python discord.Message使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在discord的用法示例。


在下文中一共展示了discord.Message方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: send_header

# 需要导入模块: import discord [as 别名]
# 或者: from discord import Message [as 别名]
def send_header(self, msg: Message) -> None:
        """Sends a header embed with information about the relayed messages to the watch channel."""
        user_id = msg.author.id

        guild = self.bot.get_guild(GuildConfig.id)
        actor = guild.get_member(self.watched_users[user_id]['actor'])
        actor = actor.display_name if actor else self.watched_users[user_id]['actor']

        inserted_at = self.watched_users[user_id]['inserted_at']
        time_delta = self._get_time_delta(inserted_at)

        reason = self.watched_users[user_id]['reason']

        if isinstance(msg.channel, DMChannel):
            # If a watched user DMs the bot there won't be a channel name or jump URL
            # This could technically include a GroupChannel but bot's can't be in those
            message_jump = "via DM"
        else:
            message_jump = f"in [#{msg.channel.name}]({msg.jump_url})"

        footer = f"Added {time_delta} by {actor} | Reason: {reason}"
        embed = Embed(description=f"{msg.author.mention} {message_jump}")
        embed.set_footer(text=textwrap.shorten(footer, width=128, placeholder="..."))

        await self.webhook_send(embed=embed, username=msg.author.display_name, avatar_url=msg.author.avatar_url) 
开发者ID:python-discord,项目名称:bot,代码行数:27,代码来源:watchchannel.py

示例2: punish

# 需要导入模块: import discord [as 别名]
# 或者: from discord import Message [as 别名]
def punish(self, msg: Message, member: Member, reason: str) -> None:
        """Punishes the given member for triggering an antispam rule."""
        if not any(role.id == self.muted_role.id for role in member.roles):
            remove_role_after = AntiSpamConfig.punishment['remove_after']

            # Get context and make sure the bot becomes the actor of infraction by patching the `author` attributes
            context = await self.bot.get_context(msg)
            context.author = self.bot.user
            context.message.author = self.bot.user

            # Since we're going to invoke the tempmute command directly, we need to manually call the converter.
            dt_remove_role_after = await self.expiration_date_converter.convert(context, f"{remove_role_after}S")
            await context.invoke(
                self.bot.get_command('tempmute'),
                member,
                dt_remove_role_after,
                reason=reason
            ) 
开发者ID:python-discord,项目名称:bot,代码行数:20,代码来源:antispam.py

示例3: maybe_delete_messages

# 需要导入模块: import discord [as 别名]
# 或者: from discord import Message [as 别名]
def maybe_delete_messages(self, channel: TextChannel, messages: List[Message]) -> None:
        """Cleans the messages if cleaning is configured."""
        if AntiSpamConfig.clean_offending:
            # If we have more than one message, we can use bulk delete.
            if len(messages) > 1:
                message_ids = [message.id for message in messages]
                self.mod_log.ignore(Event.message_delete, *message_ids)
                await channel.delete_messages(messages)

            # Otherwise, the bulk delete endpoint will throw up.
            # Delete the message directly instead.
            else:
                self.mod_log.ignore(Event.message_delete, messages[0].id)
                try:
                    await messages[0].delete()
                except NotFound:
                    log.info(f"Tried to delete message `{messages[0].id}`, but message could not be found.") 
开发者ID:python-discord,项目名称:bot,代码行数:19,代码来源:antispam.py

示例4: check_for_answer

# 需要导入模块: import discord [as 别名]
# 或者: from discord import Message [as 别名]
def check_for_answer(self, message: discord.Message) -> None:
        """Checks for whether new content in a help channel comes from non-claimants."""
        channel = message.channel

        # Confirm the channel is an in use help channel
        if self.is_in_category(channel, constants.Categories.help_in_use):
            log.trace(f"Checking if #{channel} ({channel.id}) has been answered.")

            # Check if there is an entry in unanswered
            if await self.unanswered.contains(channel.id):
                claimant_id = await self.help_channel_claimants.get(channel.id)
                if not claimant_id:
                    # The mapping for this channel doesn't exist, we can't do anything.
                    return

                # Check the message did not come from the claimant
                if claimant_id != message.author.id:
                    # Mark the channel as answered
                    await self.unanswered.set(channel.id, False) 
开发者ID:python-discord,项目名称:bot,代码行数:21,代码来源:help_channels.py

示例5: on_message_delete

# 需要导入模块: import discord [as 别名]
# 或者: from discord import Message [as 别名]
def on_message_delete(self, msg: discord.Message) -> None:
        """
        Reschedule an in-use channel to become dormant sooner if the channel is empty.

        The new time for the dormant task is configured with `HelpChannels.deleted_idle_minutes`.
        """
        if not self.is_in_category(msg.channel, constants.Categories.help_in_use):
            return

        if not await self.is_empty(msg.channel):
            return

        log.info(f"Claimant of #{msg.channel} ({msg.author}) deleted message, channel is empty now. Rescheduling task.")

        # Cancel existing dormant task before scheduling new.
        self.cancel_task(msg.channel.id)

        task = TaskData(constants.HelpChannels.deleted_idle_minutes * 60, self.move_idle_channel(msg.channel))
        self.schedule_task(msg.channel.id, task) 
开发者ID:python-discord,项目名称:bot,代码行数:21,代码来源:help_channels.py

示例6: get_code

# 需要导入模块: import discord [as 别名]
# 或者: from discord import Message [as 别名]
def get_code(self, message: Message) -> Optional[str]:
        """
        Return the code from `message` to be evaluated.

        If the message is an invocation of the eval command, return the first argument or None if it
        doesn't exist. Otherwise, return the full content of the message.
        """
        log.trace(f"Getting context for message {message.id}.")
        new_ctx = await self.bot.get_context(message)

        if new_ctx.command is self.eval_command:
            log.trace(f"Message {message.id} invokes eval command.")
            split = message.content.split(maxsplit=1)
            code = split[1] if len(split) > 1 else None
        else:
            log.trace(f"Message {message.id} does not invoke eval command.")
            code = message.content

        return code 
开发者ID:python-discord,项目名称:bot,代码行数:21,代码来源:snekbox.py

示例7: help_cleanup

# 需要导入模块: import discord [as 别名]
# 或者: from discord import Message [as 别名]
def help_cleanup(bot: Bot, author: Member, message: Message) -> None:
    """
    Runs the cleanup for the help command.

    Adds the :trashcan: reaction that, when clicked, will delete the help message.
    After a 300 second timeout, the reaction will be removed.
    """
    def check(reaction: Reaction, user: User) -> bool:
        """Checks the reaction is :trashcan:, the author is original author and messages are the same."""
        return str(reaction) == DELETE_EMOJI and user.id == author.id and reaction.message.id == message.id

    await message.add_reaction(DELETE_EMOJI)

    try:
        await bot.wait_for("reaction_add", check=check, timeout=300)
        await message.delete()
    except TimeoutError:
        await message.remove_reaction(DELETE_EMOJI, bot.user)
    except NotFound:
        pass 
开发者ID:python-discord,项目名称:bot,代码行数:22,代码来源:help.py

示例8: _has_rich_embed

# 需要导入模块: import discord [as 别名]
# 或者: from discord import Message [as 别名]
def _has_rich_embed(msg: Message) -> bool:
        """Determines if `msg` contains any rich embeds not auto-generated from a URL."""
        if msg.embeds:
            for embed in msg.embeds:
                if embed.type == "rich":
                    urls = URL_RE.findall(msg.content)
                    if not embed.url or embed.url not in urls:
                        # If `embed.url` does not exist or if `embed.url` is not part of the content
                        # of the message, it's unlikely to be an auto-generated embed by Discord.
                        return True
                    else:
                        log.trace(
                            "Found a rich embed sent by a regular user account, "
                            "but it was likely just an automatic URL embed."
                        )
                        return False
        return False 
开发者ID:python-discord,项目名称:bot,代码行数:19,代码来源:filtering.py

示例9: apply

# 需要导入模块: import discord [as 别名]
# 或者: from discord import Message [as 别名]
def apply(
    last_message: Message, recent_messages: List[Message], config: Dict[str, int]
) -> Optional[Tuple[str, Iterable[Member], Iterable[Message]]]:
    """Detects repeated messages sent by a single user."""
    relevant_messages = tuple(
        msg
        for msg in recent_messages
        if msg.author == last_message.author
    )
    total_relevant = len(relevant_messages)

    if total_relevant > config['max']:
        return (
            f"sent {total_relevant} messages in {config['interval']}s",
            (last_message.author,),
            relevant_messages
        )
    return None 
开发者ID:python-discord,项目名称:bot,代码行数:20,代码来源:burst.py

示例10: apply

# 需要导入模块: import discord [as 别名]
# 或者: from discord import Message [as 别名]
def apply(
    last_message: Message, recent_messages: List[Message], config: Dict[str, int]
) -> Optional[Tuple[str, Iterable[Member], Iterable[Message]]]:
    """Detects total attachments exceeding the limit sent by a single user."""
    relevant_messages = tuple(
        msg
        for msg in recent_messages
        if (
            msg.author == last_message.author
            and len(msg.attachments) > 0
        )
    )
    total_recent_attachments = sum(len(msg.attachments) for msg in relevant_messages)

    if total_recent_attachments > config['max']:
        return (
            f"sent {total_recent_attachments} attachments in {config['interval']}s",
            (last_message.author,),
            relevant_messages
        )
    return None 
开发者ID:python-discord,项目名称:bot,代码行数:23,代码来源:attachments.py

示例11: apply

# 需要导入模块: import discord [as 别名]
# 或者: from discord import Message [as 别名]
def apply(
    last_message: Message, recent_messages: List[Message], config: Dict[str, int]
) -> Optional[Tuple[str, Iterable[Member], Iterable[Message]]]:
    """Detects total message char count exceeding the limit sent by a single user."""
    relevant_messages = tuple(
        msg
        for msg in recent_messages
        if msg.author == last_message.author
    )

    total_recent_chars = sum(len(msg.content) for msg in relevant_messages)

    if total_recent_chars > config['max']:
        return (
            f"sent {total_recent_chars} characters in {config['interval']}s",
            (last_message.author,),
            relevant_messages
        )
    return None 
开发者ID:python-discord,项目名称:bot,代码行数:21,代码来源:chars.py

示例12: apply

# 需要导入模块: import discord [as 别名]
# 或者: from discord import Message [as 别名]
def apply(
    last_message: Message, recent_messages: List[Message], config: Dict[str, int]
) -> Optional[Tuple[str, Iterable[Member], Iterable[Message]]]:
    """Detects total Discord emojis (excluding Unicode emojis) exceeding the limit sent by a single user."""
    relevant_messages = tuple(
        msg
        for msg in recent_messages
        if msg.author == last_message.author
    )

    total_emojis = sum(
        len(DISCORD_EMOJI_RE.findall(msg.content))
        for msg in relevant_messages
    )

    if total_emojis > config['max']:
        return (
            f"sent {total_emojis} emojis in {config['interval']}s",
            (last_message.author,),
            relevant_messages
        )
    return None 
开发者ID:python-discord,项目名称:bot,代码行数:24,代码来源:discord_emojis.py

示例13: apply

# 需要导入模块: import discord [as 别名]
# 或者: from discord import Message [as 别名]
def apply(
    last_message: Message, recent_messages: List[Message], config: Dict[str, int]
) -> Optional[Tuple[str, Iterable[Member], Iterable[Message]]]:
    """Detects total role mentions exceeding the limit sent by a single user."""
    relevant_messages = tuple(
        msg
        for msg in recent_messages
        if msg.author == last_message.author
    )

    total_recent_mentions = sum(len(msg.role_mentions) for msg in relevant_messages)

    if total_recent_mentions > config['max']:
        return (
            f"sent {total_recent_mentions} role mentions in {config['interval']}s",
            (last_message.author,),
            relevant_messages
        )
    return None 
开发者ID:python-discord,项目名称:bot,代码行数:21,代码来源:role_mentions.py

示例14: apply

# 需要导入模块: import discord [as 别名]
# 或者: from discord import Message [as 别名]
def apply(
    last_message: Message, recent_messages: List[Message], config: Dict[str, int]
) -> Optional[Tuple[str, Iterable[Member], Iterable[Message]]]:
    """Detects total mentions exceeding the limit sent by a single user."""
    relevant_messages = tuple(
        msg
        for msg in recent_messages
        if msg.author == last_message.author
    )

    total_recent_mentions = sum(len(msg.mentions) for msg in relevant_messages)

    if total_recent_mentions > config['max']:
        return (
            f"sent {total_recent_mentions} mentions in {config['interval']}s",
            (last_message.author,),
            relevant_messages
        )
    return None 
开发者ID:python-discord,项目名称:bot,代码行数:21,代码来源:mentions.py

示例15: convert

# 需要导入模块: import discord [as 别名]
# 或者: from discord import Message [as 别名]
def convert(self, ctx, argument):
        id_regex = re.compile(r'^(?:(?P<channel_id>[0-9]{15,21})-)?(?P<message_id>[0-9]{15,21})$')
        link_regex = re.compile(
            r'^https?://(?:(ptb|canary)\.)?discord(?:app)?\.com/channels/'
            r'(?:([0-9]{15,21})|(@me))'
            r'/(?P<channel_id>[0-9]{15,21})/(?P<message_id>[0-9]{15,21})/?$'
        )
        match = id_regex.match(argument) or link_regex.match(argument)
        if not match:
            raise BadArgument('Message "{msg}" not found.'.format(msg=argument))
        message_id = int(match.group("message_id"))
        channel_id = match.group("channel_id")
        message = ctx.bot._connection._get_message(message_id)
        if message:
            return message
        channel = ctx.bot.get_channel(int(channel_id)) if channel_id else ctx.channel
        if not channel:
            raise BadArgument('Channel "{channel}" not found.'.format(channel=channel_id))
        try:
            return await channel.fetch_message(message_id)
        except discord.NotFound:
            raise BadArgument('Message "{msg}" not found.'.format(msg=argument))
        except discord.Forbidden:
            raise BadArgument("Can't read messages in {channel}".format(channel=channel.mention)) 
开发者ID:Rapptz,项目名称:discord.py,代码行数:26,代码来源:converter.py


注:本文中的discord.Message方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。