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

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

项目:CorpBot.py    作者:corpnewt    | 项目源码 | 文件源码
def name(member : discord.Member):
    # A helper function to return the member's display name
    nick = name = None
    try:
        nick = member.nick
    except AttributeError:
        pass
    try:
        name = member.name
    except AttributeError:
        pass
    if nick:
        return nick
    if name:
        return name
    return None
项目:CorpBot.py    作者:corpnewt    | 项目源码 | 文件源码
def recheckrole(self, ctx, *, user : discord.Member = None):
        """Re-iterate through all members and assign the proper roles based on their xp (admin only)."""

        author  = ctx.message.author
        server  = ctx.message.server
        channel = ctx.message.channel

        isAdmin = author.permissions_in(channel).administrator

        # Only allow admins to change server stats
        if not isAdmin:
            await self.bot.send_message(channel, 'You do not have sufficient privileges to access this command.')
            return

        if not user:
            user = author

        # Now we check for promotions
        if await CheckRoles.checkroles(user, channel, self.settings, self.bot):
            await self.bot.send_message(channel, 'Done checking roles.\n\n*{}* was updated.'.format(DisplayName.name(user)))
        else:
            await self.bot.send_message(channel, 'Done checking roles.\n\n*{}* was not updated.'.format(DisplayName.name(user)))
项目:YeeBot    作者:jaspric    | 项目源码 | 文件源码
def addmeme(ctx, *args, member: discord.Member = None):
    if member is None:
        member = ctx.message.author
    if args:
        if 'youtu' in args[0] or 'gfycat' in args[0] or 'imgur' in args[0] or 'streamable' in args[0] or 'redd' in args[0]:

            cur.execute("SELECT status FROM links WHERE link = ?", (args[0],))
            check = cur.fetchone()
            if check is None:
                cur.execute("INSERT INTO links (link, status, submitter_id, submitter_name) VALUES (?, 'review', ?, ?)", (args[0], member.id, member.name))
                conn.commit()
                cur.execute("SELECT count(*) FROM links WHERE status = 'review'")
                count = cur.fetchone()[0]
                if count == 1:
                    await yeebot.send_message(yeebot.get_channel(review_channel_id), 'There is 1 link awaiting review.'.format(count))
                else:
                    await yeebot.send_message(yeebot.get_channel(review_channel_id), 'There are {} links awaiting review.'.format(count))
                await yeebot.delete_message(ctx.message)
                return await yeebot.say("`{}` has been submitted for review.".format(args[0]))
            else:
                return await yeebot.say("Sorry, that link has already been submitted. It is currently in status: `{}`".format(check[0]))
        else:
            return await yeebot.say("Please only submit links from Youtube, gfycat, streamable, or imgur.")
    else:
        return await yeebot.say("Please use the format: `!addmeme https://link.to.meme/meme`")
项目:YeeBot    作者:jaspric    | 项目源码 | 文件源码
def review(ctx, amount=1, member: discord.Member = None):
    if member is None:
        member = ctx.message.author
    if ctx.message.channel.id == review_channel_id:
        if amount < 1 or amount > 5:
            return await yeebot.say("Please use the format `!review <1-5>`.")
        elif amount > 1 and amount < 6:
            cur.execute("SELECT link, submitter_name FROM links WHERE status = 'review' LIMIT ?", (amount, ))
            links = cur.fetchall()
            if links:
                for row in links:
                    await yeebot.say("Submitted by: {}, `{}`".format(row[1], row[0]))
            else:
                return await yeebot.say("No links to review.")
        else:
            cur.execute("SELECT link, submitter_name FROM links WHERE status = 'review' LIMIT ?", (amount, ))
            links = cur.fetchall()
            if links:
                for row in links:
                    await yeebot.say("Submitted by: {}, {}".format(row[1], row[0]))
            else:
                return await yeebot.say("No links to review.")
    else:
        return await yeebot.say("You do not have permission to execute this command.")
项目:Jumper-Cogs    作者:Redjumpman    | 项目源码 | 文件源码
def give(self, ctx, user: discord.Member, cookies: int):
        """Gives another user your cookies"""
        author = ctx.message.author
        settings = self.check_server_settings(author.server)
        if user.bot:
            return await self.bot.say("Nice try, us bots can't accept cookies from strangers.")
        if author.id == user.id:
            return await self.bot.say("You can't give yourself cookies.")
        self.account_check(settings, author)
        self.account_check(settings, user)
        sender_cookies = settings["Players"][author.id]["Cookies"]
        if 0 < cookies <= sender_cookies:
            settings["Players"][author.id]["Cookies"] -= cookies
            settings["Players"][user.id]["Cookies"] += cookies
            dataIO.save_json(self.file_path, self.system)
            msg = "You gave **{}** cookies to {}".format(cookies, user.name)
        else:
            msg = "You don't have enough cookies in your account"

        await self.bot.say(msg)
