Python discord.User() Examples

The following are 30 code examples of discord.User(). 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: converters.py    From bot with MIT License 6 votes vote down vote up
def convert(self, ctx: Context, arg: str) -> t.Union[discord.User, discord.Object]:
        """Convert the `arg` to a `discord.User` or `discord.Object`."""
        try:
            return await super().convert(ctx, arg)
        except BadArgument:
            pass

        try:
            user_id = int(arg)
            log.trace(f"Fetching user {user_id}...")
            return await ctx.bot.fetch_user(user_id)
        except ValueError:
            log.debug(f"Failed to fetch user {arg}: could not convert to int.")
            raise BadArgument(f"The provided argument can't be turned into integer: `{arg}`")
        except discord.HTTPException as e:
            # If the Discord error isn't `Unknown user`, return a proxy instead
            if e.code != 10013:
                log.info(f"Failed to fetch user, returning a proxy instead: status {e.status}")
                return proxy_user(arg)

            log.debug(f"Failed to fetch user {arg}: user does not exist.")
            raise BadArgument(f"User `{arg}` does not exist") 
Example #3
Source File: thread.py    From modmail with GNU Affero General Public License v3.0 6 votes vote down vote up
def __init__(
        self,
        manager: "ThreadManager",
        recipient: typing.Union[discord.Member, discord.User, int],
        channel: typing.Union[discord.DMChannel, discord.TextChannel] = None,
    ):
        self.manager = manager
        self.bot = manager.bot
        if isinstance(recipient, int):
            self._id = recipient
            self._recipient = None
        else:
            if recipient.bot:
                raise CommandError("Recipient cannot be a bot.")
            self._id = recipient.id
            self._recipient = recipient
        self._channel = channel
        self.genesis_message = None
        self._ready_event = asyncio.Event()
        self.close_task = None
        self.auto_close_task = None 
Example #4
Source File: incident.py    From apex-sigma-core with GNU General Public License v3.0 6 votes vote down vote up
def edit(self, user, reason):
        """
        Edits the incident reason/description
        and stores the user who edited it.
        :param user: The user that edited the description.
        :type user: discord.Member or discord.User
        :param reason: The new reason text contents.
        :type reason: str
        :return:
        :rtype:
        """
        previous = self.to_dict()
        del previous['edits']
        self.reason = reason
        by = IncidentUser(user)
        when = arrow.utcnow().float_timestamp
        self.edits.append({'moderator': by.to_dict(), 'timestamp': when, 'previous': previous}) 
Example #5
Source File: sigma.py    From apex-sigma-core with GNU General Public License v3.0 6 votes vote down vote up
def on_ready(self):
        """
        Starts events when the full client connection process is finished.
        :return:
        """
        self.gateway_finish = arrow.utcnow().float_timestamp
        self.log.info(f'Gateway connection established in {round(self.gateway_finish - self.gateway_start, 3)}s')
        self.ready = True
        self.log.info('---------------------------------')
        self.log.info('Apex Sigma Fully Loaded and Ready')
        self.log.info('---------------------------------')
        self.log.info(f'User Account: {self.user.name}#{self.user.discriminator}')
        self.log.info(f'User Snowflake: {self.user.id}')
        self.log.info('---------------------------------')
        self.log.info('Launching On-Ready Modules...')
        self.loop.create_task(self.queue.event_runner('ready'))
        self.log.info('All On-Ready Module Loops Created')
        self.log.info('---------------------------------') 
Example #6
Source File: captcha.py    From calebj-cogs with GNU General Public License v3.0 6 votes vote down vote up
def _approve(self, user: discord.User, delay=None):
        await self.cancel(user)

        if delay:
            await asyncio.sleep(delay)

        if isinstance(user, discord.Member):
            member = user
        else:
            member = self.server.get_member(user.id)

        if not (member and self.enabled and self.role):
            return False
        elif self.role_mode:
            await self.cog.bot.add_roles(member, self.role)
        else:
            await self.cog.bot.remove_roles(member, self.role) 
