Python discord.Member() Examples

The following are 30 code examples of discord.Member(). 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: modlog.py    From bot with MIT License 7 votes vote down vote up
def on_member_remove(self, member: discord.Member) -> None:
        """Log member leave event to user log."""
        if member.guild.id != GuildConstant.id:
            return

        if member.id in self._ignored[Event.member_remove]:
            self._ignored[Event.member_remove].remove(member.id)
            return

        member_str = escape_markdown(str(member))
        await self.send_log_message(
            Icons.sign_out, Colours.soft_red,
            "User left", f"{member_str} (`{member.id}`)",
            thumbnail=member.avatar_url_as(static_format="png"),
            channel_id=Channels.user_log
        ) 
Example #2
Source File: help_channels.py    From bot with MIT License 7 votes vote down vote up
def revoke_send_permissions(self, member: discord.Member) -> None:
        """
        Disallow `member` to send messages in the Available category for a certain time.

        The time until permissions are reinstated can be configured with
        `HelpChannels.claim_minutes`.
        """
        log.trace(
            f"Revoking {member}'s ({member.id}) send message permissions in the Available category."
        )

        await self.add_cooldown_role(member)

        # Cancel the existing task, if any.
        # Would mean the user somehow bypassed the lack of permissions (e.g. user is guild owner).
        self.cancel_task(member.id, ignore_missing=True)

        await self.schedule_cooldown_expiration(member, constants.HelpChannels.claim_minutes * 60) 
Example #3
Source File: modlog.py    From bot with MIT License 6 votes vote down vote up
def on_member_join(self, member: discord.Member) -> None:
        """Log member join event to user log."""
        if member.guild.id != GuildConstant.id:
            return

        member_str = escape_markdown(str(member))
        message = f"{member_str} (`{member.id}`)"
        now = datetime.utcnow()
        difference = abs(relativedelta(now, member.created_at))

        message += "\n\n**Account age:** " + humanize_delta(difference)

        if difference.days < 1 and difference.months < 1 and difference.years < 1:  # New user account!
            message = f"{Emojis.new} {message}"

        await self.send_log_message(
            Icons.sign_in, Colours.soft_green,
            "User joined", message,
            thumbnail=member.avatar_url_as(static_format="png"),
            channel_id=Channels.user_log
        ) 
Example #4
Source File: mentions.py    From bot with MIT License 6 votes vote down vote up
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 
Example #5
Source File: information.py    From bot with MIT License 6 votes vote down vote up
def basic_user_infraction_counts(self, member: Member) -> str:
        """Gets the total and active infraction counts for the given `member`."""
        infractions = await self.bot.api_client.get(
            'bot/infractions',
            params={
                'hidden': 'False',
                'user__id': str(member.id)
            }
        )

        total_infractions = len(infractions)
        active_infractions = sum(infraction['active'] for infraction in infractions)

        infraction_output = f"**Infractions**\nTotal: {total_infractions}\nActive: {active_infractions}"

        return infraction_output 
Example #6
Source File: information.py    From bot with MIT License 6 votes vote down vote up
def user_info(self, ctx: Context, user: Member = None) -> None:
        """Returns info about a user."""
        if user is None:
            user = ctx.author

        # Do a role check if this is being executed on someone other than the caller
        elif user != ctx.author and not with_role_check(ctx, *constants.MODERATION_ROLES):
            await ctx.send("You may not use this command on users other than yourself.")
            return

        # Non-staff may only do this in #bot-commands
        if not with_role_check(ctx, *constants.STAFF_ROLES):
            if not ctx.channel.id == constants.Channels.bot_commands:
                raise InWhitelistCheckFailure(constants.Channels.bot_commands)

        embed = await self.create_user_embed(ctx, user)

        await ctx.send(embed=embed) 
Example #7
Source File: chars.py    From bot with MIT License 6 votes vote down vote up
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 
Example #8
Source File: converter.py    From discord.py with MIT License 6 votes vote down vote up
def convert(self, ctx, argument):
        bot = ctx.bot
        match = self._get_id_match(argument) or re.match(r'<@!?([0-9]+)>$', argument)
        guild = ctx.guild
        result = None
        if match is None:
            # not a mention...
            if guild:
                result = guild.get_member_named(argument)
            else:
                result = _get_from_guilds(bot, 'get_member_named', argument)
        else:
            user_id = int(match.group(1))
            if guild:
                result = guild.get_member(user_id) or _utils_get(ctx.message.mentions, id=user_id)
            else:
                result = _get_from_guilds(bot, 'get_member', user_id)

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

        return result 