项目:Jumper-Cogs    作者:Redjumpman    | 项目源码 | 文件源码
def steal(self, ctx, user: discord.Member=None):
        """Steal cookies from another user. 2h cooldown."""
        author = ctx.message.author
        server = author.server
        action = "Steal CD"
        settings = self.check_server_settings(author.server)
        self.account_check(settings, author)

        if user is None:
            user = self.random_user(settings, author, server)

        if user == "Fail":
            pass
        elif user.bot:
            return await self.bot.say("Stealing failed because the picked target is a bot.\nYou "
                                      "can retry stealing again, your cooldown is not consumed.")

        if await self.check_cooldowns(author.id, action, settings):
            msg = self.steal_logic(settings, user, author)
            await self.bot.say("?(=(|) ? (|)=)? Neko-chan is on the prowl to steal :cookie:")
            await asyncio.sleep(4)
            await self.bot.say(msg)
项目:Jumper-Cogs    作者:Redjumpman    | 项目源码 | 文件源码
def check_server_settings(self, server):
        if server.id not in self.system["Servers"]:
            self.system["Servers"][server.id] = {"Shop List": {},
                                                 "Users": {},
                                                 "Pending": {},
                                                 "Config": {"Shop Name": "Jumpman's",
                                                            "Shop Open": True,
                                                            "Shop Notify": False,
                                                            "Shop Role": None,
                                                            "Trade Cooldown": 30,
                                                            "Store Output Method": "Chat",
                                                            "Inventory Output Method": "Chat",
                                                            "Sort Method": "Alphabet",
                                                            "Member Discount": None,
                                                            "Pending Type": "Manual"}
                                                 }
            dataIO.save_json(self.file_path, self.system)
            print("Creating default Shop settings for Server: {}".format(server.name))
            path = self.system["Servers"][server.id]
            return path
        else:
            path = self.system["Servers"][server.id]
            if "Shop Role" not in path["Config"]:
                path["Config"]["Shop Role"] = None
            return path
项目:Jumper-Cogs    作者:Redjumpman    | 项目源码 | 文件源码
def _removeuser_casino(self, ctx, user: discord.Member):
        """Remove a user from casino"""
        author = ctx.message.author
        super().check_server_settings(author.server)

        if not super().membership_exists(user):
            msg = _("This user is not a member of the casino.")
        else:
            await self.bot.say(_("Are you sure you want to remove player data for {}? Type {} to "
                                 "confirm.").format(user.name, user.name))
            response = await self.bot.wait_for_message(timeout=15, author=author)
            if response is None:
                msg = _("No response. Player removal cancelled.")
            elif response.content.title() == user.name:
                super().remove_membership(user)
                msg = _("{}\'s casino data has been removed by {}.").format(user.name, author.name)
            else:
                msg = _("Incorrect name. Cancelling player removal.")
        await self.bot.say(msg)
项目:Jumper-Cogs    作者:Redjumpman    | 项目源码 | 文件源码
def _balance_setcasino(self, ctx, user: discord.Member, chips: int):
        """Sets a Casino member's chip balance"""
        author = ctx.message.author
        settings = super().check_server_settings(author.server)
        chip_name = settings["System Config"]["Chip Name"]
        casino_name = settings["System Config"]["Casino Name"]
        try:
            super().set_chips(user, chips)
        except NegativeChips:
            return await self.bot.say(_("Chips must be higher than 0."))
        except UserNotRegistered:
            return await self.bot.say(_("You need to register to the {} Casino. To register type "
                                        "`{}casino join`.").format(casino_name, ctx.prefix))
        else:
            logger.info("SETTINGS CHANGED {}({}) set {}({}) chip balance to "
                        "{}".format(author.name, author.id, user.name, user.id, chips))
            await self.bot.say(_("```Python\nSetting the chip balance of {} to "
                                 "{} {} chips.```").format(user.name, chips, chip_name))
项目:PTSCogs    作者:PlanetTeamSpeakk    | 项目源码 | 文件源码
def spam(self, ctx, user : discord.Member, spamtext, number : int=0):
        """Spams x times, default is 4."""
        if user.id == "96987941519237120":
            await self.bot.say("Hell nah, I ain't spamming him.")
            return
        if user.id == settings.owner:
            await self.bot.say("Hell nah, I ain't spamming him. If you want to spam my owner use the `suggest` command!")
            return
        if number >> 8:
            await self.bot.say("Hell nah, not past 8 for fck sakes.")
            return
        if number == 0:
            number = 4
        counter = 0
        while counter < number:
            try:
                await self.bot.send_message(user, "{}, sent by **{}**".format(spamtext, ctx.message.author))
            except discord.Forbidden:
                await self.bot.say("{} blocked me :sob:".format(user.mention))
                return
            counter = counter + 1
            if counter == 1:
                await self.bot.say("Hehe, {} got spammed {} time!".format(user.mention, counter))
            else:
                await self.bot.say("Hehe, {} got spammed {} time!".format(user.mention, counter))
项目:Dwarf    作者:Dwarf-Community    | 项目源码 | 文件源码
def user_is_registered(self, user):
        """Checks whether a ?User? is registered in the database.

        Parameters
        ----------
        user
            Can be a Discord `User` object or `Member` object, or a user ID.
        """

        if isinstance(user, discord.User) or isinstance(user, discord.Member):
            try:
                get_user_model().objects.get(id=user.id)
                return True
            except get_user_model().DoesNotExist:
                return False
        else:
            try:
                get_user_model().objects.get(id=user)
                return True
            except get_user_model().DoesNotExist:
                return False
