Python discord.utils() Examples

The following are 16 code examples of discord.utils(). 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: emote.py    From EmoteCollector with GNU Affero General Public License v3.0 7 votes vote down vote up
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) 
Example #2
Source File: communication.py    From modmail with GNU Affero General Public License v3.0 6 votes vote down vote up
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)) 
Example #3
Source File: emote.py    From EmoteCollector with GNU Affero General Public License v3.0 6 votes vote down vote up
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() 
Example #4
Source File: emote.py    From EmoteCollector with GNU Affero General Public License v3.0 6 votes vote down vote up
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() 
Example #5
Source File: emote.py    From EmoteCollector with GNU Affero General Public License v3.0 6 votes vote down vote up
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]) 
Example #6
Source File: emote.py    From EmoteCollector with GNU Affero General Public License v3.0 6 votes vote down vote up
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]) 
Example #7
Source File: leveler.py    From Maybe-Useful-Cogs with MIT License 5 votes vote down vote up
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)) 
Example #8
Source File: emote.py    From EmoteCollector with GNU Affero General Public License v3.0 5 votes vote down vote up
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.')) 
Example #9
Source File: emote.py    From EmoteCollector with GNU Affero General Public License v3.0 5 votes vote down vote up
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]) 
Example #10
Source File: emote.py    From EmoteCollector with GNU Affero General Public License v3.0 5 votes vote down vote up
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() 
Example #11
Source File: emote.py    From EmoteCollector with GNU Affero General Public License v3.0 5 votes vote down vote up
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) 
Example #12
Source File: emote.py    From EmoteCollector with GNU Affero General Public License v3.0 5 votes vote down vote up
def _is_emote(toke1):
		return toke1.type == 'EMOTE' and toke1.value.strip(':') not in utils.emote.emoji_shortcodes 
Example #13
Source File: leveler.py    From Maybe-Useful-Cogs with MIT License 4 votes vote down vote up
def _handle_levelup(self, user, userinfo, server, channel):
        if not isinstance(self.settings["lvl_msg"], list):
            self.settings["lvl_msg"] = []
            fileIO("data/leveler/settings.json", "save", self.settings)

        if server.id in self.settings["lvl_msg"]: # if lvl msg is enabled
            # channel lock implementation
            if "lvl_msg_lock" in self.settings.keys() and server.id in self.settings["lvl_msg_lock"].keys():
                channel_id = self.settings["lvl_msg_lock"][server.id]
                channel = find(lambda m: m.id == channel_id, server.channels)

            server_identifier = "" # super hacky
            name = self._is_mention(user) # also super hacky
            # private message takes precedent, of course
            if "private_lvl_msg" in self.settings and server.id in self.settings["private_lvl_msg"]:
                server_identifier = " on {}".format(server.name)
                channel = user
                name = "You"

            new_level = str(userinfo["servers"][server.id]["level"])
            # add to appropriate role if necessary
            try:
                server_roles = db.roles.find_one({'server_id':server.id})
                if server_roles != None:
                    for role in server_roles['roles'].keys():
                        if int(server_roles['roles'][role]['level']) == int(new_level):
                            role_obj = discord.utils.find(lambda r: r.name == role, server.roles)
                            await self.bot.add_roles(user, role_obj)

                            if server_roles['roles'][role]['remove_role'] != None:
                                remove_role_obj = discord.utils.find(
                                    lambda r: r.name == server_roles['roles'][role]['remove_role'], server.roles)
                                if remove_role_obj != None:
                                    await self.bot.remove_roles(user, remove_role_obj)
            except:
                await self.bot.send_message(channel, 'Role was not set. Missing Permissions!')

            # add appropriate badge if necessary
            try:
                server_linked_badges = db.badgelinks.find_one({'server_id':server.id})
                if server_linked_badges != None:
                    for badge_name in server_linked_badges['badges']:
                        if int(server_linked_badges['badges'][badge_name]) == int(new_level):
                            server_badges = db.badges.find_one({'server_id':server.id})
                            if server_badges != None and badge_name in server_badges['badges'].keys():
                                userinfo_db = db.users.find_one({'user_id':user.id})
                                new_badge_name = "{}_{}".format(badge_name, server.id)
                                userinfo_db["badges"][new_badge_name] = server_badges['badges'][badge_name]
                                db.users.update_one({'user_id':user.id}, {'$set':{"badges": userinfo_db["badges"]}})
            except:
                await self.bot.send_message(channel, 'Error. Badge was not given!')

            if "text_only" in self.settings and server.id in self.settings["text_only"]:
                await self.bot.send_typing(channel)
                em = discord.Embed(description='**{} just gained a level{}! (LEVEL {})**'.format(name, server_identifier, new_level), colour=user.colour)
                await self.bot.send_message(channel, '', embed = em)
            else:
                await self.draw_levelup(user, server)
                await self.bot.send_typing(channel)
                await self.bot.send_file(channel, 'data/leveler/temp/{}_level.png'.format(user.id), content='**{} just gained a level{}!**'.format(name, server_identifier)) 
Example #14
Source File: emote.py    From EmoteCollector with GNU Affero General Public License v3.0 4 votes vote down vote up
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) 
Example #15
Source File: emote.py    From EmoteCollector with GNU Affero General Public License v3.0 4 votes vote down vote up
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)) 
Example #16
Source File: emote.py    From EmoteCollector with GNU Affero General Public License v3.0 4 votes vote down vote up
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!'))