Example #9
Source File: defcon.py    From bot with MIT License 6 votes vote down vote up
def send_defcon_log(self, action: Action, actor: Member, e: Exception = None) -> None:
        """Send log message for DEFCON action."""
        info = action.value
        log_msg: str = (
            f"**Staffer:** {actor.mention} {actor} (`{actor.id}`)\n"
            f"{info.template.format(days=self.days.days)}"
        )
        status_msg = f"DEFCON {action.name.lower()}"

        if e:
            log_msg += (
                "**There was a problem updating the site** - This setting may be reverted when the bot restarts.\n\n"
                f"```py\n{e}\n```"
            )

        await self.mod_log.send_log_message(info.icon, info.color, status_msg, log_msg) 
Example #10
Source File: attachments.py    From bot with MIT License 6 votes vote down vote up
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 
Example #11
Source File: modofail.py    From Penny-Dreadful-Tools with GNU General Public License v3.0 6 votes vote down vote up
def modofail(ctx: MtgContext, args: Optional[str]) -> None:
    """Ding!"""
    if args is not None and args.lower() == 'reset':
        redis.clear(f'modofail:{ctx.guild}')
    author = ctx.author
    if isinstance(author, Member) and hasattr(author, 'voice') and author.voice is not None and author.voice.channel is not None:
        voice_channel = ctx.author.voice.channel
        voice = ctx.channel.guild.voice_client
        if voice is None:
            voice = await voice_channel.connect()
        elif voice.channel != voice_channel:
            voice.move_to(voice_channel)
        voice.play(FFmpegPCMAudio('ding.ogg'))
    n = redis.increment(f'modofail:{ctx.guild}')
    redis.expire(f'modofail:{ctx.guild}', 3600)
    await ctx.send(f':bellhop: **MODO fail** {n}') 
Example #12
Source File: burst.py    From bot with MIT License 6 votes vote down vote up
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 
Example #13
Source File: information.py    From bot with MIT License 6 votes vote down vote up
def user_nomination_counts(self, member: Member) -> str:
        """Gets the active and historical nomination counts for the given `member`."""
        nominations = await self.bot.api_client.get(
            'bot/nominations',
            params={
                'user__id': str(member.id)
            }
        )

        output = ["**Nominations**"]

        if not nominations:
            output.append("This user has never been nominated.")
        else:
            count = len(nominations)
            is_currently_nominated = any(nomination["active"] for nomination in nominations)
            nomination_noun = "nomination" if count == 1 else "nominations"

            if is_currently_nominated:
                output.append(f"This user is **currently** nominated ({count} {nomination_noun} in total).")
            else:
                output.append(f"This user has {count} historical {nomination_noun}, but is currently not nominated.")

        return "\n".join(output) 
Example #14
Source File: bot.py    From Penny-Dreadful-Tools with GNU General Public License v3.0 6 votes vote down vote up
def on_reaction_add(self, reaction: Reaction, author: Member) -> None:
        if reaction.message.author == self.user:
            c = reaction.count
            if reaction.me:
                c = c - 1
            if c > 0 and not reaction.custom_emoji and reaction.emoji == '❎':
                try:
                    await reaction.message.delete()
                except NotFound: # Someone beat us to it?
                    pass
            elif c > 0 and 'Ambiguous name for ' in reaction.message.content and reaction.emoji in command.DISAMBIGUATION_EMOJIS_BY_NUMBER.values():
                async with reaction.message.channel.typing():
                    search = re.search(r'Ambiguous name for ([^\.]*)\. Suggestions: (.*)', reaction.message.content)
                    if search:
                        previous_command, suggestions = search.group(1, 2)
                        card = re.findall(r':[^:]*?: ([^:]*) ', suggestions + ' ')[command.DISAMBIGUATION_NUMBERS_BY_EMOJI[reaction.emoji]-1]
                        # pylint: disable=protected-access
                        message = Container(content='!{c} {a}'.format(c=previous_command, a=card), channel=reaction.message.channel, author=author, reactions=[], _state=reaction.message._state)
                        await self.on_message(message)
                        await reaction.message.delete() 
Example #15
Source File: sheetManager.py    From avrae with GNU General Public License v3.0 6 votes vote down vote up
def transferchar(self, ctx, user: discord.Member):
        """Gives a copy of the active character to another user."""
        character: Character = await Character.from_ctx(ctx)
        overwrite = ''

        conflict = await self.bot.mdb.characters.find_one({"owner": str(user.id), "upstream": character.upstream})
        if conflict:
            overwrite = "**WARNING**: This will overwrite an existing character."

        await ctx.send(f"{user.mention}, accept a copy of {character.name}? (Type yes/no)\n{overwrite}")
        try:
            m = await self.bot.wait_for('message', timeout=300,
                                        check=lambda msg: msg.author == user
                                                          and msg.channel == ctx.channel
                                                          and get_positivity(msg.content) is not None)
        except asyncio.TimeoutError:
            m = None

        if m is None or not get_positivity(m.content): return await ctx.send("Transfer not confirmed, aborting.")

        character.owner = str(user.id)
        await character.commit(ctx)
        await ctx.send(f"Copied {character.name} to {user.display_name}'s storage.") 