项目:Dwarf    作者:Dwarf-Community    | 项目源码 | 文件源码
def get_member(self, member=None, user=None, guild=None):
        """Retrieves a Dwarf ?Member? object from the database.
        Either ?member? or both ?user? and ?guild? must be given as arguments.

        Parameters
        ----------
        member : Optional
            Has to be a Discord ?Member? object.
        user : Optional
            Can be a Discord `User` object or a user ID.
        guild : Optional
            Can be a Discord ?Server? object or a guild ID.
        """

        if isinstance(member, discord.Member):
            user_id = member.id
            guild_id = member.server.id
        else:
            if user is None or guild is None:
                raise ValueError("Either a Member object or both user ID "
                                 "and guild ID must be given as argument(s).")
            if isinstance(user, discord.User):
                user_id = user.id
            else:
                user_id = user
            if isinstance(guild, discord.Server):
                guild_id = guild.id
            else:
                guild_id = guild

        return Member.objects.get(user=user_id, guild=guild_id)
项目:lagbot    作者:mikevb1    | 项目源码 | 文件源码
def on_member_join(self, member):
        """Automatically assign roles if guild has a role set through `newrole` command."""
        if not member.guild.me.guild_permissions.manage_roles:
            return
        async with self.bot.db_pool.acquire() as con:
            role_id = await con.fetchval('''
                SELECT role_id FROM newrole WHERE guild_id = $1
                ''', member.guild.id)
            if role_id is None:
                return
            role = discord.utils.get(member.guild.roles, id=role_id)
            if role is None:
                async with con.transaction():
                    await con.execute('''
                        DELETE FROM newrole WHERE guild_id = $1
                        ''', member.guild.id)
                return
        await member.add_roles(role, reason='New Member')
项目:PomodoroBot    作者:VicenteRD    | 项目源码 | 文件源码
def has_role(member: discord.Member, role_id: str):
    """ Checks if a member has a role with a specified ID.

    :param member: The member to check.
    :type member: discord.Member

    :param role_id: The ID of the role to check for.
    :type role_id: str

    :return: True if the member has a role with the given ID, false otherwise
    """

    for role in member.roles:
        if role.id == role_id:
            return True
    return False
项目:PomodoroBot    作者:VicenteRD    | 项目源码 | 文件源码
def spoof(self, member: discord.Member, channel: discord.Channel):
        """ Spoofs a channel ID if there's a set channel to spoof from
            the one where the command was executed. Also checks for the
            author's permissions to see if they can spoof commands.

        :param member: The member trying to spoof the command.
        :type member: discord.Member

        :param channel: The channel from which the command to spoof was sent.
        :type channel: discord.Channel

        :return: If there's a registered ID to spoof and the author has elevated
            permissions, returns the spoofed ID. If not, returns the same ID
            as channel_id
        """

        if self.has_permission(member) and self.get_interface(channel).spoofed\
                is not None:
            return self._interfaces[channel].spoofed
        return channel
项目:aryas    作者:lattkkthxbbye    | 项目源码 | 文件源码
def clear(self, ctx: commands.Context, number: int, member: discord.Member = None) -> None:
        """
        Purges messages from the channel
        :param ctx: The message context
        :param number: The number of messages to purge
        :param member: The member whose messages will be cleared
        """

        if number < 1:
            await command_error(ctx, "You must attempt to purge at least 1 message!")
            return

        def predicate(msg: discord.Message) -> bool:
            return msg == ctx.message or member is None or msg.author == member

        if number <= 100:
            #  Add 1 to limit to include command message, subtract 1 from the return to not count it.
            msgs = await self.bot.purge_from(ctx.message.channel, limit=number + 1, check=predicate)
            send(self.bot, '{} message{} cleared.'.format(len(msgs) - 1, "s" if len(msgs) - 1 != 1 else ""),
                 ctx.message.channel, True)
        else:
            await command_error(ctx, 'Cannot delete more than 100 messages at a time.')
项目:ridings-cogs    作者:ridinginstyle00    | 项目源码 | 文件源码
def joino(self, ctx, user : discord.Member):
        """Forces another person to join the ranking system"""
        if not user:
            if user.id not in self.leader_board:
                self.leader_board[user.id] = {"name": user.name, "rank": 0, "XP": 0}
                dataIO.save_json("data/levels/leader_board.json", self.leader_board)
                await self.bot.say("{} has joined the Levelboard!".format(user.mention))
            else:
                    await self.bot.say("{} has already joined and is rank {}".format(user.mention, str(self.get_rank(user.id))))
        else:
            if user.id not in self.leader_board:
                self.leader_board[user.id] = {"name": user.name, "rank": 0, "XP": 0}
                dataIO.save_json("data/levels/leader_board.json", self.leader_board)
                await self.bot.say("{} has joined the Levelboard!".format(user.mention))
            else:
                await self.bot.say("{} has already joined and is rank {}".format(user.mention, str(self.get_rank(user.id))))
项目:ridings-cogs    作者:ridinginstyle00    | 项目源码 | 文件源码
def _stats(self, ctx, user : discord.Member=None):
        """Show rank and XP of users.

        Defaults to yours."""
        if not user:
            user = ctx.message.author 
            if self.check_joined(user.id):
                await self.bot.say("{}'s stats: **Wins: {} | Losses: {} | Ties: {} **".format(user.name, self.get_wins(user.id),
                                                                         self.get_losses(user.id),
                                                                         self.get_ties(user.id)))
            else:
                await self.bot.say("{}, you are not yet in the tournament!".format(user.mention))
        else:
            if self.check_joined(user.id):
                await self.bot.say("{}'s stats: **Wins: {} | Losses: {} | Ties: {} **".format(user.name, self.get_wins(user.id),
                                                                         self.get_losses(user.id),
                                                                         self.get_ties(user.id)))
            else:
                await self.bot.say("This user has not joined the tournament")