Example #7
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 #8
Source File: bot.py    From modmail with GNU Affero General Public License v3.0 6 votes vote down vote up
def check_guild_age(self, author: discord.Member) -> bool:
        guild_age = self.config.get("guild_age")
        now = datetime.utcnow()

        if not hasattr(author, "joined_at"):
            logger.warning("Not in guild, cannot verify guild_age, %s.", author.name)
            return True

        try:
            min_guild_age = author.joined_at + guild_age
        except ValueError:
            logger.warning("Error with 'guild_age'.", exc_info=True)
            min_guild_age = author.joined_at + self.config.remove("guild_age")

        if min_guild_age > now:
            # User has not stayed in the guild for long enough
            delta = human_timedelta(min_guild_age)
            logger.debug("Blocked due to guild age, user %s.", author.name)

            if str(author.id) not in self.blocked_users:
                new_reason = f"System Message: Recently Joined. Required to wait for {delta}."
                self.blocked_users[str(author.id)] = new_reason

            return False
        return True 
Example #9
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 #10
Source File: remindme.py    From 26-Cogs with GNU General Public License v3.0 6 votes vote down vote up
def check_reminders(self):
        while self is self.bot.get_cog("RemindMe"):
            to_remove = []
            for reminder in self.reminders:
                if reminder["FUTURE"] <= int(time.time()):
                    try:
                        await self.bot.send_message(discord.User(id=reminder["ID"]), "You asked me to remind you this:\n{}".format(reminder["TEXT"]))
                    except (discord.errors.Forbidden, discord.errors.NotFound):
                        to_remove.append(reminder)
                    except discord.errors.HTTPException:
                        pass
                    else:
                        to_remove.append(reminder)
            for reminder in to_remove:
                self.reminders.remove(reminder)
            if to_remove:
                fileIO("data/remindme/reminders.json", "save", self.reminders)
            await asyncio.sleep(5) 
Example #11
Source File: bot.py    From modmail with GNU Affero General Public License v3.0 6 votes vote down vote up
def check_account_age(self, author: discord.Member) -> bool:
        account_age = self.config.get("account_age")
        now = datetime.utcnow()

        try:
            min_account_age = author.created_at + account_age
        except ValueError:
            logger.warning("Error with 'account_age'.", exc_info=True)
            min_account_age = author.created_at + self.config.remove("account_age")

        if min_account_age > now:
            # User account has not reached the required time
            delta = human_timedelta(min_account_age)
            logger.debug("Blocked due to account age, user %s.", author.name)

            if str(author.id) not in self.blocked_users:
                new_reason = f"System Message: New Account. Required to wait for {delta}."
                self.blocked_users[str(author.id)] = new_reason

            return False
        return True 
Example #12
Source File: modmail.py    From modmail with GNU Affero General Public License v3.0 6 votes vote down vote up
def freply(self, ctx, *, msg: str = ""):
        """
        Reply to a Modmail thread with variables.

        Works just like `{prefix}reply`, however with the addition of three variables:
          - `{{channel}}` - the `discord.TextChannel` object
          - `{{recipient}}` - the `discord.User` object of the recipient
          - `{{author}}` - the `discord.User` object of the author

        Supports attachments and images as well as
        automatically embedding image URLs.
        """
        msg = self.bot.formatter.format(
            msg, channel=ctx.channel, recipient=ctx.thread.recipient, author=ctx.message.author
        )
        ctx.message.content = msg
        async with ctx.typing():
            await ctx.thread.reply(ctx.message) 
Example #13
Source File: reminders.py    From bot with MIT License 6 votes vote down vote up
def ensure_valid_reminder(
        self,
        reminder: dict,
        cancel_task: bool = True
    ) -> t.Tuple[bool, discord.User, discord.TextChannel]:
        """Ensure reminder author and channel can be fetched otherwise delete the reminder."""
        user = self.bot.get_user(reminder['author'])
        channel = self.bot.get_channel(reminder['channel_id'])
        is_valid = True
        if not user or not channel:
            is_valid = False
            log.info(
                f"Reminder {reminder['id']} invalid: "
                f"User {reminder['author']}={user}, Channel {reminder['channel_id']}={channel}."
            )
            asyncio.create_task(self._delete_reminder(reminder['id'], cancel_task))

        return is_valid, user, channel 
Example #14
Source File: help.py    From bot with MIT License 6 votes vote down vote up
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 
Example #15
Source File: modmail.py    From modmail with GNU Affero General Public License v3.0 6 votes vote down vote up
def logs_responded(self, ctx, *, user: User = None):
        """
        Get all logs where the specified user has responded at least once.

        If no `user` is provided, the user will be the person who sent this command.
        `user` may be a user ID, mention, or name.
        """
        user = user if user is not None else ctx.author

        entries = await self.bot.api.get_responded_logs(user.id)

        embeds = self.format_log_embeds(entries, avatar_url=self.bot.guild.icon_url)

        if not embeds:
            embed = discord.Embed(
                color=self.bot.error_color,
                description=f"{getattr(user, 'mention', user.id)} has not responded to any threads.",
            )
            return await ctx.send(embed=embed)

        session = EmbedPaginatorSession(ctx, *embeds)
        await session.run() 
