本文整理汇总了Python中discord.utils方法的典型用法代码示例。如果您正苦于以下问题:Python discord.utils方法的具体用法?Python discord.utils怎么用?Python discord.utils使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类discord
的用法示例。
在下文中一共展示了discord.utils方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_user_premium
# 需要导入模块: import discord [as 别名]
# 或者: from discord import utils [as 别名]
def get_user_premium(self, user_id, command_id):
guild = self.bot.get_guild(self.bot.config.main_server)
if not guild:
return
member = guild.get_member(user_id)
if not member:
return
if user_id in self.bot.config.admins or user_id in self.bot.config.owners:
amount = 1000
elif utils.get(member.roles, id=self.bot.config.premium5):
amount = 5
elif utils.get(member.roles, id=self.bot.config.premium3):
amount = 3
elif utils.get(member.roles, id=self.bot.config.premium1):
amount = 1
else:
amount = 0
payload = {"output": amount, "command_id": command_id}
await self.bot.redis.execute("PUBLISH", self.ipc_channel, json.dumps(payload))
示例2: add_safe
# 需要导入模块: import discord [as 别名]
# 或者: from discord import utils [as 别名]
def add_safe(self, name, url, author_id):
"""Try to add an emote. Returns a string that should be sent to the user."""
if not re.fullmatch(r'\w{2,32}', name, re.ASCII):
return _(
'{name} is not a valid emote name; use 2–32 English letters, numbers and underscores.'
).format(name=discord.utils.escape_mentions(name))
try:
emote = await self.add_from_url(name, url, author_id)
except discord.HTTPException as ex:
return (
_('An error occurred while creating the emote:\n')
+ utils.format_http_exception(ex))
except ValueError:
return _('Error: Invalid URL.')
except aiohttp.ServerDisconnectedError:
return _('Error: The connection was closed early by the remote host.')
except aiohttp.ClientResponseError as exc:
raise errors.HTTPException(exc.status)
else:
return _('Emote {emote} successfully created.').format(emote=emote)
示例3: fetch_emote
# 需要导入模块: import discord [as 别名]
# 或者: from discord import utils [as 别名]
def fetch_emote(self, url):
# credits to @Liara#0001 (ID 136900814408122368) for most of this part
# https://gitlab.com/Pandentia/element-zero/blob/47bc8eeeecc7d353ec66e1ef5235adab98ca9635/element_zero/cogs/emoji.py#L217-228
def validate_headers(response):
response.raise_for_status()
# some dumb servers also send '; charset=UTF-8' which we should ignore
mimetype, options = utils.parse_header(response.headers.get('Content-Type', ''))
if mimetype not in {'image/png', 'image/jpeg', 'image/gif', 'image/webp'}:
raise errors.InvalidImageError
range_header = f'bytes=0-{image_utils.MINIMUM_BYTES_NEEDED}'
async with self.http.get(url, headers={'Range': range_header}, timeout=5) as response:
validate_headers(response)
# ensure it has a valid image header
image_utils.mime_type_for_image(await response.read())
async with self.http.get(url) as response:
validate_headers(response)
return await response.read()
示例4: search
# 需要导入模块: import discord [as 别名]
# 或者: from discord import utils [as 别名]
def search(self, context, query):
"""Search for emotes whose name contains "query"."""
processed = [
emote.with_status(linked=True)
async for emote in self.db.search(query, allow_nsfw=context.channel)]
if not processed:
if utils.channel_is_nsfw(context.channel):
return await context.send(_('No results matched your query.'))
return await context.send(_('No results matched your query, or your query only found NSFW emotes.'))
paginator = Pages(context, entries=processed)
self.paginators.add(paginator)
await self.warn_if_no_external_emojis_permission(context)
await paginator.begin()
示例5: cache_search
# 需要导入模块: import discord [as 别名]
# 或者: from discord import utils [as 别名]
def cache_search(self, context, query: (lambda arg: re.compile(codeblock_converter(arg).content))):
"""Search all emotes that the bot can see using a regular expression.
This is useful for gauging the nsfw threshold for a certain kind of emote or seeing if an emote should be
preserved based on its name.
"""
await self.warn_if_no_external_emojis_permission(context)
emotes = []
for e in sorted(
(e for e in self.bot.emojis if e.is_usable() and query.search(e.name)),
key=lambda e: (e.name.lower(), e.name, 0 if e.animated else 1),
):
emotes.append(e)
if len(emotes) == 10:
await context.send(''.join(map(str, emotes)))
emotes.clear()
if emotes:
await context.send(''.join(map(str, emotes)))
await context.try_add_reaction(utils.SUCCESS_EMOJIS[True])
示例6: blacklist_server
# 需要导入模块: import discord [as 别名]
# 或者: from discord import utils [as 别名]
def blacklist_server(self, context, guild: Guild, *, reason):
"""Prevent a server from using the bot. This is a last ditch effort. Only use it if you really must.
If you don't provide a reason, the server will be un-blacklisted.
"""
await self.db.set_guild_blacklist(guild.id, reason)
target = guild.system_channel if guild.system_channel.permissions_for(guild.me).send_messages else None
if target is None:
target = discord.utils.find(lambda c: c.permissions_for(guild.me).send_messages, guild.text_channels)
if target is None:
await context.send(_('Warning: no suitable channel found to notify the member of that server.'))
else:
current_locale.set(await self.bot.cogs['Locales'].guild_locale(guild.id) or i18n.default_locale)
await target.send(_(
'This server has been blacklisted for “{reason}”. '
'Server admins, use the {context.prefix}support command in DMs to appeal. '
'Now leaving…').format(**locals()))
await guild.leave()
await context.try_add_reaction(utils.SUCCESS_EMOJIS[True])
示例7: linkrole
# 需要导入模块: import discord [as 别名]
# 或者: from discord import utils [as 别名]
def linkrole(self, ctx, role_name:str, level:int, remove_role = None):
"""Associate a role with a level. Removes previous role if given."""
server = ctx.message.server
role_obj = discord.utils.find(lambda r: r.name == role_name, server.roles)
remove_role_obj = discord.utils.find(lambda r: r.name == remove_role, server.roles)
if role_obj == None or (remove_role != None and remove_role_obj == None):
if remove_role == None:
await self.bot.say("**Please make sure the `{}` role exists!**".format(role_name))
else:
await self.bot.say("**Please make sure the `{}` and/or `{}` roles exist!**".format(role_name, remove_role))
else:
server_roles = db.roles.find_one({'server_id':server.id})
if not server_roles:
new_server = {
'server_id': server.id,
'roles': {
role_name: {
'level':str(level),
'remove_role': remove_role
}
}
}
db.roles.insert_one(new_server)
else:
if role_name not in server_roles['roles']:
server_roles['roles'][role_name] = {}
server_roles['roles'][role_name]['level'] = str(level)
server_roles['roles'][role_name]['remove_role'] = remove_role
db.roles.update_one({'server_id':server.id}, {'$set':{'roles':server_roles['roles']}})
if remove_role == None:
await self.bot.say("**The `{}` role has been linked to level `{}`**".format(role_name, level))
else:
await self.bot.say("**The `{}` role has been linked to level `{}`. Will also remove `{}` role.**".format(
role_name, level, remove_role))
示例8: info
# 需要导入模块: import discord [as 别名]
# 或者: from discord import utils [as 别名]
def info(self, context, emote: DatabaseEmoteConverter()):
"""Gives info on an emote.
The emote must be in the database.
"""
embed = discord.Embed()
embed.url = emote.url
embed.set_thumbnail(url=emote.url)
embed.title = f'{emote.name} {emote.status()}'
if emote.description is not None:
embed.description = emote.description
if emote.created is not None:
embed.timestamp = emote.created
embed.set_footer(text=_('Created'))
avatar = None
with contextlib.suppress(AttributeError):
avatar = self.bot.get_user(emote.author).avatar_url_as(static_format='png', size=32)
name = utils.format_user(self.bot, emote.author, mention=False)
if avatar is None:
embed.set_author(name=name)
else:
embed.set_author(name=name, icon_url=avatar)
if emote.modified is not None:
embed.add_field(
name=_('Last modified'),
# hangul filler prevents the embed fields from jamming next to each other
value=utils.format_time(emote.modified) + '\N{hangul filler}')
embed.add_field(name=_('Usage count'), value=await self.db.get_emote_usage(emote))
await self.warn_if_no_external_emojis_permission(context)
await context.send(embed=embed)
示例9: add_from_e0
# 需要导入模块: import discord [as 别名]
# 或者: from discord import utils [as 别名]
def add_from_e0(self, context, name):
"""Copy an emote from an archive of Element Zero's emote database.
You can find a full list of them at https://emote-collector.python-for.life/e0-list.
"""
name = name.strip(':;')
try:
id, animated = self.e0_emojis[name.lower()]
except KeyError:
await context.send(_("Emote not found in Element Zero's database."))
return
await context.invoke(self.add, name, utils.emote.url(id, animated=animated))
示例10: parse_add_command_args
# 需要导入模块: import discord [as 别名]
# 或者: from discord import utils [as 别名]
def parse_add_command_args(self, context, args):
if context.message.attachments:
return self.parse_add_command_attachment(context, args)
elif len(args) == 1:
match = re.match(utils.lexer.t_CUSTOM_EMOTE, args[0])
if match is None:
# translator's note: please also translate NAME_HERE and URL_HERE
raise commands.BadArgument(_(
'Error: I expected a custom emote as the first argument, '
'but I got something else. '
"If you're trying to add an emote using an image URL, "
'you need to provide a name as the first argument, like this:\n'
'`{}add NAME_HERE URL_HERE`').format(context.prefix))
else:
url = utils.emote.url(match['id'], animated=match['animated'])
return match['name'], url
elif len(args) >= 2:
name = args[0]
match = re.match(utils.lexer.t_CUSTOM_EMOTE, args[1])
if match is None:
url = utils.strip_angle_brackets(args[1])
else:
url = utils.emote.url(match['id'], animated=match['animated'])
return name, url
elif not args:
raise commands.BadArgument(_('Your message had no emotes and no name!'))
示例11: rename
# 需要导入模块: import discord [as 别名]
# 或者: from discord import utils [as 别名]
def rename(self, context, *args):
r"""Renames an emote. You must own it.
Example:
ec/rename a b
Renames \:a: to \:b:
"""
if not args:
return await context.send(_('You must specify an old name and a new name.'))
# allow e.g. foo{bar,baz} -> rename foobar to foobaz
if len(args) == 1:
old_name, new_name = utils.expand_cartesian_product(args[0])
if not new_name:
return await context.send(_('Error: you must provide a new name for the emote.'))
else:
old_name, new_name, *rest = args
old_name, new_name = map(lambda c: c.strip(':;'), (old_name, new_name))
try:
await self.db.rename_emote(old_name, new_name, context.author.id)
except discord.HTTPException as ex:
await context.send(utils.format_http_exception(ex))
else:
await context.send(_('Emote successfully renamed.'))
示例12: describe
# 需要导入模块: import discord [as 别名]
# 或者: from discord import utils [as 别名]
def describe(self, context, name, *, description=None):
"""Set an emote's description. It will be displayed in ec/info.
If you leave out the description, it will be removed.
You could use this to:
- Detail where you got the image
- Credit another author
- Write about why you like the emote
- Describe how it's used
Currently, there's a limit of 500 characters.
"""
await self.db.set_emote_description(name, description, context.author.id)
await context.try_add_reaction(utils.SUCCESS_EMOJIS[True])
示例13: popular
# 需要导入模块: import discord [as 别名]
# 或者: from discord import utils [as 别名]
def popular(self, context, user: UserOrMember = None):
"""Lists popular emojis.
If a user is provided, the list will only contain popular emotes created by that user.
"""
# code generously provided by @Liara#0001 under the MIT License:
# https://gitlab.com/Pandentia/element-zero/blob/ca7d7f97e068e89334e66692922d9a8744e3e9be/element_zero/cogs/emoji.py#L364-399
processed = []
async for i, emote in utils.async_enumerate(
self.db.popular_emotes(user.id if user else None, limit=200, allow_nsfw=context.channel)
):
c = emote.usage
multiple = '' if c == 1 else 's'
# TODO internationalize this (needs plural support)
processed.append(
f'{emote.with_linked_name()} '
f'— used {c} time{multiple}')
if not processed:
return await context.send(self.no_emotes_found_error(context, user))
paginator = Pages(context, entries=processed)
self.paginators.add(paginator)
await self.warn_if_no_external_emojis_permission(context)
await paginator.begin()
示例14: _extract_emotes
# 需要导入模块: import discord [as 别名]
# 或者: from discord import utils [as 别名]
def _extract_emotes(self,
message: discord.Message,
content: str = None,
*,
callback,
log_usage=False,
):
"""Extract emotes according to predicate.
Callback is a coroutine function taking three arguments: token, out: StringIO, and emotes_used: set
For each token, callback will be called with these arguments.
out is the StringIO that holds the extracted string to return, and emotes_used is a set
containing the IDs of all emotes that were used, for logging purposes.
Returns extracted_message: str, has_emotes: bool.
"""
out = io.StringIO()
emotes_used = set()
if content is None:
content = message.content
# we make a new one each time otherwise two tasks might use the same lexer at the same time
lexer = utils.lexer.new()
lexer.input(content)
for toke1 in iter(lexer.token, None):
await callback(toke1, out, emotes_used)
result = out.getvalue() if emotes_used else content
if log_usage:
for emote in emotes_used:
await self.db.log_emote_use(emote)
return utils.clean_content(self.bot, message, result), bool(emotes_used)
示例15: _is_emote
# 需要导入模块: import discord [as 别名]
# 或者: from discord import utils [as 别名]
def _is_emote(toke1):
return toke1.type == 'EMOTE' and toke1.value.strip(':') not in utils.emote.emoji_shortcodes