项目:ridings-cogs    作者:ridinginstyle00    | 项目源码 | 文件源码
def sfp(self, ctx, user: discord.Member=None):
        """Super Falcon Punch"""
        author = ctx.message.author
        if not user:
            await self.bot.say("{} has Super Falcon Punched!".format(author.mention))
            with aiohttp.ClientSession() as session:
                async with session.get("https://cdn.discordapp.com/attachments/172354611477348352/193299243539234817/imgres.jpg") as resp:
                    test = await resp.read()
                    with open("data/commands/Images/imgres.png", "wb") as f:
                        f.write(test)
            await self.bot.upload("data/commands/Images/imgres.png")
        else:
            await self.bot.say("{} has Super Falcon Punched {} and blew him away!".format(author.mention, user.mention))
            with aiohttp.ClientSession() as session:
                async with session.get("https://cdn.discordapp.com/attachments/172354611477348352/193299243539234817/imgres.jpg") as resp:
                    test = await resp.read()
                    with open("data/commands/Images/imgres.png", "wb") as f:
                        f.write(test)
            await self.bot.upload("data/commands/Images/imgres.png")
项目:ridings-cogs    作者:ridinginstyle00    | 项目源码 | 文件源码
def suckmydonut(self, ctx, user : discord.Member = None):
        """Suck My Donuts Beeyatch!"""
        author = ctx.message.author
        if not user:
            with aiohttp.ClientSession() as session:
                async with session.get("http://owned.com/media/_cache/adjusted/postblock/image/4/6/7/2/4672.jpg.png") as resp:
                    test = await resp.read()
                    with open("data/commands/Images/imgres.png", "wb") as f:
                        f.write(test)
                        await self.bot.say("{} says to:".format(author.mention))
            await self.bot.upload("data/commands/Images/imgres.png")
        else:
            with aiohttp.ClientSession() as session:
                async with session.get("http://owned.com/media/_cache/adjusted/postblock/image/4/6/7/2/4672.jpg.png") as resp:
                    test = await resp.read()
                    with open("data/commands/Images/imgres.png", "wb") as f:
                        f.write(test)
                        await self.bot.say("{} tells {} to:".format(author.mention, user.mention))
            await self.bot.upload("data/commands/Images/imgres.png")
项目:ridings-cogs    作者:ridinginstyle00    | 项目源码 | 文件源码
def spank(self, ctx, user : discord.Member = None):
        """Spank"""
        author = ctx.message.author
        if not user:
            with aiohttp.ClientSession() as session:
                async with session.get("https://images-ext-1.discordapp.net/eyJ1cmwiOiJodHRwczovL2Nkbi5kaXNjb3JkYXBwLmNvbS9hdHRhY2htZW50cy8xMDc5NDI2NTIyNzU2MDE0MDgvMTA3OTQ1MDg3MzUwMDc5NDg4L1R1SEdKLmdpZiJ9.-XeFHSFOR0nv53M34HeUBqQc7Wc.gif") as resp:
                    test = await resp.read()
                    with open("data/commands/Images/imgres.gif", "wb") as f:
                        f.write(test)
                        await self.bot.say("{} spanked someone! :scream:".format(author.mention))
            await self.bot.upload("data/commands/Images/imgres.gif")
        else:
            with aiohttp.ClientSession() as session:
                async with session.get("https://images-ext-1.discordapp.net/eyJ1cmwiOiJodHRwczovL2Nkbi5kaXNjb3JkYXBwLmNvbS9hdHRhY2htZW50cy8xMDc5NDI2NTIyNzU2MDE0MDgvMTA3OTQ1MDg3MzUwMDc5NDg4L1R1SEdKLmdpZiJ9.-XeFHSFOR0nv53M34HeUBqQc7Wc.gif") as resp:
                    test = await resp.read()
                    with open("data/commands/Images/imgres.gif", "wb") as f:
                        f.write(test)
                        await self.bot.say("{} spanked {}! :scream:".format(author.mention, user.mention))
            await self.bot.upload("data/commands/Images/imgres.gif")
项目:clifford-discord-bot    作者:jwill89    | 项目源码 | 文件源码
def get_scales(member: discord.Member):
    # Query Database
    with db.cursor() as cursor:
        sql = "SELECT `total` FROM scales WHERE `username` = %s"
        print(str(member))
        cursor.execute(sql, (str(member),))
        entry = cursor.fetchone()
        cursor.close()


    # Return the Number of Scales
    if entry['total'] is not None:
        return entry['total']
    else:
        return 0


# Add Scales to User's Total
项目:clifford-discord-bot    作者:jwill89    | 项目源码 | 文件源码
def get_roles(member: discord.Member):
    """Lists a User's Roles"""

    total = 0
    role_list = ''

    for role in member.roles:
        if total > 0:
            role_list += ', '
        role_list += str(role)
        total += 1

    await bot.say('{0.name} is a member of these roles: '.format(member) + role_list)