Example #16
Source File: admin.py    From xenon with GNU General Public License v3.0 6 votes vote down vote up
def su(self, ctx, member: discord.User, *, msg):
        """
        Execute a command in place of another user


        __Arguments__

        **member**: The user (must be a member of this guild)
        **msg**: The message, doesn't need to be a command
        """
        if member.id == ctx.bot.owner_id:
            raise cmd.CommandError("How about ... **no**?")

        webhook = await ctx.channel.create_webhook(name="sudo")
        await webhook.send(content=msg, username=member.name, avatar_url=member.avatar_url)
        await webhook.delete()

        await asyncio.sleep(1)  # Webhooks are slow

        message = ctx.message
        message.author = member
        message.content = msg
        await self.bot.process_commands(message) 
Example #17
Source File: permissions.py    From BashBot with MIT License 5 votes vote down vote up
def set_permission(permission_name, new_value, user):
    if isinstance(user, User):
        user = user.id

    if isinstance(user, str) and user.startswith("<@"):
        user = user[2:-1]

    permissions = bot.permissions.get(user)

    if not permissions:
        bot.permissions.set(user, {})
        permissions = bot.permissions.get(user)

    parts = permission_name.split(".")

    if parts[0] in ["channels", "servers", "global"]:
        if parts[0] in permissions:
            permissions = permissions[parts[0]]
        else:
            permissions[parts[0]] = {}
            permissions = permissions[parts[0]]

        if parts[0] in ["channels", "servers"]:
            if parts[1].startswith("<#"):
                parts[1] = parts[1][2:-1]

            if parts[1] in permissions:
                permissions = permissions[parts[1]]
            else:
                permissions[parts[1]] = {}
                permissions = permissions[parts[1]]
            permission_name = ".".join(parts[2:])
        else:
            permission_name = ".".join(parts[1:])

    permissions[permission_name] = new_value.lower() == "true"
    bot.permissions.save() 
Example #18
Source File: players.py    From DueUtil with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        if len(args) > 0 and isinstance(args[0], discord.User):
            super().__init__(args[0].id, args[0].name, **kwargs)
            players[self.id] = self
        else:
            super().__init__("NO_ID", "DueUtil Player", **kwargs)
        self.reset()
        self.money = 100 
Example #19
Source File: logging.py    From EmoteCollector with GNU Affero General Public License v3.0 5 votes vote down vote up
def log_emote_action(self, *, event, emote, title=None, by: discord.User = None):
		e = discord.Embed()
		e.title = title or event.title()
		e.colour = getattr(LogColor, event)
		e.description = f'[{emote.name}]({emote.url})'
		e.timestamp = emote.created
		e.set_thumbnail(url=emote.url)
		e.set_footer(text='Originally created')
		e.add_field(name='Owner', value=utils.format_user(self.bot,
			emote.author, mention=True))
		if by:
			e.add_field(name='Action taken by', value=by.mention, inline=False)

		return await self._log(event=event, nsfw=emote.is_nsfw, embed=e) 
Example #20
Source File: fetch.py    From apex-sigma-core with GNU General Public License v3.0 5 votes vote down vote up
def make_user_data(usr):
        """
        Makes a data dict for storage for a user.
        :param usr: The user to store.
        :type usr: discord.Member or discord.User
        :rtype: dict
        """
        data = {
            "username": usr.name,
            "discriminator": usr.discriminator,
            "id": str(usr.id),
            "avatar": usr.avatar,
            "bot": usr.bot
        }
        return data 
Example #21
Source File: command.py    From apex-sigma-core with GNU General Public License v3.0 5 votes vote down vote up
def update_cooldown(self, author):
        """
        Updates the cooldown timer of the command usage.
        :type author: discord.User
        :param author: The author of the command.
        :return:
        """
        cdfile = await self.db[self.db.db_nam].CommandCooldowns.find_one({'command': self.name}) or {}
        cooldown = cdfile.get('cooldown')
        if cooldown:
            await self.bot.cool_down.set_cooldown(f'{self.name}_core', author, cooldown) 
