Exemplo n.º 1
0
    raise error


@bot.event
async def on_command(ctx):
    await ctx.message.add_reaction('⌚')


@bot.event
async def on_command_completion(ctx):
    await ctx.message.add_reaction('✅')
    await ctx.message.remove_reaction('⌚', ctx.bot.user)

@bot.command()
@is_public_council_channel()
@commands.check_any(commands.has_any_role('Council Members', 'Admins', 'Mods'), commands.is_owner(), commands.has_permissions(manage_permissions=True))
async def lock(ctx):
    await ctx.channel.set_permissions(ctx.guild.default_role, send_messages=False)
    await ctx.reply("This channel is now locked.")

@bot.command()
@is_public_council_channel()
@commands.check_any(commands.has_any_role('Council Members', 'Admins', 'Mods'), commands.is_owner(), commands.has_permissions(manage_permissions=True))
async def unlock(ctx):
    await ctx.channel.set_permissions(ctx.guild.default_role, send_messages=True)
    await ctx.reply("This channel is now unlocked.")

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.create_task(bot.start(os.environ.get("DISCORD_TOKEN")))
    loop.run_forever()
Exemplo n.º 2
0
def is_owner_or_admin():
    return commands.check(lambda ctx: is_owner_check(ctx.message)) or commands.has_permissions(administrator=True)