# COMMAND: !get_channel_id
项目:Excalibot    作者:endreman0    | 项目源码 | 文件源码
def member(self, ctx, member : discord.Member = None):
        """Retrieves information about a member of the guild."""
        async with ctx.typing():
            member = member or ctx.author
            icon_url = member.avatar_url_as(static_format='png')
            e = discord.Embed(type='rich', color=member.color)
            e.set_thumbnail(url=icon_url)
            e.add_field(name='Name', value=str(member))
            e.add_field(name='ID', value=member.id)
            e.add_field(name='Nickname', value=member.nick)
            e.add_field(name='Bot Created' if member.bot else 'User Joined Discord', value=member.created_at.strftime(datetime_format))
            e.add_field(name='Joined Guild', value=member.joined_at.strftime(datetime_format))
            e.add_field(name='Color', value=str(member.color).upper())

            e.add_field(name='Status and Game', value='%s, playing %s' % (str(member.status).title(), member.game), inline=False)
            roles = sorted(member.roles)[1:] # Remove @everyone
            roles.reverse()
            e.add_field(name='Roles', value=', '.join(role.name for role in roles) or 'None', inline=False)
            e.add_field(name='Icon URL', value=icon_url, inline=False)
        await ctx.send(embed=e)
项目:aikaterna-cogs    作者:aikaterna    | 项目源码 | 文件源码
def displayname(self, member : discord.Member):
        # A helper function to return the member's display name
        nick = name = None
        try:
            nick = member.nick
        except AttributeError:
            pass
        try:
            name = member.name
        except AttributeError:
            pass
        if nick:
            return nick
        if name:
            return name
        return None
项目:kitsuchan-2    作者:n303p4    | 项目源码 | 文件源码
def mine(self, ctx, *, user: discord.Member):
        """Set a tripmine for someone. Tripmines go off at random.

        * user - The person for which the mine will go off.
        """
        if user.id == ctx.bot.user.id:
            await ctx.send("Nope. :3")
        elif (ctx.channel.id in self.tripmines.keys() and
              self.tripmines[ctx.channel.id].has_member(user.id)):
            raise commands.UserInputError(f"A tripmine is already set for {user.display_name}.")
        else:
            self.tripmines.setdefault(ctx.channel.id, TripmineChannelArray())
            self.tripmines[ctx.channel.id].add_member(user.id)
            message = await ctx.send(f"Tripmine set for {user.display_name}! :3")
            await asyncio.sleep(3)
            await message.delete()
项目:kitsuchan-2    作者:n303p4    | 项目源码 | 文件源码
def unmine(self, ctx, *, user: discord.Member):
        """Remove a tripmine from yourself, or from someone else.

        * user - The person for which the mine will go off.
        """
        if not user:
            user = ctx.author

        if user.id == ctx.bot.user.id:
            await ctx.send("Nope. :3")
        elif (ctx.channel.id in self.tripmines.keys() and
              self.tripmines[ctx.channel.id].has_member(user.id)):
            self.tripmines[ctx.channel.id].remove_member(user.id)
            await ctx.send(f"Removed tripmine for {user.display_name}! :3")
        else:
            raise commands.UserInputError(f"No tripmine is currently set for {user.display_name}.")
项目:discordbot.py    作者:rauenzi    | 项目源码 | 文件源码
def plonk(self, ctx, *, member: discord.Member):
        """Bans a user from using the bot.

        This bans a person from using the bot in the current server.
        There is no concept of a global ban. This ban can be bypassed
        by having the Manage Server permission.

        To use this command you must have the Manage Server permission
        or have a Bot Admin role.
        """

        plonks = self.config.get('plonks', {})
        guild_id = ctx.message.server.id
        db = plonks.get(guild_id, [])

        if member.id in db:
            await self.bot.responses.failure(message='That user is already bot banned in this server.')
            return

        db.append(member.id)
        plonks[guild_id] = db
        await self.config.put('plonks', plonks)
        await self.bot.responses.success(message='%s has been banned from using the bot in this server.' % member)
项目:discordbot.py    作者:rauenzi    | 项目源码 | 文件源码
def unplonk(self, ctx, *, member: discord.Member):
        """Unbans a user from using the bot.

        To use this command you must have the Manage Server permission
        or have a Bot Admin role.
        """

        plonks = self.config.get('plonks', {})
        guild_id = ctx.message.server.id
        db = plonks.get(guild_id, [])

        try:
            db.remove(member.id)
        except ValueError:
            await self.bot.responses.failure(message='%s is not banned from using the bot in this server.' % member)
        else:
            plonks[guild_id] = db
            await self.config.put('plonks', plonks)
            await self.bot.responses.success(message='%s has been unbanned from using the bot in this server.' % member)
项目:calebj-cogs    作者:calebj    | 项目源码 | 文件源码
def protect_common(self, obj, protect=True):
        if not isinstance(obj, (discord.Member, discord.Role)):
            raise TypeError('Can only pass member or role objects.')
        server = obj.server
        id = ('r' if type(obj) is discord.Role else '') + obj.id

        protected = self.duelists.get(server.id, {}).get("protected", [])
        if protect == (id in protected):
            return False
        elif protect:
            protected.append(id)
        else:
            protected.remove(id)

        if server.id not in self.duelists:
            self.duelists[server.id] = {}
        self.duelists[server.id]['protected'] = protected
        dataIO.save_json(JSON_PATH, self.duelists)
        return True