Example #22
Source File: fetch.py    From apex-sigma-core with GNU General Public License v3.0 5 votes vote down vote up
def fetch_user(self, uid):
        """
        Fetches and caches a user.
        :param uid: The user ID.
        :type uid: int
        :return:
        :rtype: None or discord.User
        """
        result = None
        data = await self.get_object_doc('user', uid)
        if data:
            result = discord.User(state=self.state, data=data)
        return result 
Example #23
Source File: sigma.py    From apex-sigma-core with GNU General Public License v3.0 5 votes vote down vote up
def on_member_unban(self, guild, user):
        """
        Starts events when a user is removed from a guild's ban list.
        :type guild: discord.Guild
        :type user: discord.User
        :param guild: The guild from which the user was unbanned.
        :param user: The user that was unbanned.
        :return:
        """
        if not user.bot:
            self.loop.create_task(self.queue.event_runner('member_unban', UnbanPayload(self, guild, user))) 
Example #24
Source File: thread.py    From modmail with GNU Affero General Public License v3.0 5 votes vote down vote up
def create(
        self,
        recipient: typing.Union[discord.Member, discord.User],
        *,
        creator: typing.Union[discord.Member, discord.User] = None,
        category: discord.CategoryChannel = None,
    ) -> Thread:
        """Creates a Modmail thread"""

        # checks for existing thread in cache
        thread = self.cache.get(recipient.id)
        if thread:
            await thread.wait_until_ready()
            if thread.channel and self.bot.get_channel(thread.channel.id):
                logger.warning("Found an existing thread for %s, abort creating.", recipient)
                return thread
            logger.warning("Found an existing thread for %s, closing previous thread.", recipient)
            self.bot.loop.create_task(
                thread.close(closer=self.bot.user, silent=True, delete_channel=False)
            )

        thread = Thread(self, recipient)

        self.cache[recipient.id] = thread

        # Schedule thread setup for later
        cat = self.bot.main_category
        if category is None and len(cat.channels) == 50:
            fallback_id = self.bot.config["fallback_category_id"]
            if fallback_id:
                fallback = discord.utils.get(cat.guild.categories, id=int(fallback_id))
                if fallback and len(fallback.channels) != 50:
                    category = fallback

            if not category:
                category = await cat.clone(name="Fallback Modmail")
                self.bot.config.set("fallback_category_id", category.id)
                await self.bot.config.update()

        self.bot.loop.create_task(thread.setup(creator=creator, category=category))
        return thread 
Example #25
Source File: thread.py    From modmail with GNU Affero General Public License v3.0 5 votes vote down vote up
def close(
        self,
        *,
        closer: typing.Union[discord.Member, discord.User],
        after: int = 0,
        silent: bool = False,
        delete_channel: bool = True,
        message: str = None,
        auto_close: bool = False,
    ) -> None:
        """Close a thread now or after a set time in seconds"""

        # restarts the after timer
        await self.cancel_closure(auto_close)

        if after > 0:
            # TODO: Add somewhere to clean up broken closures
            #  (when channel is already deleted)
            now = datetime.utcnow()
            items = {
                # 'initiation_time': now.isoformat(),
                "time": (now + timedelta(seconds=after)).isoformat(),
                "closer_id": closer.id,
                "silent": silent,
                "delete_channel": delete_channel,
                "message": message,
                "auto_close": auto_close,
            }
            self.bot.config["closures"][str(self.id)] = items
            await self.bot.config.update()

            task = self.bot.loop.call_later(
                after, self._close_after, closer, silent, delete_channel, message
            )

            if auto_close:
                self.auto_close_task = task
            else:
                self.close_task = task
        else:
            await self._close(closer, silent, delete_channel, message) 
Example #26
Source File: thread.py    From modmail with GNU Affero General Public License v3.0 5 votes vote down vote up
def recipient(self) -> typing.Optional[typing.Union[discord.User, discord.Member]]:
        return self._recipient 