Exemplo n.º 3
0
class Role(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.Cog.listener()
    async def on_raw_reaction_add(self, payload):
        emoji = str(payload.emoji)
        roles = await role.get_role_by_group_emoji(payload.channel_id, payload.message_id, emoji, payload.guild_id)

        if len(roles) == 0:
            return  # we don't want to continue, as there isn't really anything more we need to do here

        guild = await self.bot.fetch_guild(payload.guild_id)
        member = await guild.fetch_member(payload.user_id)
        for roleids in roles:
            role_obj = guild.get_role(roleids['role_id'])
            if role_obj is None:
                continue
            else:
                await member.add_roles(role_obj, reason="Added by message reaction.")

    @commands.Cog.listener()
    async def on_raw_reaction_remove(self, payload):
        emoji = str(payload.emoji)
        roles = await role.get_role_by_group_emoji(payload.channel_id, payload.message_id, emoji, payload.guild_id)

        if len(roles) == 0:
            return  # we don't want to continue, as there isn't really anything more we need to do here

        guild = await self.bot.fetch_guild(payload.guild_id)
        member = await guild.fetch_member(payload.user_id)
        for roleids in roles:
            role_obj = guild.get_role(roleids['role_id'])
            if role_obj is None:
                continue
            else:
                await member.remove_roles(role_obj, reason="Removed by message reaction.")

    @commands.group(aliases=['rr'])
    @commands.check_any(commands.has_permissions(manage_roles=True), commands.is_owner())
    async def reactionrole(self, ctx):
        pass

    @reactionrole.command(name='create', aliases=['c'])
    async def role_create(self, ctx, group_id: int, role_name: discord.Role, name, description, emoji, protect_mentions: bool = True):
        existing_roles = await role.get_group_roles(group_id, ctx.guild.id)
        if len(existing_roles) >= 20:
            raise SahasrahBotException(
                'No more than 20 roles can be on a group.  Please create a new group.')

#        if discord.utils.find(lambda e: str(e) == emoji, ctx.bot.emojis) is None and not is_emoji(emoji):
#            raise SahasrahBotException(
#                'Custom emoji is not available to this bot.')

        await role.create_role(ctx.guild.id, group_id, role_name.id, name, emoji, description, protect_mentions)
        await refresh_bot_message(ctx, group_id)

    @reactionrole.command(name='update', aliases=['u'])
    async def role_update(self, ctx, role_id: int, name, description, protect_mentions: bool = False):
        await role.update_role(ctx.guild.id, role_id, name, description, protect_mentions)
        groups = await role.get_role_group(role_id, ctx.guild.id)
        await refresh_bot_message(ctx, groups[0]['id'])

    # this is a whole pile of trash...
    @reactionrole.command(name='delete', aliases=['del'])
    async def role_delete(self, ctx, role_id: int):
        groups = await role.get_role_group(role_id, ctx.guild.id)
        channel = ctx.guild.get_channel(groups[0]['channel_id'])
        message = await channel.fetch_message(groups[0]['message_id'])

        await message.remove_reaction(strip_custom_emoji(groups[0]['emoji']), ctx.bot.user)

        await role.delete_role(ctx.guild.id, role_id)

        await refresh_bot_message(ctx, groups[0]['id'])

    @reactionrole.command(name='list', aliases=['l'])
    async def role_list(self, ctx, group_id: int):
        roles = await role.get_group_roles(group_id, ctx.guild.id)
        await ctx.reply(embed=embed_formatter.reaction_role_list(ctx, roles))

    @commands.group(aliases=['rg'])
    @commands.check_any(commands.has_permissions(manage_roles=True), commands.is_owner())
    async def reactiongroup(self, ctx):
        pass

    @reactiongroup.command(name='create', aliases=['c'])
    async def group_create(self, ctx, channel: discord.TextChannel, name, description=None, bot_managed: bool = True, message_id: int = None):
        if bot_managed:
            message = await channel.send('temp message')
        else:
            message = await channel.fetch_message(message_id)
        await role.create_group(ctx.guild.id, channel.id, message.id, name, description, bot_managed)

    @reactiongroup.command(name='update', aliases=['u'])
    async def group_update(self, ctx, group_id: int, name, description):
        await role.update_group(ctx.guild.id, group_id, name, description)
        await refresh_bot_message(ctx, group_id)

    @reactiongroup.command(name='refresh', aliases=['r'])
    async def group_refresh(self, ctx, group_id: int):
        await refresh_bot_message(ctx, group_id)

    @reactiongroup.command(name='delete', aliases=['d'])
    async def group_delete(self, ctx, group_id: int):
        await role.delete_group(ctx.guild.id, group_id)

    @reactiongroup.command(name='list', aliases=['l'])
    async def group_list(self, ctx, group_id: int = None):
        if group_id is None:
            groups = await role.get_guild_groups(ctx.guild.id)
        else:
            groups = await role.get_guild_group_by_id(group_id, ctx.guild.id)
        await ctx.reply(embed=await embed_formatter.reaction_group_list(ctx, groups))

    @commands.command()
    @commands.check_any(commands.has_permissions(manage_roles=True), commands.is_owner())
    async def importroles(self, ctx, mode=None):
        if ctx.message.attachments:
            content = await ctx.message.attachments[0].read()
            role_import_list = csv.DictReader(
                io.StringIO(content.decode()))
            for i in role_import_list:
                try:
                    role_obj = await commands.RoleConverter().convert(ctx, i['role'])
                except commands.BadArgument:
                    await ctx.reply(f"Failed to find role identified by {i['role']}")
                    continue

                try:
                    member_obj = await commands.MemberConverter().convert(ctx, i['member'])
                except commands.BadArgument:
                    await ctx.reply(f"Failed to find member identified by {i['member']}")
                    continue

                if not mode == "dry":
                    await member_obj.add_roles(role_obj)
        else:
            raise SahasrahBotException("You must supply a valid csv file.")
Exemplo n.º 4
0
def is_admin():
    return commands.check_any(
        commands.is_owner(), commands.has_permissions(administrator=True)
    )
Exemplo n.º 5
0
class Economy(commands.Cog):
    def __init__(self, client):
        self.client = client

        print('Caching Economy Database...')
        self.balance_dict = {i['_id']: i['balance'] for i in self.client.currency_data.find()}
        self.pricing = {1: 500, 2: 2000, 3: 5000, 4: 10000, 5: 20000,
                        6: 50000, 7: 80000, 8: 100000}
        print('Done')

    @commands.Cog.listener()
    async def on_ready(self):
        print(f"{self.__class__.__name__} loaded successfully.")

    @commands.command(aliases=['balance', 'coins'])
    async def bal(self, ctx, user: discord.Member = None):
        user = ctx.author if not user else user
        if user.id not in self.balance_dict:
            post = {"_id": user.id, "balance": 0}
            self.client.currency_data.insert_one(post)
            self.balance_dict[user.id] = 0
        if user == ctx.author:
            await ctx.send(embed=discord.Embed(title=f"{user.name}'s balance",
                                               description=f'You have currently {self.balance_dict.get(user.id)} <:DogyCoin:844481455823519754>',
                                               color=discord.Color.gold(),
                                               timestamp=datetime.datetime.now(pytz.timezone('Asia/Kolkata'))))
        else:
            await ctx.send(embed=discord.Embed(title=f'{user.name}#{user.discriminator}',
                                               description=f'They have currently {self.balance_dict.get(user.id)} <:DogyCoin:844481455823519754>',
                                               color=discord.Color.gold(),
                                               timestamp=datetime.datetime.now(pytz.timezone('Asia/Kolkata'))))

    @commands.command()
    @commands.check_any(commands.has_role("Tournament Manager"), commands.has_permissions(administrator=True))
    async def addbal(self, ctx, members: commands.Greedy[discord.Member], balance: commands.Greedy[int]):
        if members == [] or balance == []:
            await ctx.send("Missing required arguments..")
            return
        if len(members) == len(balance):
            log = ''
            for x, y in zip(members, balance):
                try:
                    self.balance_dict[x.id] += y
                except KeyError:
                    self.balance_dict[x.id] = y
                self.client.currency_data.update_one({"_id": x.id}, {"$set": {"balance": self.balance_dict[x.id]}},
                                                     upsert=True)
                log += f"Added {y} <:DogyCoin:844481455823519754> to {x.mention}. \nUpdated bal: {self.balance_dict[x.id]} <:DogyCoin:844481455823519754>\n"
            await ctx.send(embed=discord.Embed(title="Balance Updated!",
                                               color=discord.Color.green(),
                                               description=log))
        elif len(balance) == 1:
            log = f"Added {balance[0]} <:DogyCoin:844481455823519754> to "
            for i in members:
                try:
                    self.balance_dict[i.id] += balance[0]
                except KeyError:
                    self.balance_dict[i.id] = balance[0]
                self.client.currency_data.update_one({"_id": i.id}, {"$set": {"balance": self.balance_dict[i.id]}},
                                                     upsert=True)
                log += f"{i.mention} "
            await ctx.send(embed=discord.Embed(title="Balance Updated!",
                                               color=discord.Color.green(),
                                               description=log))
        else:
            await ctx.send("Some error occurred.")

    @commands.command()
    @commands.check_any(commands.has_role("Tournament Manager"), commands.has_permissions(administrator=True))
    async def deduct(self, ctx, member: discord.Member, amount: int, msg: typing.Optional[bool] = True):
        try:
            self.balance_dict[member.id] -= amount
        except KeyError:
            self.balance_dict[member.id] = -amount
        self.client.currency_data.update_one({"_id": member.id}, {"$set": {"balance": self.balance_dict[member.id]}},
                                             upsert=True)
        if msg:
            await ctx.send(embed=discord.Embed(title="DogyCoins Deducted!",
                                               description=f"Deducted {amount} from {member.mention}\n"
                                                           f"Updated Bal: {self.balance_dict[member.id]} <:DogyCoin:844481455823519754>",
                                               color=discord.Color.red()))

    @commands.command()
    @commands.is_owner()
    async def setbal(self, ctx, member: discord.Member, balance):
        self.balance_dict[member.id] = int(balance)
        self.client.currency_data.update_one({"_id": member.id}, {"$set": {"balance": self.balance_dict[member.id]}},
                                             upsert=True)
        await ctx.send(embed=discord.Embed(title='Balance Updated.',
                                           description=f"Updated {member.mention} balance..\n"
                                                       f"They have now {self.balance_dict[member.id]} <:DogyCoin:844481455823519754>",
                                           color=member.color))

    @commands.command(aliases=['lb'])
    async def leaderboard(self, ctx):
        length = len(self.balance_dict.keys())
        no_of_embeds = length / 10 if length % 10 == 0 else int(length / 10) + 1
        emoji = self.client.get_emoji(844481455823519754)
        sorted_dict_desc = dict(sorted(self.balance_dict.items(), key=itemgetter(1), reverse=True))
        keys = [a for a in sorted_dict_desc.keys()]
        values = [b for b in sorted_dict_desc.values()]
        key_lists = [keys[i: i + 10] for i in range(0, len(keys), 10)]
        values_list = [values[i: i + 10] for i in range(0, len(values), 10)]
        embeds = []
        for i in range(1, no_of_embeds + 1):
            embed = discord.Embed(title=f"Richest members of {ctx.guild.name} | Page {i}",
                                  color=discord.Color.gold(), description='')
            for count, user_id, coins in zip(range(i * 10 - 9, i * 10 + 1), key_lists[i - 1], values_list[i - 1]):
                user = discord.utils.get(ctx.guild.members, id=user_id)
                if user is not None:
                    embed.description += f'{count}. {user.name}#{user.discriminator} - {coins} <:DogyCoin:844481455823519754>\n'
                else:
                    pass
            embed.set_author(name='Leaderboard', icon_url=emoji.url)
            embeds.append(embed)
        paginator = CustomEmbedPaginator(ctx, auto_footer=True, remove_reactions=True)
        for emoji, cmd in self.client.emoji_cmd_dict.items():
            paginator.add_reaction(emoji, cmd)
        await paginator.run(embeds)

    @commands.command()
    async def shop(self, ctx):
        embed = discord.Embed(title='DogyCoin Shop', color=discord.Color.dark_gold())
        embed.description = "1. 500 <:DogyCoin:844481455823519754> - Nickname Change(once)\n" \
                            "2. 2000 <:DogyCoin:844481455823519754> - Dwellers role.\n" \
                            "3. 5000 <:DogyCoin:844481455823519754> - Permanent Nickname Change Perms\n" \
                            "4. 10000 <:DogyCoin:844481455823519754> - 10₹\n" \
                            "5. 20000 <:DogyCoin:844481455823519754> - 1 Week Tourney Pass\n" \
                            "6. 50000 <:DogyCoin:844481455823519754> - 55₹\n" \
                            "7. 80000 <:DogyCoin:844481455823519754> - 85₹\n" \
                            "8. 100000 <:DogyCoin:844481455823519754> - 1 month tourney pass\n" \
                            "*Note - Things are subject to change as this is still in development.\n " \
                            "These are just placeholders anyways you can still buy it."
        embed.set_footer(text='Dm Leo to purchase.')
        await ctx.send(embed=embed)

    @commands.group(invoke_without_command=True)
    @commands.cooldown(1, 5, commands.BucketType.user)
    async def buy(self, ctx):
        message = ''
        bot_msg = await ctx.send("Provide the index of the item you want to buy.")

        def check(m):
            return m.author == ctx.author and m.channel == ctx.channel

        try:
            message = await self.client.wait_for('message', check=check, timeout=10.0)
        except asyncio.TimeoutError:
            await bot_msg.add_reaction('❌')
        try:
            index = int(message)
        except ValueError:
            await ctx.send("Provide the correct index of the item.")
            await message.add_reaction('🚫')
            return
        if index not in self.pricing.keys():
            await message.add_reaction('❌')
            await ctx.send("Provide the correct index of the shop items.")
        else:
            await ctx.send("Command work in progress")
            # await self.client.get_command(f'{message.content}')(ctx=ctx)

    @buy.command(aliases=['1'])
    async def item1(self, ctx):
        capable = self.is_capable(ctx, 1)
        if not capable:
            await ctx.send("You don't have enough coins to purchase the item.")
            return
        await ctx.send('command work in progress')
        # await self.client.get_command('deduct')(ctx=ctx, member=ctx.author, amount=self.pricing.get(1), msg=False)
        # the item function

    @buy.command(aliases=['2'])
    async def item2(self, ctx):
        capable = self.is_capable(ctx, 1)
        if not capable:
            await ctx.send("You don't have enough coins to purchase the item.")
            return
        await ctx.send('command work in progress')
        # await self.client.get_command('deduct')(ctx=ctx, member=ctx.author, amount=self.pricing.get(1), msg=False)
        # the item function

    @buy.command(aliases=['3'])
    async def item3(self, ctx):
        capable = self.is_capable(ctx, 1)
        if not capable:
            await ctx.send("You don't have enough coins to purchase the item.")
            return
        await ctx.send('command work in progress')
        # await self.client.get_command('deduct')(ctx=ctx, member=ctx.author, amount=self.pricing.get(1), msg=False)
        # the item function

    @buy.command(aliases=['4'])
    async def item4(self, ctx):
        capable = self.is_capable(ctx, 1)
        if not capable:
            await ctx.send("You don't have enough coins to purchase the item.")
            return
        await ctx.send('command work in progress')
        # await self.client.get_command('deduct')(ctx=ctx, member=ctx.author, amount=self.pricing.get(1), msg=False)
        # the item function

    @buy.command(aliases=['5'])
    async def item5(self, ctx):
        capable = self.is_capable(ctx, 1)
        if not capable:
            await ctx.send("You don't have enough coins to purchase the item.")
            return
        await ctx.send('command work in progress')
        # await self.client.get_command('deduct')(ctx=ctx, member=ctx.author, amount=self.pricing.get(1), msg=False)
        # the item function

    @buy.command(aliases=['6'])
    async def item6(self, ctx):
        capable = self.is_capable(ctx, 1)
        if not capable:
            await ctx.send("You don't have enough coins to purchase the item.")
            return
        await ctx.send('command work in progress')
        # await self.client.get_command('deduct')(ctx=ctx, member=ctx.author, amount=self.pricing.get(1), msg=False)
        # the item function

    @buy.command(aliases=['7'])
    async def item7(self, ctx):
        capable = self.is_capable(ctx, 1)
        if not capable:
            await ctx.send("You don't have enough coins to purchase the item.")
            return
        await ctx.send('command work in progress')
        # await self.client.get_command('deduct')(ctx=ctx, member=ctx.author, amount=self.pricing.get(1), msg=False)
        # the item function

    @buy.command(aliases=['8'])
    async def item8(self, ctx):
        capable = self.is_capable(ctx, 1)
        if not capable:
            await ctx.send("You don't have enough coins to purchase the item.")
            return
        await ctx.send('command work in progress')
        # await self.client.get_command('deduct')(ctx=ctx, member=ctx.author, amount=self.pricing.get(1), msg=False)
        # the item function

    def is_capable(self, ctx, price_index):
        user_bal = self.balance_dict.get(ctx.author.id)
        if user_bal is None:
            return False
        if user_bal < self.pricing.get(price_index):
            return False
        return True
Exemplo n.º 6
0
class BsVerification(commands.Cog):
    def __init__(self, client):
        print('Loading BSVerification Data')
        self.client = client
        self.basic_club_role = 727782320165355523
        self.family_role = 843442036111573003
        self.loading_emj = '<a:loading:848756850458361876>'
        self.failed_emj = '<a:failed:848757026418851840>'
        self.success_emj = '<a:success:848756404797964288>'
        with open('secrets.json') as f:
            bs_token = json.load(f)['bs_api_token']
        self.tag_dict = {
            i['_id']: i['player_tag']
            for i in self.client.bs_data.find()
        }
        self.club_role_dict = {
            j['club_tag']: {
                'club_name': j['club_name'],
                'role_id': j['_id']
            }
            for j in self.client.club_roles_data.find()
        }
        self.position_role_dict = {
            "member": 841908832007487488,
            "senior": 841908822653534229,
            "vicepresident": 842630288143417364,
            "president": 698419850082779196
        }
        self.bs_client = brawlstats.Client(is_async=True, token=bs_token)
        print("Done.")

    @commands.command()
    @commands.check_any(commands.has_permissions(administrator=True),
                        commands.has_any_role('Moderator'))
    async def verify(self, ctx, user: discord.Member, tag: str):
        await ctx.trigger_typing()
        clean_tag = tag.upper().strip('#').replace('O', '0')
        verification_message = await ctx.send(embed=in_progress(
            tag=clean_tag,
            desc=f'{self.loading_emj} Validating your tag #{clean_tag}...'))
        try:
            player = await self.bs_client.get_player(clean_tag)
        except brawlstats.NotFoundError:
            await asyncio.sleep(1)
            await verification_message.edit(
                embed=failed(f'{self.failed_emj} Invalid tag.'))
            return
        else:
            self.tag_dict['_id'] = clean_tag
            # post = {'_id': user.id, "player_tag": clean_tag}
            self.client.bs_data.update_one({"_id": user.id},
                                           {"$set": {
                                               "player_tag": clean_tag
                                           }},
                                           upsert=True)
            await asyncio.sleep(1)
            await verification_message.edit(embed=in_progress(
                tag=clean_tag,
                desc=f'{self.success_emj} Tag verified successfully.\n'
                f'Player Name: {player.name}\n'
                f'{self.loading_emj} Checking Club...'))
        club = await player.get_club()
        if club is None:
            await asyncio.sleep(1)
            await verification_message.edit(embed=success(
                tag=clean_tag,
                desc=f'{self.success_emj} Tag verified successfully.\n'
                f'Player Name: {player.name}\n'
                f"{self.failed_emj} Player isn't in any club. Can't assign club roles.",
                ctx=ctx))
            return
        clean_club_tag = club.tag.upper().strip('#')
        if clean_club_tag in self.club_role_dict.keys():
            await asyncio.sleep(1)
            await verification_message.edit(embed=success(
                tag=clean_tag,
                desc=f'{self.success_emj} Tag verified successfully.\n'
                f'Player Name: {player.name}\n'
                f"{self.success_emj} Club found: {club.name} (`#{clean_club_tag}`)\n"
                f"{self.loading_emj} Assigning club roles...",
                ctx=ctx))

            # adding basic club roles.
            club_role_id = int(self.club_role_dict[clean_club_tag]['role_id'])
            await user.add_roles(ctx.guild.get_role(club_role_id))
            await user.add_roles(ctx.guild.get_role(self.basic_club_role))
            await user.add_roles(ctx.guild.get_role(self.family_role))

            # finding Position in club
            club_members = await club.get_members()
            for i in range(len(club_members)):
                if club_members[i].tag == player.tag:
                    position_role_id = self.position_role_dict[
                        club_members[i].role.lower()]
                    await user.add_roles(ctx.guild.get_role(position_role_id))
                    await asyncio.sleep(1)  # give role acc. to position.
                    await verification_message.edit(embed=success(
                        tag=clean_tag,
                        desc=f'{self.success_emj} Tag verified successfully.\n'
                        f'Player Name: {player.name}\n'
                        f"{self.success_emj} Club found: {club.name} (`#{clean_club_tag}`)\n"
                        f"{self.success_emj} Assigned <@&{position_role_id}> role for <@&{club_role_id}> club.\n"
                        f"{user.mention} can react on {self.success_emj} to set their nickname according to club.",
                        ctx=ctx))
                    await verification_message.add_reaction(self.success_emj)

                    def check(reaction, user_):
                        return user_ == user and str(
                            reaction.emoji) == self.success_emj

                    try:
                        _, user__ = await self.client.wait_for('reaction_add',
                                                               check=check,
                                                               timeout=15.0)
                    except asyncio.TimeoutError:
                        await verification_message.edit(embed=success(
                            tag=clean_tag,
                            desc=
                            f'{self.success_emj} Tag verified successfully.\n'
                            f'Player Name: {player.name}\n'
                            f"{self.success_emj} Club found: {club.name} (`#{clean_club_tag}`)\n"
                            f"{self.success_emj} Assigned <@&{position_role_id}> role for <@&{club_role_id}> club.",
                            ctx=ctx))
                        await verification_message.clear_reactions()
                    else:
                        await user__.edit(nick=f"{player.name} | {club.name}")
                    break

        else:
            await asyncio.sleep(1)
            await verification_message.edit(embed=success(
                tag=clean_tag,
                desc=f'{self.success_emj} Tag verified successfully.\n'
                f'Player Name: {player.name}\n'
                f"{self.success_emj} Club found: {club.name} (`#{clean_club_tag}`)\n"
                f"{self.failed_emj} Player isn't in any of our clubs. Can't assign club roles.",
                ctx=ctx))

    @commands.command()
    @commands.has_permissions(administrator=True)
    async def addclubrole(self, ctx, tag, role: discord.Role):
        clean_tag = tag.upper().strip('#').replace('O', '0')
        try:
            club = await self.bs_client.get_club(clean_tag)
        except brawlstats.NotFoundError:
            await ctx.send("Invalid Club Tag.")
            return
        # post = {'_id': role.id, 'club_tag': clean_tag, "club_name": club.name}
        self.client.club_roles_data.update_one({'_id': role.id}, {
            "$set": {
                '_id': role.id,
                'club_tag': clean_tag,
                'club_name': club.name
            }
        },
                                               upsert=True)
        self.client.reload_extension('cogs.brawlstars')
        await ctx.send(embed=discord.Embed(
            title='New club role added.',
            description=
            f"{club.name} #(`{clean_tag}`) has been assigned to {role.mention}",
            colour=discord.Colour.green(),
            timestamp=datetime.datetime.now(pytz.timezone('Asia/Kolkata'))))

    @commands.command()
    @commands.check_any(commands.has_permissions(administrator=True),
                        commands.has_any_role('Moderator'))
    async def listclubroles(self, ctx):
        await ctx.trigger_typing()
        msg = await ctx.send(embed=discord.Embed(
            description=f'{self.loading_emj} Getting Data...\n'
            f'Wait few moments.',
            colour=ctx.author.color))
        desc = ''

        for i in self.club_role_dict.keys():
            desc += f'**{self.club_role_dict[i]["club_name"]} (`#{i}`) => <@&{self.club_role_dict[i]["role_id"]}>**\n'
        embed = discord.Embed(title='List of Clubs and roles.',
                              description=desc,
                              colour=ctx.author.color)
        await asyncio.sleep(1)
        await msg.edit(embed=embed)

    @commands.command()
    @commands.has_permissions(administrator=True)
    async def listplayers(self, ctx):
        pass
Exemplo n.º 7
0
def has_admin_permissions():
    return commands.has_permissions(administrator=True)
Exemplo n.º 8
0
client = commands.Bot(command_prefix='.')
client.remove_command('help')


@client.event
async def on_ready():
    print('Bot is ready!')
    await client.change_presence(
        activity=discord.Activity(name=f'{client.command_prefix}help',
                                  type=discord.ActivityType.watching))


@client.command()
@commands.check_any(commands.is_owner(),
                    commands.has_permissions(administrator=True))
async def load(ctx, extension):
    try:
        client.load_extension(f'cogs.{extension}')
        await ctx.send(f'Loaded extension {extension}.')
    except commands.errors.ExtensionNotFound:
        await ctx.send(f'Extension {extension} does not exist!')
    except commands.errors.ExtensionAlreadyLoaded:
        await ctx.send(f'Extension {extension} already loaded!')


@client.command()
@commands.check_any(commands.is_owner(),
                    commands.has_permissions(administrator=True))
async def unload(ctx, extension):
    try:
Exemplo n.º 9
0
        rank = page + 1
        for i in query:
            user = await bot.fetch_user(i[0])
            if user:
                string += f'[{rank}.] {user.name}: level {i[1]}.\n'
            else:
                string += f'[{rank}.] User left server: level {i[1]}.\n'
            rank += 1
        await ctx.send(f'```ini\n{string}```')
    else:
        await ctx.send('No entries on this page!')


@bot.command(brief='Admin-only.',
             description='Add or remove points from user if necessary.')
@commands.check_any(commands.has_permissions(administrator=True),
                    commands.is_owner())
async def modify(ctx, user: discord.Member, modifier: int = 1):
    c.execute('''SELECT * FROM users WHERE user_id = ?''', (user.id, ))
    query = c.fetchone()
    if query:
        c.execute('''UPDATE users SET score = score + ? WHERE user_id = ?''', (
            modifier,
            user.id,
        ))
        await ctx.send(user.display_name + " modified.")
    else:
        await ctx.send('User not found (or hasn\'t contributed).')
    db.commit()

Exemplo n.º 10
0
class Administration(commands.Cog):
    """A category for administrative commands."""
    def __init__(self, bot: commands.Bot):
        self.bot = bot

    @commands.check_any(commands.has_permissions(administrator=True),
                        commands.is_owner())
    @group(name="prefix", invoke_without_command=True, case_insensitive=True)
    @example("""
    <prefix>prefix !
    <prefix>prefix change !
    <prefix>prefix insensitive true
    """)
    async def _prefix(self, ctx: commands.Context, prefix: str = None):
        """A group of commands for managing your guild's prefix.

        If no subcommand is invoked and you passed in a prefix then the prefix will be changed
        to that prefix. So `<prefix>prefix "bot "` would be the same as `<prefix>prefix change "bot "`"""
        if prefix is not None:
            return await self._change(ctx, prefix)
        await ctx.send_help(ctx.command)

    @_prefix.command(name="change")
    @example("""
    <prefix>prefix change !
    """)
    async def _change(self, ctx: commands.Context, prefix: str):
        """Changes the prefix for your server.

        NOTE: If you want to have spaces in your prefix, use quotes around the prefix
        Example: `{prefix}prefix change "bot "`
        """
        if len(prefix) > 10:
            return await ctx.send("Your prefix can't be that long!")

        elif len(prefix) == 0:
            return await ctx.send("Your prefix cannot be nothing.")

        async with self.bot.db.acquire() as connection:
            guild = await connection.fetchrow(
                "SELECT * FROM guilds WHERE guild_id = $1", ctx.guild.id)
            if guild:
                await connection.execute(
                    "UPDATE guilds SET prefix = $1 WHERE guild_id = $2",
                    prefix,
                    ctx.guild.id,
                )
            else:
                await connection.execute(
                    "INSERT INTO guilds (guild_id, prefix) VALUES ($1, $2)",
                    ctx.guild.id,
                    prefix,
                )
            self.bot.dispatch('prefix_change')
        embed = discord.Embed(
            title=f"Set prefix to: {prefix}",
            colour=discord.Colour.green(),
            timestamp=datetime.utcnow(),
        )
        embed.set_footer(text=f"Requested by {ctx.author}",
                         icon_url=ctx.author.avatar_url)
        await ctx.send(embed=embed)

    @_prefix.command(name="insensitive",
                     aliases=("case_insensitive", "caseinsensitive"))
    @example("""
    <prefix>prefix insensitive on
    <prefix>prefix case_insensitive disable
    """)
    async def _insensitive_prefix(self, ctx: commands.Context,
                                  true_or_false: bool):
        """Sets your prefix to case insensitive if you sent True and case sensitive if set to False.

        Prefixes are case sensitive by default."""
        async with self.bot.db.acquire() as connection:
            guild = await connection.fetchrow(
                "SELECT * FROM guilds WHERE guild_id = $1", ctx.guild.id)
            if guild is not None and guild["prefix"] is not None:
                await connection.execute(
                    "UPDATE guilds SET insensitive = $1 WHERE guild_id = $2",
                    true_or_false,
                    ctx.guild.id,
                )
            else:
                return await ctx.send("You didn't set your prefix yet!")
        embed = discord.Embed(
            title=f"Set prefix to case {'in' * int(true_or_false)}sensitive",
            colour=discord.Colour.green(),
            timestamp=datetime.utcnow(),
        )
        embed.set_footer(text=f"Requested by {ctx.author}",
                         icon_url=ctx.author.avatar_url)
        await ctx.send(embed=embed)

    @commands.has_permissions(manage_channels=True)
    @command(name="slow_mode", aliases=("slowmode", "sm"))
    @example("""
    <prefix>slowmode 10
    <prefix>sm 0
    """)
    async def slow_mode(self, ctx: commands.Context,
                        channel: t.Optional[discord.TextChannel], time: int):
        """Changes the slowmode delay for the channel you specify, if channel isn't sepicified it will be the channel you invoked the command.

        You can also set it to 0 to reset the slowmode delay."""
        channel = channel or ctx.channel
        if time < 0:
            return await ctx.send("You can't have a negative slowmode delay!")
        await channel.edit(slowmode_delay=time)
        if time == 0:
            embed = discord.Embed(
                title="Channel slowmode delay has been reset!",
                colour=discord.Colour.green(),
                timestamp=datetime.utcnow(),
            )
        else:
            s = "" if time == 1 else "s"
            embed = discord.Embed(
                title=
                f"Channel slowmode delay has been set to {time} second{s}!",
                colour=discord.Colour.green(),
                timestamp=datetime.utcnow(),
            )
        embed.set_footer(text=f"Requested by {ctx.author}",
                         icon_url=ctx.author.avatar_url)
        await ctx.send(embed=embed)

    @commands.check_any(commands.has_permissions(administrator=True),
                        commands.is_owner())
    @command(name="levelup_messages",
             aliases=("level_messages", "levelmessages"))
    async def _level_up_messages(self, ctx: commands.Context,
                                 true_or_false: bool):
        """Enable or disable the messages that are set when a user levels up.

        You can give 'yes', 'y', 'true', 't', '1', 'enable', 'on' if you want it on,
        or 'no', 'n', 'false', 'f', '0', 'disable', 'off' if you want it off. Casing does not matter."""
        async with self.bot.db.acquire() as connection:
            guild = await connection.fetchrow(
                "SELECT * FROM guilds WHERE guild_id = $1", ctx.guild.id)
            if not guild:
                await connection.execute(
                    "INSERT INTO guilds (guild_id, level_up_messages) VALUES ($1, $2)",
                    ctx.guild.id,
                    true_or_false,
                )
            else:
                await connection.execute(
                    "UPDATE guilds SET level_up_messages = $1 WHERE guild_id = $2",
                    true_or_false,
                    guild["guild_id"],
                )
        embed = discord.Embed(
            description=
            f"**✅ Set level up messages to {'on' if true_or_false else 'off'}**"
        )
        embed.set_footer(text=f"Requested by {ctx.author}",
                         icon_url=ctx.author.avatar_url)
        await ctx.send(embed=embed)
Exemplo n.º 11
0
import typing as t
import textwrap

import discord
from discord.ext import commands
from loguru import logger

from src.bot import Bot

DATA_FORMAT = "%d/%m/%y - %X"

is_mod = commands.has_permissions(kick_members=True, ban_members=True)


class ModCog(commands.Cog, name="moderation"):  # type: ignore
    """
    Do mod stuff like ban and kick.
    """
    def __init__(self, bot: Bot) -> None:
        super().__init__()
        self.bot = bot

    async def check_role_order(self, activator: discord.Member,
                               target: discord.Member) -> None:
        activator_role = activator.roles[-1]
        target_role = target.roles[-1]

        if activator_role <= target_role:
            raise commands.CheckFailure(
                "you may not use this command on a user with a higher or same role as you"
            )
Exemplo n.º 12
0
class AdminCmds(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

        self.db = self.bot.get_cog("Database")

    @commands.command(name="purge", aliases=["p"])
    @commands.has_permissions(manage_messages=True)
    @commands.guild_only()
    async def purge_messages(self, ctx, n: int):
        if n <= 9999:
            try:
                await ctx.channel.purge(limit=n + 1)
            except Exception:
                error_embed = discord.Embed(
                    color=discord.Color.green(),
                    description=
                    '''Uh oh, Villager Bot had a problem deleting those messages, try again later!'''
                )
                await ctx.send(embed=error_embed)
        else:
            limit_embed = discord.Embed(
                color=discord.Color.green(),
                description=
                '''You cannot purge more than 9999 messages at one time!''')
            await ctx.send(embed=limit_embed)

    @commands.command(name="ban")
    @commands.guild_only()
    @commands.has_permissions(ban_members=True)
    async def ban_user(self,
                       ctx,
                       user: discord.User,
                       *,
                       reason="No reason provided."):
        if ctx.author.id == user.id:
            await ctx.send(
                embed=discord.Embed(color=discord.Color.green(),
                                    description="You cannot ban yourself."))
            return
        for entry in await ctx.guild.bans():
            if entry[1].id == user.id:
                already_banned_embed = discord.Embed(
                    color=discord.Color.green(),
                    description="User has been already banned!")
                await ctx.send(embed=already_banned_embed)
                return

        await ctx.guild.ban(user, reason=reason)
        banned_embed = discord.Embed(
            color=discord.Color.green(),
            description=f"Successfully banned **{str(user)}**.")
        await ctx.send(embed=banned_embed)

    @commands.command(name="pardon")
    @commands.guild_only()
    @commands.has_permissions(ban_members=True)
    async def pardon_user(self,
                          ctx,
                          user: discord.User,
                          *,
                          reason="No reason provided."):
        if ctx.author.id == user.id:
            await ctx.send(
                embed=discord.Embed(color=discord.Color.green(),
                                    description="You cannot unban yourself."))
            return
        for entry in await ctx.guild.bans():
            if entry[1].id == user.id:
                await ctx.guild.unban(user, reason=reason)
                unban_embed = discord.Embed(
                    color=discord.Color.green(),
                    description=f"Successfully unbanned **{str(user)}**.")
                await ctx.send(embed=unban_embed)
                return

        not_banned_embed = discord.Embed(
            color=discord.Color.green(),
            description="Mentioned user had not been banned before!")
        await ctx.send(embed=not_banned_embed)

    @commands.command(name="kick")
    @commands.guild_only()
    @commands.has_permissions(kick_members=True)
    async def kick_user(self,
                        ctx,
                        user: discord.User,
                        *,
                        reason="No reason provided."):
        if ctx.author.id == user.id:
            await ctx.send(
                embed=discord.Embed(color=discord.Color.green(),
                                    description="You cannot kick yourself."))
            return
        await ctx.guild.kick(user, reason=reason)
        kick_embed = discord.Embed(
            color=discord.Color.green(),
            description=f"Successfully kicked **{str(user)}**.")
        await ctx.send(embed=kick_embed)

    @commands.command(name="warn", aliases=["warnuser"])
    @commands.guild_only()
    @commands.check_any(commands.has_permissions(administrator=True),
                        commands.has_permissions(kick_members=True),
                        commands.has_permissions(ban_members=True))
    async def warn(self,
                   ctx,
                   user: discord.User,
                   *,
                   reason="No reason provided"):
        if ctx.author.id == user.id:
            await ctx.send(
                embed=discord.Embed(color=discord.Color.green(),
                                    description="You cannot warn yourself."))
            return
        reason = (reason[:125] + "...") if len(reason) > 128 else reason
        await self.db.add_warn(user.id, ctx.author.id, ctx.guild.id, reason)
        await ctx.send(embed=discord.Embed(
            color=discord.Color.green(),
            description=
            f"**{user}** was warned by **{ctx.author}** for reason: *{reason}*"
        ))

    @commands.command(name="warns",
                      aliases=["getwarns", "getuserwarns", "warnings"])
    @commands.guild_only()
    @commands.check_any(commands.has_permissions(administrator=True),
                        commands.has_permissions(kick_members=True),
                        commands.has_permissions(ban_members=True))
    async def get_user_warns(self, ctx, user: discord.User):
        user_warns = await self.db.get_warns(user.id, ctx.guild.id)
        embed = discord.Embed(
            color=discord.Color.green(),
            title=f"**{user}**'s Warnings ({len(user_warns)} total):")
        if len(user_warns) == 0:
            await ctx.send(embed=discord.Embed(
                color=discord.Color.green(),
                title=f"**{user}**'s Warnings ({len(user_warns)} total):",
                description=f"**{user}** has no warnings in this server."))
            return
        for warning in user_warns:
            embed.add_field(
                name=f"Warning by **{self.bot.get_user(warning[1])}**:",
                value=warning[3],
                inline=False)
        await ctx.send(embed=embed)

    @commands.command(name="clearwarns",
                      aliases=["deletewarns", "removewarns"])
    @commands.guild_only()
    @commands.check_any(commands.has_permissions(administrator=True),
                        commands.has_permissions(kick_members=True),
                        commands.has_permissions(ban_members=True))
    async def clear_user_warns(self, ctx, user: discord.User):
        user_warns = await self.db.get_warns(user.id, ctx.guild.id)
        if len(user_warns) == 0:
            await ctx.send(
                embed=discord.Embed(color=discord.Color.green(),
                                    description=f"**{user}** has no warns."))
        else:
            await self.db.clear_warns(user.id, ctx.guild.id)
            await ctx.send(embed=discord.Embed(
                color=discord.Color.green(),
                description=f"Cleared all of **{user}**'s warns."))
Exemplo n.º 13
0
class general(commands.Cog):
    """your general every-day commands"""
    def __init__(self, bot):
        self.bot = bot

    ##### .s <text> #####
    # resends the message as the bot

    @commands.command(
        aliases=['s', 'send'],
        usage="<text>",
        help="Speak as if you were me. # URLs/Invites not allowed!")
    async def say(self, ctx, *, msg: typing.Optional[str]):
        if msg == None:
            await ctx.send(
                f"Error! empty. do: `{ctx.prefix}{ctx.command} <text>`")

        results = re.findall(
            "http[s]?:\/\/(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*(),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+",
            msg)  # HTTP/HTTPS URL regex
        results2 = re.findall(
            "(?:https?:\/\/)?discord(?:app)?\.(?:com\/invite|gg)\/[a-zA-Z0-9]+\/?",
            msg)  # Discord invite regex
        if results or results2:
            await ctx.send(
                f"`{ctx.prefix}{ctx.command}` can't be used to send invites or URLs, as it could bypass spam filters!",
                delete_after=5)
            try:
                await ctx.message.delete(delay=5)
            except:
                return
            return

        try:
            await ctx.message.delete()
        except:
            pass
        if ctx.channel.permissions_for(ctx.author).mention_everyone:
            if ctx.message.reference:
                reply = ctx.message.reference.resolved
                await reply.reply(msg)
            else:
                await ctx.send(msg)
        else:
            if ctx.message.reference:
                reply = ctx.message.reference.resolved
                await reply.reply(
                    msg,
                    allowed_mentions=discord.AllowedMentions(everyone=False))
            else:
                await ctx.send(
                    msg,
                    allowed_mentions=discord.AllowedMentions(everyone=False))

    ##### .a <TextChannel> <text> ######
    #sends the message in a channel

    @commands.command(help="Echoes a message to another channel",
                      aliases=['a', 'an', 'announce'],
                      usage="<channel> <message>")
    @commands.check_any(commands.has_permissions(manage_messages=True),
                        commands.is_owner())
    async def echo(self,
                   ctx,
                   channel: typing.Optional[discord.TextChannel] = None,
                   *,
                   msg: typing.Optional[str]):
        if channel == None:
            await ctx.send(f"""You must specify a channel
`{ctx.prefix}{ctx.command}{ctx.usage} [#channel] [message]`""")
            return
        if msg == None:
            await ctx.send(f"""You must type a message.
`{ctx.prefix}{ctx.command} [#channel] [message]`""")
            return
        if channel.permissions_for(ctx.author).mention_everyone:
            if ctx.message.reference:
                msg = ctx.message.reference.resolved.content
            await channel.send(msg)

        else:
            if ctx.message.reference:
                msg = ctx.message.reference.resolved.content
            await channel.send(
                msg, allowed_mentions=discord.AllowedMentions(everyone=False))

    @commands.command(
        aliases=['e'],
        usage="-reply- [new message] [--d|--s]",
        help=
        "Quote a bot message to edit it. # Append --s at the end to supress embeds and --d to delete the message"
    )
    @commands.check_any(commands.has_permissions(manage_messages=True),
                        commands.is_owner())
    async def edit(self, ctx, *, new_message: typing.Optional[str] = '--d'):
        new = new_message
        if ctx.message.reference:
            msg = ctx.message.reference.resolved
            try:
                if new.endswith("--s"):
                    await msg.edit(content=f"{new[:-3]}", suppress=True)
                elif new.endswith('--d'):
                    await msg.delete()
                else:
                    await msg.edit(content=new, suppress=False)
                try:
                    await ctx.message.delete()
                except discord.Forbidden:
                    return
            except:
                pass
        else:
            await ctx.message.add_reaction('⚠')
            await asyncio.sleep(3)
            try:
                await ctx.message.delete()
            except discord.Forbidden:
                return

    #### .jumbo <Emoji> ####
    # makes emoji go big

    @commands.command(aliases=['jumbo', 'bigemoji', 'emojinfo'],
                      help="Makes an emoji bigger and shows it's formatting",
                      usage="<emoji>")
    async def emoji(self, ctx, emoji: typing.Optional[discord.PartialEmoji]):
        if emoji == None:
            await ctx.send(embed=discord.Embed(
                description="Please specify a valid Custom Emoji",
                color=ctx.me.color))
        else:
            if emoji.animated:
                emojiformat = f"*`<`*`a:{emoji.name}:{emoji.id}>`"
            else:
                emojiformat = f"*`<`*`:{emoji.name}:{emoji.id}>`"
            embed = discord.Embed(description=f"{emojiformat}",
                                  color=ctx.me.color)
            embed.set_image(url=emoji.url)
            await ctx.send(embed=embed)

    #### .uuid <mcname> ####
    # gets user's UUID (minecraft)

    @commands.command(help="Fetches the UUID of a minecraft user",
                      usage="<Minecraft username>")
    async def uuid(self, ctx, *, argument: typing.Optional[str] = None):
        if argument == None:
            embed = discord.Embed(
                description="please specify a Minecraft Username to look up",
                color=ctx.me.color)
            await ctx.send(embed=embed)
            return
        async with aiohttp.ClientSession() as cs:
            async with cs.get(
                    f"https://api.mojang.com/users/profiles/minecraft/{argument}"
            ) as cs:
                embed = discord.Embed(color=ctx.me.color)
                if cs.status == 204:
                    embed.add_field(
                        name='⚠ ERROR ⚠',
                        value=f"`{argument}` is not a minecraft username!")

                elif cs.status == 400:
                    embed.add_field(name="⛔ ERROR ⛔",
                                    value="ERROR 400! Bad request.")
                else:
                    res = await cs.json()
                    user = res["name"]
                    uuid = res["id"]
                    embed.add_field(name=f'Minecraft username: `{user}`',
                                    value=f"**UUID:** `{uuid}`")
                await ctx.send(embed=embed)