项目:SESTREN    作者:SirThane    | 项目源码 | 文件源码
def c4_play(self, ctx, *, user: discord.Member=None):
        """Star a game of Connect Four

        `[p]c4 start @user` will start a game
        with that user in the current channel."""
        if not self.chan_check(ctx):
            return
        if user:
            session = self.session(ctx)
            if session:
                await self.message(ctx, msg="There is already an active game in this channel.", level=2)
            elif user.id == ctx.author.id:
                await self.message(ctx, msg="You cannot start a game with yourself.", level=1)
            elif user.id == self.bot.user.id:
                await self.message(ctx, msg="NOT IMPLEMENTED: You can play against SESTREN soon."
                                            "<:doritoface:337530039677485057>", level=1)
            #     self.sessions[ctx.channel.id] = ConnectFourSession(user, ctx)
            #     await self.send_board(ctx, init=True)
            #     self.sessions[ctx.channel.id].s_play()
            #     await self.send_board(ctx)
            else:
                self.sessions[ctx.channel.id] = ConnectFourSession(user, ctx)
                await self.send_board(ctx, init=True)
        else:
            await self.bot.formatter.format_help_for(ctx, ctx.command, "You need another player to start.")
项目:SESTREN    作者:SirThane    | 项目源码 | 文件源码
def discrim(self, ctx, *, member: discord.Member=None):
        """Finds a username that you can use to change discriminator

        [p]discrim"""
        if not member:
            member = ctx.author

        d = member.discriminator
        f = discord.utils.find(lambda x: x.discriminator == d and not x.id == member.id,
                               self.bot.get_all_members())
        if f is not None:
            em = discord.Embed(title="Discrim",
                               description="Change your name to `{}` and then back to `{}` to get a new discriminator"
                                           "".format(f.name, member.name), colour=0x00FF00)
            await ctx.send(embed=em)
        else:
            em = discord.Embed(title="Sorry",
                               description="I couldn't find another person with your discriminator", colour=0xFF0000)
            await ctx.send(embed=em)
项目:FalltoSkyBot    作者:Sakiut    | 项目源码 | 文件源码
def mute(self, ctx, *, user:discord.Member):
        """Mute un utilisateur
        Requiert la permission de kick"""

        await self.bot.delete_message(ctx.message)

        if ctx.message.author.server_permissions.kick_members == True:

            overwrite = ctx.message.channel.overwrites_for(user) or discord.PermissionOverwrite()
            overwrite.send_messages = False
            await self.bot.edit_channel_permissions(ctx.message.channel, user, overwrite)
            tmp = await self.bot.send_message(ctx.message.channel, "{} is now muted here !".format(user.mention))
            await asyncio.sleep(5)
            await self.bot.delete_message(tmp)

        else:
            tmp = await self.bot.say("```\nVous n'avez pas la permission d'utiliser cette commande\n```")
            await asyncio.sleep(5)
            await self.bot.delete_message(tmp)
项目:FalltoSkyBot    作者:Sakiut    | 项目源码 | 文件源码
def unmute(self, ctx, *, user:discord.Member):
        """Unute un utilisateur
        Requiert la permission de kick"""

        await self.bot.delete_message(ctx.message)

        if ctx.message.author.server_permissions.kick_members == True:

            overwrite = ctx.message.channel.overwrites_for(user) or discord.PermissionOverwrite()
            overwrite.send_messages = True
            await self.bot.edit_channel_permissions(ctx.message.channel, user, overwrite)
            tmp = await self.bot.send_message(ctx.message.channel, "{} is no longer muted here! He/she can speak now!".format(user.mention))
            await asyncio.sleep(5)
            await self.bot.delete_message(tmp)

        else:
            tmp = await self.bot.say("```\nVous n'avez pas la permission d'utiliser cette commande\n```")
            await asyncio.sleep(5)
            await self.bot.delete_message(tmp)
项目:FalltoSkyBot    作者:Sakiut    | 项目源码 | 文件源码
def report(self, ctx, user: discord.Member, *, reason: str):
        """Reporte un utilisateur au staff"""

        await self.bot.delete_message(ctx.message)

        server = ctx.message.server
        Channels = server.channels
        End = []

        Return = False

        for chan in list(Channels):
            Name = str(chan.name)
            Type = str(chan.type)
            if "moderation" in str(chan.name):
                if Type is "text":
                    ModChan = chan
                    Return = True

        if Return is not True:
            ModChan = await self.bot.create_channel(server, 'moderation', type=discord.ChannelType.text)

        await self.bot.send_message(ModChan, "{0} a été report par {1}, raison : {2}, @here".format(user.mention, ctx.message.author.mention, reason))
项目:FalltoSkyBot    作者:Sakiut    | 项目源码 | 文件源码
def money(self, ctx, *, user:discord.Member=None):
        """Affiche votre cagnotte"""

        data        = casino.start()
        server      = ctx.message.server
        if not user:
            user    = ctx.message.author
        chan        = ctx.message.channel

        await self.bot.delete_message(ctx.message)
        money = casino.get(server, user, data)

        mon_embed           = discord.Embed()
        mon_embed.colour    = 0x3498db
        mon_embed.title     = "Cagnotte : {}$".format(str(money))
        mon_embed.set_footer(text = "{0}#{1}".format(user.name, user.discriminator), icon_url = user.avatar_url)
        await self.bot.say(embed = mon_embed)