Example #16
Source File: help_channels.py    From bot with MIT License 6 votes vote down vote up
def _change_cooldown_role(self, member: discord.Member, coro_func: CoroutineFunc) -> None:
        """
        Change `member`'s cooldown role via awaiting `coro_func` and handle errors.

        `coro_func` is intended to be `discord.Member.add_roles` or `discord.Member.remove_roles`.
        """
        guild = self.bot.get_guild(constants.Guild.id)
        role = guild.get_role(constants.Roles.help_cooldown)
        if role is None:
            log.warning(f"Help cooldown role ({constants.Roles.help_cooldown}) could not be found!")
            return

        try:
            await coro_func(role)
        except discord.NotFound:
            log.debug(f"Failed to change role for {member} ({member.id}): member not found")
        except discord.Forbidden:
            log.debug(
                f"Forbidden to change role for {member} ({member.id}); "
                f"possibly due to role hierarchy"
            )
        except discord.HTTPException as e:
            log.error(f"Failed to change role for {member} ({member.id}): {e.status} {e.code}") 
Example #17
Source File: role_mentions.py    From bot with MIT License 6 votes vote down vote up
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 
Example #18
Source File: infractions.py    From bot with MIT License 6 votes vote down vote up
def pardon_mute(self, user_id: int, guild: discord.Guild, reason: t.Optional[str]) -> t.Dict[str, str]:
        """Remove a user's muted role, DM them a notification, and return a log dict."""
        user = guild.get_member(user_id)
        log_text = {}

        if user:
            # Remove the muted role.
            self.mod_log.ignore(Event.member_update, user.id)
            await user.remove_roles(self._muted_role, reason=reason)

            # DM the user about the expiration.
            notified = await utils.notify_pardon(
                user=user,
                title="You have been unmuted",
                content="You may now send messages in the server.",
                icon_url=utils.INFRACTION_ICONS["mute"][1]
            )

            log_text["Member"] = f"{user.mention}(`{user.id}`)"
            log_text["DM"] = "Sent" if notified else "**Failed**"
        else:
            log.info(f"Failed to unmute user {user_id}: user not found")
            log_text["Failure"] = "User was not found in the guild."

        return log_text 
Example #19
Source File: antispam.py    From bot with MIT License 6 votes vote down vote up
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
            ) 
Example #20
Source File: antispam.py    From bot with MIT License 6 votes vote down vote up
def add(self, rule_name: str, members: Iterable[Member], messages: Iterable[Message]) -> None:
        """Adds new rule violation events to the deletion context."""
        self.rules.add(rule_name)

        for member in members:
            if member.id not in self.members:
                self.members[member.id] = member

        for message in messages:
            if message.id not in self.messages:
                self.messages[message.id] = message

                # Re-upload attachments
                destination = message.guild.get_channel(Channels.attachment_log)
                urls = await send_attachments(message, destination, link_large=False)
                self.attachments.append(urls) 
Example #21
Source File: discord_emojis.py    From bot with MIT License 6 votes vote down vote up
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 
Example #22
Source File: infractions.py    From bot with MIT License 6 votes vote down vote up
def apply_mute(self, ctx: Context, user: Member, reason: t.Optional[str], **kwargs) -> None:
        """Apply a mute infraction with kwargs passed to `post_infraction`."""
        if await utils.get_active_infraction(ctx, user, "mute"):
            return

        infraction = await utils.post_infraction(ctx, user, "mute", reason, active=True, **kwargs)
        if infraction is None:
            return

        self.mod_log.ignore(Event.member_update, user.id)

        async def action() -> None:
            await user.add_roles(self._muted_role, reason=reason)

            log.trace(f"Attempting to kick {user} from voice because they've been muted.")
            await user.move_to(None, reason=reason)

        await self.apply_infraction(ctx, infraction, user, action()) 
Example #23
Source File: infractions.py    From bot with MIT License 6 votes vote down vote up
def on_member_join(self, member: Member) -> None:
        """Reapply active mute infractions for returning members."""
        active_mutes = await self.bot.api_client.get(
            "bot/infractions",
            params={
                "active": "true",
                "type": "mute",
                "user__id": member.id
            }
        )

        if active_mutes:
            reason = f"Re-applying active mute: {active_mutes[0]['id']}"
            action = member.add_roles(self._muted_role, reason=reason)

            await self.reapply_infraction(active_mutes[0], action)

    # region: Permanent infractions 
