本文整理汇总了Python中discord.User方法的典型用法代码示例。如果您正苦于以下问题:Python discord.User方法的具体用法?Python discord.User怎么用?Python discord.User使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类discord
的用法示例。
在下文中一共展示了discord.User方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: help_cleanup
# 需要导入模块: import discord [as 别名]
# 或者: from discord import User [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
示例2: ensure_valid_reminder
# 需要导入模块: import discord [as 别名]
# 或者: from discord import User [as 别名]
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
示例3: on_member_join
# 需要导入模块: import discord [as 别名]
# 或者: from discord import User [as 别名]
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
)
示例4: on_member_remove
# 需要导入模块: import discord [as 别名]
# 或者: from discord import User [as 别名]
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
)
示例5: pardon_mute
# 需要导入模块: import discord [as 别名]
# 或者: from discord import User [as 别名]
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
示例6: proxy_user
# 需要导入模块: import discord [as 别名]
# 或者: from discord import User [as 别名]
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
示例7: convert
# 需要导入模块: import discord [as 别名]
# 或者: from discord import User [as 别名]
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")
示例8: su
# 需要导入模块: import discord [as 别名]
# 或者: from discord import User [as 别名]
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)
示例9: _approve
# 需要导入模块: import discord [as 别名]
# 或者: from discord import User [as 别名]
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)
示例10: check_reminders
# 需要导入模块: import discord [as 别名]
# 或者: from discord import User [as 别名]
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)
示例11: logs_responded
# 需要导入模块: import discord [as 别名]
# 或者: from discord import User [as 别名]
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()
示例12: freply
# 需要导入模块: import discord [as 别名]
# 或者: from discord import User [as 别名]
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)
示例13: check_account_age
# 需要导入模块: import discord [as 别名]
# 或者: from discord import User [as 别名]
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
示例14: check_guild_age
# 需要导入模块: import discord [as 别名]
# 或者: from discord import User [as 别名]
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
示例15: __init__
# 需要导入模块: import discord [as 别名]
# 或者: from discord import User [as 别名]
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