项目:FalltoSkyBot    作者:Sakiut    | 项目源码 | 文件源码
def add_money(self, ctx, *, user:discord.Member=None):
        """Ajoute de l'argent à la cagnotte d'un utilisateur
        Bot Master uniquement"""

        data        = casino.start()
        server      = ctx.message.server
        if not user:
            user    = ctx.message.author
        chan        = ctx.message.channel

        if ctx.message.author.id == "187565415512276993":
            await self.bot.delete_message(ctx.message)
            tmp = await self.bot.say("Combien voulez-vous ajouter à la cagnotte de {} ?".format(user.name))
            ans = await self.bot.wait_for_message(author = ctx.message.author, channel = chan)
            money = int(ans.content)
            await self.bot.delete_message(ans)
            casino.post(server, user, data, money)
            await self.bot.delete_message(tmp)
            tmp = await self.bot.say("Done")
            await asyncio.sleep(3)
            await self.bot.delete_message(tmp)
        else:
            return
项目:pcbot    作者:pckv    | 项目源码 | 文件源码
def format_new_score(mode: api.GameMode, score: dict, beatmap: dict, rank: int, member: discord.Member):
    """ Format any score. There should be a member name/mention in front of this string. """
    acc = calculate_acc(mode, score)
    return (
        "[{i}{artist} - {title} [{version}]{i}]({host}b/{beatmap_id})\n"
        "**{pp}pp {stars:.2f}\u2605, {rank} {scoreboard_rank}+{mods}**"
        "```diff\n"
        "  acc     300s   100s   50s    miss   combo\n"
        "{sign} {acc:<8.2%}{count300:<7}{count100:<7}{count50:<7}{countmiss:<7}{maxcombo}{max_combo}```"
        "{live}"
    ).format(
        host=host,
        sign="!" if acc == 1 else ("+" if score["perfect"] == "1" else "-"),
        mods=Mods.format_mods(int(score["enabled_mods"])),
        acc=acc,
        artist=beatmap["artist"].replace("_", "\_"),
        title=beatmap["title"].replace("_", "\_"),
        i="*" if "*" not in beatmap["artist"] + beatmap["title"] else "",  # Escaping asterisk doesn't work in italics
        version=beatmap["version"],
        stars=float(beatmap["difficultyrating"]),
        max_combo="/{}".format(beatmap["max_combo"]) if mode in (api.GameMode.Standard, api.GameMode.Catch) else "",
        scoreboard_rank="#{} ".format(rank) if rank else "",
        live=await format_stream(member, score, beatmap),
        **score
    )
项目:pcbot    作者:pckv    | 项目源码 | 文件源码
def info(message: discord.Message, member: discord.Member=Annotate.Self):
    """ Display configuration info. """
    # Make sure the member is assigned
    assert member.id in osu_config.data["profiles"], "No osu! profile assigned to **{}**!".format(member.name)

    user_id = osu_config.data["profiles"][member.id]
    mode = get_mode(member.id)
    update_mode = get_update_mode(member.id)

    e = discord.Embed(color=member.color)
    e.set_author(name=member.display_name, icon_url=member.avatar_url, url=host + "u/" + user_id)
    e.add_field(name="Game Mode", value=mode.name)
    e.add_field(name="Notification Mode", value=update_mode.name)
    e.add_field(name="Playing osu!", value="YES" if member.id in osu_tracking.keys() else "NO")

    await client.send_message(message.channel, embed=e)
项目:pcbot    作者:pckv    | 项目源码 | 文件源码
def can_use_command(cmd: Command, author, channel: discord.Channel=None):
    """ Return True if the member who sent the message can use this command. """
    if cmd.owner and not is_owner(author):
        return False
    if channel is not None and not has_permissions(cmd, author, channel):
        return False
    if not has_roles(cmd, author):
        return False

    # Handle server specific commands for both server and PM commands
    if type(author) is discord.User and cmd.servers:
        return False
    if type(author) is discord.Member and not is_valid_server(cmd, author.server):
        return False

    return True
项目:Squid-Plugins    作者:tekulvw    | 项目源码 | 文件源码
def addrole(self, ctx, rolename, user: discord.Member=None):
        """Adds a role to a user, defaults to author

        Role name must be in quotes if there are spaces."""
        author = ctx.message.author
        channel = ctx.message.channel
        server = ctx.message.server

        if user is None:
            user = author

        role = self._role_from_string(server, rolename)

        if role is None:
            await self.bot.say('That role cannot be found.')
            return

        if not channel.permissions_for(server.me).manage_roles:
            await self.bot.say('I don\'t have manage_roles.')
            return

        await self.bot.add_roles(user, role)
        await self.bot.say('Added role {} to {}'.format(role.name, user.name))
项目:Squid-Plugins    作者:tekulvw    | 项目源码 | 文件源码
def removerole(self, ctx, rolename, user: discord.Member=None):
        """Removes a role from user, defaults to author

        Role name must be in quotes if there are spaces."""
        server = ctx.message.server
        author = ctx.message.author

        role = self._role_from_string(server, rolename)
        if role is None:
            await self.bot.say("Role not found.")
            return

        if user is None:
            user = author

        if role in user.roles:
            try:
                await self.bot.remove_roles(user, role)
                await self.bot.say("Role successfully removed.")
            except discord.Forbidden:
                await self.bot.say("I don't have permissions to manage roles!")
        else:
            await self.bot.say("User does not have that role.")