Example #24
Source File: infractions.py    From bot with MIT License 6 votes vote down vote up
def shadow_tempmute(
        self, ctx: Context,
        user: Member,
        duration: Expiry,
        *,
        reason: t.Optional[str] = None
    ) -> None:
        """
        Temporarily mute a user for the given reason and duration without notifying the user.

        A unit of time should be appended to the duration.
        Units (∗case-sensitive):
        \u2003`y` - years
        \u2003`m` - months∗
        \u2003`w` - weeks
        \u2003`d` - days
        \u2003`h` - hours
        \u2003`M` - minutes∗
        \u2003`s` - seconds

        Alternatively, an ISO 8601 timestamp can be provided for the duration.
        """
        await self.apply_mute(ctx, user, reason, expires_at=duration, hidden=True) 
Example #25
Source File: customization.py    From avrae with GNU General Public License v3.0 5 votes vote down vote up
def gvar_editor(self, ctx, name, user: discord.Member = None):
        """Toggles the editor status of a user."""
        gvar = await self.bot.mdb.gvars.find_one({"key": name})
        if gvar is None:
            return await ctx.send("Global variable not found.")

        if user is not None:
            if gvar['owner'] != str(ctx.author.id):
                return await ctx.send("You are not the owner of this variable.")
            else:
                e = gvar.get('editors', [])
                if str(user.id) in e:
                    e.remove(str(user.id))
                    msg = f"Removed {user} from the editor list."
                else:
                    e.append(str(user.id))
                    msg = f"Added {user} to the editor list."
                await self.bot.mdb.gvars.update_one({"key": name}, {"$set": {"editors": e}})
            await ctx.send(f'Global variable `{name}` edited: {msg}')
        else:
            embed = EmbedWithAuthor(ctx)
            embed.title = "Editors"
            editor_mentions = []
            for editor in gvar.get('editors', []):
                editor_mentions.append(f"<@{editor}>")
            embed.description = ', '.join(editor_mentions) or "No editors."
            await ctx.send(embed=embed) 
Example #26
Source File: basic_bot.py    From discord.py with MIT License 5 votes vote down vote up
def joined(ctx, member: discord.Member):
    """Says when a member joined."""
    await ctx.send('{0.name} joined in {0.joined_at}'.format(member)) 
Example #27
Source File: converters.py    From bot with MIT License 5 votes vote down vote up
def proxy_user(user_id: str) -> discord.Object:
    """
    Create a proxy user object from the given id.

    Used when a Member or User object cannot be resolved.
    """
    log.trace(f"Attempting to create a proxy user for the user id {user_id}.")

    try:
        user_id = int(user_id)
    except ValueError:
        log.debug(f"Failed to create proxy user {user_id}: could not convert to int.")
        raise BadArgument(f"User ID `{user_id}` is invalid - could not convert to an integer.")

    user = discord.Object(user_id)
    user.mention = user.id
    user.display_name = f"<@{user.id}>"
    user.avatar_url_as = lambda static_format: None
    user.bot = False

    return user 
Example #28
Source File: converters.py    From bot with MIT License 5 votes vote down vote up
def convert(ctx: Context, arg: str) -> t.Union[discord.Member, str]:
        """Check if the argument is a Discord user, and if not, falls back to a string."""
        try:
            maybe_snowflake = arg.strip("<@!>")
            return await ctx.bot.fetch_user(maybe_snowflake)
        except (discord.NotFound, discord.HTTPException):
            return arg 
Example #29
Source File: infractions.py    From bot with MIT License 5 votes vote down vote up
def apply_kick(self, ctx: Context, user: Member, reason: t.Optional[str], **kwargs) -> None:
        """Apply a kick infraction with kwargs passed to `post_infraction`."""
        infraction = await utils.post_infraction(ctx, user, "kick", reason, active=False, **kwargs)
        if infraction is None:
            return

        self.mod_log.ignore(Event.member_remove, user.id)

        if reason:
            reason = textwrap.shorten(reason, width=512, placeholder="...")

        action = user.kick(reason=reason)
        await self.apply_infraction(ctx, infraction, user, action) 
Example #30
Source File: infractions.py    From bot with MIT License 5 votes vote down vote up
def shadow_kick(self, ctx: Context, user: Member, *, reason: t.Optional[str] = None) -> None:
        """Kick a user for the given reason without notifying the user."""
        await self.apply_kick(ctx, user, reason, hidden=True, active=False)