Example #27
Source File: bot.py    From modmail with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_thread_cooldown(self, author: discord.Member):
        thread_cooldown = self.config.get("thread_cooldown")
        now = datetime.utcnow()

        if thread_cooldown == isodate.Duration():
            return

        last_log = await self.api.get_latest_user_logs(author.id)

        if last_log is None:
            logger.debug("Last thread wasn't found, %s.", author.name)
            return

        last_log_closed_at = last_log.get("closed_at")

        if not last_log_closed_at:
            logger.debug("Last thread was not closed, %s.", author.name)
            return

        try:
            cooldown = datetime.fromisoformat(last_log_closed_at) + thread_cooldown
        except ValueError:
            logger.warning("Error with 'thread_cooldown'.", exc_info=True)
            cooldown = datetime.fromisoformat(last_log_closed_at) + self.config.remove(
                "thread_cooldown"
            )

        if cooldown > now:
            # User messaged before thread cooldown ended
            delta = human_timedelta(cooldown)
            logger.debug("Blocked due to thread cooldown, user %s.", author.name)
            return delta
        return 
Example #28
Source File: bot.py    From modmail with GNU Affero General Public License v3.0 5 votes vote down vote up
def is_blocked(
        self,
        author: discord.User,
        *,
        channel: discord.TextChannel = None,
        send_message: bool = False,
    ) -> typing.Tuple[bool, str]:

        member = self.guild.get_member(author.id)
        if member is None:
            logger.debug("User not in guild, %s.", author.id)
        else:
            author = member

        if str(author.id) in self.blocked_whitelisted_users:
            if str(author.id) in self.blocked_users:
                self.blocked_users.pop(str(author.id))
                await self.config.update()
            return False

        blocked_reason = self.blocked_users.get(str(author.id)) or ""

        if not self.check_account_age(author) or not self.check_guild_age(author):
            new_reason = self.blocked_users.get(str(author.id))
            if new_reason != blocked_reason:
                if send_message:
                    await channel.send(
                        embed=discord.Embed(
                            title="Message not sent!",
                            description=new_reason,
                            color=self.error_color,
                        )
                    )
            return True

        if not self.check_manual_blocked(author):
            return True

        await self.config.update()
        return False 
Example #29
Source File: bot.py    From modmail with GNU Affero General Public License v3.0 5 votes vote down vote up
def check_manual_blocked(self, author: discord.Member) -> bool:
        if str(author.id) not in self.blocked_users:
            return True

        blocked_reason = self.blocked_users.get(str(author.id)) or ""
        now = datetime.utcnow()

        if blocked_reason.startswith("System Message:"):
            # Met the limits already, otherwise it would've been caught by the previous checks
            logger.debug("No longer internally blocked, user %s.", author.name)
            self.blocked_users.pop(str(author.id))
            return True
        # etc "blah blah blah... until 2019-10-14T21:12:45.559948."
        end_time = re.search(r"until ([^`]+?)\.$", blocked_reason)
        if end_time is None:
            # backwards compat
            end_time = re.search(r"%([^%]+?)%", blocked_reason)
            if end_time is not None:
                logger.warning(
                    r"Deprecated time message for user %s, block and unblock again to update.",
                    author.name,
                )

        if end_time is not None:
            after = (datetime.fromisoformat(end_time.group(1)) - now).total_seconds()
            if after <= 0:
                # No longer blocked
                self.blocked_users.pop(str(author.id))
                logger.debug("No longer blocked, user %s.", author.name)
                return True
        logger.debug("User blocked, user %s.", author.name)
        return False 
Example #30
Source File: modmail.py    From modmail with GNU Affero General Public License v3.0 5 votes vote down vote up
def logs(self, ctx, *, user: User = None):
        """
        Get previous Modmail thread logs of a member.

        Leave `user` blank when this command is used within a
        thread channel to show logs for the current recipient.
        `user` may be a user ID, mention, or name.
        """

        await ctx.trigger_typing()

        if not user:
            thread = ctx.thread
            if not thread:
                raise commands.MissingRequiredArgument(SimpleNamespace(name="member"))
            user = thread.recipient

        default_avatar = "https://cdn.discordapp.com/embed/avatars/0.png"
        icon_url = getattr(user, "avatar_url", default_avatar)

        logs = await self.bot.api.get_user_logs(user.id)

        if not any(not log["open"] for log in logs):
            embed = discord.Embed(
                color=self.bot.error_color,
                description="This user does not have any previous logs.",
            )
            return await ctx.send(embed=embed)

        logs = reversed([log for log in logs if not log["open"]])

        embeds = self.format_log_embeds(logs, avatar_url=icon_url)

        session = EmbedPaginatorSession(ctx, *embeds)
        await session.run()