项目:apex-sigma-core    作者:lu-ci    | 项目源码 | 文件源码
def check_roles(allowed_roles, all_users, user):
    members = []
    for member in all_users:
        if isinstance(member, discord.Member):
            if member.id == user.id:
                members.append(member)
    authorized = False
    for member_item in members:
        for allowed_role in allowed_roles:
            role = discord.utils.find(lambda x: x.id == allowed_role, member_item.roles)
            if role:
                authorized = True
                break
        if authorized:
            break
    return authorized
项目:GrandeCogs    作者:HarukiGrande    | 项目源码 | 文件源码
def pat(self, context, member: discord.Member):
        """Pat your senpai/waifu!"""
        author = context.message.author.mention
        mention = member.mention

        pat = "**{0} got patted by {1}!**"

        choices = ['http://i.imgur.com/10VrpFZ.gif', 'http://i.imgur.com/x0u35IU.gif', 'http://i.imgur.com/0gTbTNR.gif', 'http://i.imgur.com/hlLCiAt.gif', 'http://i.imgur.com/sAANBDj.gif']

        image = random.choice(choices)

        embed = discord.Embed(description=pat.format(mention, author), colour=discord.Colour.blue())
        embed.set_image(url=image)

        await self.bot.say(embed=embed)
项目:GrandeCogs    作者:HarukiGrande    | 项目源码 | 文件源码
def kiss(self, context, member: discord.Member):
        """Kiss your senpai/waifu!"""
        author = context.message.author.mention
        mention = member.mention

        kiss = "**{0} gave {1} a kiss!**"

        choices = ['http://i.imgur.com/0D0Mijk.gif', 'http://i.imgur.com/TNhivqs.gif', 'http://i.imgur.com/3wv088f.gif', 'http://i.imgur.com/7mkRzr1.gif', 'http://i.imgur.com/8fEyFHe.gif']

        image = random.choice(choices)

        embed = discord.Embed(description=kiss.format(author, mention), colour=discord.Colour.blue())
        embed.set_image(url=image)

        await self.bot.say(embed=embed)
项目:GrandeCogs    作者:HarukiGrande    | 项目源码 | 文件源码
def hug(self, context, member: discord.Member):
        """Hug your senpai/waifu!"""
        author = context.message.author.mention
        mention = member.mention

        hug = "**{0} gave {1} a hug!**"

        choices = ['http://i.imgur.com/sW3RvRN.gif', 'http://i.imgur.com/gdE2w1x.gif', 'http://i.imgur.com/zpbtWVE.gif', 'http://i.imgur.com/ZQivdm1.gif', 'http://i.imgur.com/MWZUMNX.gif']

        image = random.choice(choices)

        embed = discord.Embed(description=hug.format(author, mention), colour=discord.Colour.blue())
        embed.set_image(url=image)

        await self.bot.say(embed=embed)
项目:Jumper-Cogs    作者:Redjumpman    | 项目源码 | 文件源码
def _give_shop(self, ctx, user: discord.Member, *, itemname):
        """Adds an item to a users inventory. Item must be in the shop."""
        author = ctx.message.author
        settings = self.check_server_settings(author.server)
        itemname = itemname.title()
        self.user_check(settings, user)
        if itemname in settings["Shop List"]:
            quantity = 1
            self.user_give_item(settings, user, quantity, itemname)
            msg = "{} was given {} by {}".format(user.mention, itemname, author.mention)
        else:
            msg = "No such item in the shop."
        await self.bot.say(msg)
项目:Jumper-Cogs    作者:Redjumpman    | 项目源码 | 文件源码
def _gift_shop(self, ctx, user: discord.Member, quantity: int, *, itemname):
        """Send a number of items from your inventory to another user"""
        if quantity < 1:
            return await self.bot.say("Quantity must be higher than 0.")

        author = ctx.message.author
        itemname = itemname.title()
        settings = self.check_server_settings(author.server)
        self.user_check(settings, author)
        self.user_check(settings, user)
        if author == user:
            await self.bot.say("This is awkward. You can't do this action with yourself.")
        else:
            await self.user_gifting(settings, user, author, itemname, quantity)
项目:Jumper-Cogs    作者:Redjumpman    | 项目源码 | 文件源码
def _trade_shop(self, ctx, user: discord.Member, quantity: int, *, tradeoffer: str):
        """Request a trade with another user"""
        author = ctx.message.author
        tradeoffer = tradeoffer.title()
        settings = self.check_server_settings(author.server)
        self.user_check(settings, author)
        self.user_check(settings, user)
        result = self.trade_checks(settings, author, user, tradeoffer, quantity)
        if result != "OK":
            return await self.bot.say(result)
        await self.trade_handler(settings, user, author, tradeoffer, quantity)
项目:Jumper-Cogs    作者:Redjumpman    | 项目源码 | 文件源码
def _anime_mal(self, ctx, user: discord.Member=None):
        """Lookup another user's MAL for anime"""
        author = ctx.message.author
        cmd = "anime"
        if not user:
            user = author
        await self.fetch_profile(user, author, cmd)