Python discord 模块,utils() 实例源码

我们从Python开源项目中,提取了以下9个代码示例,用于说明如何使用discord.utils()

项目:dango.py    作者:khazhyk    | 项目源码 | 文件源码
def remove_cog(self, name, remove=True):
        """Unloads a cog.

        Name of a cog must be it's class name.
        If another cog depends on this one, unload but do not remove it.
        """
        cog = self.cogs.get(name, None)

        if remove:
            if name in self._dango_unloaded_cogs:
                del self._dango_unloaded_cogs[name]
        elif cog:
            self._dango_unloaded_cogs[name] = type(cog)

        if not cog:
            return

        if hasattr(cog, PLUGIN_DESC):
            self.unload_cog_deps(cog)

        self._config.root.remove_group(utils.snakify(name))
        super().remove_cog(name)
        log.debug("Unloaded dcog %s", name)
项目:goldmine    作者:Armored-Dragon    | 项目源码 | 文件源码
def role_or_permissions(ctx, check, **perms):
    if check_permissions(ctx, perms):
        return True

    ch = ctx.channel
    author = ctx.author
    if isinstance(msg.channel, discord.abc.PrivateChannel):
        return False # can't have roles in PMs

    role = discord.utils.find(check, author.roles)
    return role is not None
项目:Neppy    作者:VorgunTheBeta    | 项目源码 | 文件源码
def hug(ctx, name: str):
    hugee = name
    user = utils.find(lambda m: hugee.lower() in m.display_name.lower(), ctx.message.server.members)
    msg = "*hugs {0.mention}*"
    await bot.type()
    await asyncio.sleep(2)
    await bot.say( msg.format(user))
项目:Maybe-Useful-Cogs    作者:AznStevy    | 项目源码 | 文件源码
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))
项目:dango.py    作者:khazhyk    | 项目源码 | 文件源码
def add_cog(self, cls):
        """Tries to load a cog.

        If not all dependencies are loaded, will defer until they are.
        """
        desc = getattr(cls, PLUGIN_DESC, None)
        if not desc:
            log.debug("Loading cog %s", cls)
            return super().add_cog(cls)

        depends = [self.get_cog(name) for name in desc.depends]
        if not all(depends):
            self._dango_unloaded_cogs[cls.__name__] = cls
            return

        self._config.load()
        cgroup = self._config.root.add_group(utils.snakify(cls.__name__))

        depends.insert(0, cgroup)
        if desc.pass_bot:
            depends.insert(0, self)

        try:
            cog = cls(*depends)
        except config.InvalidConfig:
            raise
        finally:
            self._config.save()
        super().add_cog(cog)
        setattr(cog, COG_DESC, CogDesc(datetime.datetime.utcnow()))
        log.debug("Loaded dcog %s.%s", cls.__module__, cls.__name__)

        # Try loading previously unloaded plugins.
        unloaded_plugins = self._dango_unloaded_cogs
        self._dango_unloaded_cogs = {}
        for plugin in unloaded_plugins.values():
            self.add_cog(plugin)
项目:Cassandra    作者:Avinch    | 项目源码 | 文件源码
def role_or_permissions(ctx, check, **perms):
    if not isinstance(ctx.channel, discord.abc.GuildChannel):
        raise commands.NoPrivateMessage

    role = discord.utils.find(check, ctx.author.roles)
    if role:
        return True

    if await check_permissions(ctx, perms):
        return True

    return False
项目:Cassandra    作者:Avinch    | 项目源码 | 文件源码
def is_mod(guild: discord.Guild, member: discord.Member):
    return discord.utils.get(guild.roles, name="Mods") in member.roles
项目:dogbot    作者:slice    | 项目源码 | 文件源码
def on_member_ban(self, guild: Guild, user):
        if not await self.bot.config_is_set(guild, 'pollr_mod_log'):
            # not configured to announce bans here
            return

        logger.debug('pollr ban process: %d', user.id)

        # grab bans channel
        bans = discord.utils.get(guild.text_channels, name='bans')

        if not bans:
            logger.debug('not announcing ban, couldn\'t find channel. gid=%d', guild.id)
            return

        ban = f'**Ban:** {describe(user)}'

        # get my permissions
        perms = guild.me.guild_permissions

        # check to see if they were banned via dogbot's ban command, and provide cleaner insight
        information = await self.ban_debounce.check(
            member_id=user.id,
            return_information=True,
            partial=True,
            wait_period=2.0
        )

        if information:
            reason = information['reason']
            responsible = information['moderator']
            ban += f'\n**Responsible:** {describe(responsible)}\n**Reason:** {reason}'

        if not information and perms.view_audit_log:
            # fall back to audit log

            await asyncio.sleep(1)  # wait a bit, because audit logs can be slow

            logs = await guild.audit_logs(action=AuditLogAction.ban, limit=5).flatten()

            # grab the entry that targeted our banned user
            entry = get(logs, target=user)

            if entry:
                ban += f'\n**Responsible:** {describe(entry.user)}'
                if entry.reason:
                    ban += f'\n**Reason:** {entry.reason}'

        try:
            # send the ban message
            await bans.send(ban)
        except discord.HTTPException as exc:
            logger.warning('Cannot announce ban, error! gid=%d %s', guild.id, exc)
项目:Maybe-Useful-Cogs    作者:AznStevy    | 项目源码 | 文件源码
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))