Beispiel #1
0
class Utilities(commands.Cog):
    def __init__(self, client):
        self.client = client
        print("Utilities Loaded")

    @commands.command()
    @commands.check_any(commands.has_permissions(administrator=True),
                        commands.has_role('Moderator'))
    async def lock(self, ctx):
        pass

    @commands.command()
    @commands.check_any(commands.has_permissions(administrator=True),
                        commands.has_role('Moderator'))
    async def unlock(self, ctx):
        pass

    @commands.command()
    @commands.check_any(commands.is_owner(),
                        commands.has_permissions(administrator=True))
    async def echo(self,
                   ctx,
                   channel: typing.Optional[discord.TextChannel] = None,
                   *,
                   message):
        channel = ctx.channel if not channel else channel
        files = [
            await attachment.to_file()
            for attachment in ctx.message.attachments
        ] if ctx.message.attachments != [] else None
        await channel.send(message, files=files)

    @commands.command()
    @commands.has_permissions(administrator=True)
    async def dm(self, ctx, user: discord.Member, *, message):
        files = [
            await attachment.to_file()
            for attachment in ctx.message.attachments
        ] if ctx.message.attachments != [] else None
        await user.send(message, files=files)

    @commands.command(aliases=['sm', 'slowmode'])
    @commands.check_any(commands.has_permissions(administrator=True),
                        commands.has_role('Moderator'))
    async def slowmo(self,
                     ctx,
                     channel: typing.Optional[discord.TextChannel] = None,
                     *,
                     seconds: int):
        await channel.edit(slowmode_delay=seconds)
        if seconds == 0:
            await ctx.send(f"Slowmode disabled for {channel.mention}")
        else:
            await ctx.send(
                f"Channel {channel.mention} slowmode set to {seconds} seconds."
            )
 def _set_gm_role_id(self, val):
     self.__gm_role_id = val
     self.add.add_check(
         commands.check_any(commands.has_role(self.gm_role_id),
                            commands.has_permissions(administrator=True)))
     self.kick.add_check(
         commands.check_any(commands.has_role(self.gm_role_id),
                            commands.has_permissions(administrator=True)))
     self.add_gm.add_check(
         commands.check_any(commands.has_role(self.gm_role_id),
                            commands.has_permissions(administrator=True)))
     self.resign_gm.add_check(commands.has_role(self.gm_role_id))
Beispiel #3
0
class Roles(commands.Cog):
    def __init__(self, Bot: commands.Bot) -> None:
        self.Bot = Bot
        self.R_verified = Bot.guilds[0].get_role(int(
            conf["Roles"]["verified"]))
        self.R_unverified = Bot.guilds[0].get_role(
            int(conf["Roles"]["unverified"]))

    @commands.group(name="roles", aliases=["role", "r"])
    async def roles(self, context: commands.Context):
        pass

    @roles.command(name="verify", aliases=["v"])
    @commands.check_any(
        commands.has_role(R_manage_member_roles),
        commands.has_permissions(manage_roles=True),
    )
    async def verify(self, context: commands.Context,
                     members: commands.Greedy[discord.Member]) -> None:
        """
        Shortcut for giving the verification role.
        """
        for member in members:
            await member.add_roles(self.R_verified,
                                   reason=f"Added by {context.author}")
            await member.remove_roles(self.R_unverified,
                                      reason=f"Removed by {context.author}")

        await context.send("Ok.")

    @roles.command(name="give", aliases=["g", "add"])
    async def give(self, context: commands.Context,
                   members: commands.Greedy[discord.Member]) -> None:
        pass
Beispiel #4
0
 async def cog_check(self, context: commands.Context) -> bool:
     """
     Only bot owner and people with bot ctrl role can do this.
     """
     return await commands.check_any(
         commands.is_owner(),
         commands.has_role(int(
             conf["Roles"]["bot ctrl"]))).predicate(context)
Beispiel #5
0
 def predicate(ctx):
     roleList = ((ExtFuncs.readVars(
         ctx.guild.id)).get('Roles')).get(roleObj)
     for role in roleList:
         if commands.has_role(role):
             return True
         elif ctx.author == ctx.guild.owner:
             return True
         else:
             continue
     return False
Beispiel #6
0
    async def predicate(ctx: commands.Context):
        """Returns true if is me or has admin role

        **Arguments**

        - `<ctx>` Context to check.

        """

        return ctx.author.id == 126913881879740416 or commands.has_role(
            'Admin')
Beispiel #7
0
def is_owner_or_admin_role(**perms):
    role = settings.bot_admin_role
    original = commands.has_role(role).predicate

    async def extended_check(ctx):
        if ctx.guild is None:
            return False

        return ctx.guild.owner_id == ctx.author.id or await original(ctx)

    return commands.check(extended_check)
Beispiel #8
0
class cog_commands(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.command(name="load_cog")
    @commands.check(commands.has_role("Admin"))
    async def load_cog(self, ctx, arg1):
        self.bot.load_extension(f"cogs.{arg1}")
        await ctx.send(f"Loaded {arg1}.")

    @commands.command(name="unload_cog")
    @commands.check(commands.has_role("Admin"))
    async def unload_cog(self, ctx, arg1):
        self.bot.unload_extension(f"cogs.{arg1}")
        await ctx.send(f"Unloaded {arg1}.")

    @commands.command(name="reload_cog")
    @commands.check(commands.has_role("Admin"))
    async def reload_cog(self, ctx, arg1):
        self.bot.unload_extension(f"cogs.{arg1}")
        self.bot.load_extension(f"cogs.{arg1}")
        await ctx.send(f"Reloaded {arg1}.")
class admin_cmds(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.command(name="msgc")
    @commands.check(commands.has_role("Admin"))
    async def message_channel(self, ctx, arg1, arg2):

        channel_id = await self.get_channel(self, arg1)
        channel = discord.utils.get(ctx.guild.channels, id=channel_id)

        print(f"msgc to {channel}")

        await channel.send(arg2)

    @commands.command(name="react")
    @commands.check(commands.has_role("Admin"))
    async def react_message(self, ctx, arg1, arg2, arg3):
        #arg1 = channel_id arg2 = msg_id arg3 = reaction

        channel_id = await self.get_channel(self, arg1)
        channel = discord.utils.get(ctx.guild.channels, id=channel_id)
        message = await channel.fetch_message(int(arg2))

        print("react")

        await message.add_reaction(arg3)

    async def get_channel(self, ctx, channel_id):
        channel = 0
        if channel_id in self.bot.text_channels:
            channel = self.bot.text_channels[channel_id]
        #elif int(channel_id) in self.bot.text_channels.values():
        #channel = int(channel_id)
        else:
            channel = int(channel_id)

        return channel
Beispiel #10
0
class Troll(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.count = 0

    @commands.command(help_command="!ansh",
                      description="hehehe",
                      help="hehehe")
    @commands.cooldown(1, 600, commands.BucketType.user)
    @commands.check_any(commands.has_role("Organizer"))
    async def ansh(self, ctx):
        ansh = self.bot.get_user(520856194190147595)
        # ansh = self.bot.get_user(173263365777522688)
        dm = await ansh.create_dm()
        await dm.send("Get anshed hehehehehehe")
        self.count += 1
        await ctx.send("Ansh has been disturbed %d times" % self.count)
Beispiel #11
0
class Trivia(commands.Cog):
    """Trivia questions."""
    def __init__(self, bot: Bot):
        self.bot = bot

    @commands.group(name="trivia", invoke_without_command=True)
    @commands.cooldown(rate=1, per=60, type=commands.BucketType.member)
    @in_channel(int(getenv("CHANNEL")))
    async def trivia(self, ctx: Context, unique: bool = False):
        """Get a trivia question."""

        pass

    @trivia.command(name="add")
    @commands.check_any(commands.is_owner(),
                        commands.has_role(337442104026595329))
    async def trivia_add(self, ctx: Context, *, question: str):
        """Add a new trivia question."""

        await ctx.reply("Enter valid answers, and .stop to finish.")

        answers = []

        while True:
            try:
                msg = await self.bot.wait_for(
                    "message",
                    check=lambda m: m.channel == ctx.channel and m.author ==
                    ctx.author,
                    timeout=15)
            except:
                return await ctx.reply("Selection timed out, exiting.")
            answer = msg.content

            if answer == ".stop":
                break
            else:
                answers.append(answer)

        answers = "`".join(answers)

        await self.bot.db.create_trivia_question(ctx.author.id, question,
                                                 answers)
Beispiel #12
0
class Extra(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.Cog.listener()
    async def on_command_error(self, ctx, error):
        return

    @commands.command(name='members',
                      description='Tells you total server member.',
                      aliases=['mbs'])
    @commands.guild_only()
    @commands.check_any(commands.has_permissions(manage_guild=True),
                        commands.has_role(782638194217844770))
    async def members(self, ctx):
        embed = discord.Embed(color=0x00FFFF)
        embed.title = "Total Members"
        embed.description = ctx.guild.member_count
        await ctx.send(embed=embed)
Beispiel #13
0
 async def reset(self, ctx):
     if ctx.message.author.guild_permissions >= discord.Permissions(
             manage_guild=True) or commands.has_role(
                 os.environ.get('MANAGER_ROLE_ID')):
         if ctx.message.author.voice is not None:
             await ctx.message.author.voice.channel.edit(
                 name='game-chat',
                 reason=f'{ctx.message.author} reset the room name.')
             await ctx.channel.edit(
                 topic='No game in progress.',
                 reason=f'{ctx.message.author} ended the game.')
             await ctx.send(
                 f'I have changed the name of your voice channel to `game-chat` and the channel topic to `No game in progress.`'
             )
         else:
             await ctx.send(
                 'You need to be in a voice channel to use this command.')
     else:
         await ctx.send(
             f'You dont have the neccessary permissions to run this command. (You will need either MANAGE_GUILD permissions or the manager role to be able to use this command)'
         )
class Admin(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.check_any(commands.is_owner(), commands.has_role('Admin'))
    @commands.command(name='purge',
                      brief='Purges [X] amount of messages from the chat')
    async def purge(self, ctx, amount=0):
        await ctx.channel.purge(limit=amount + 1)

    @commands.check_any(commands.is_owner())
    @commands.command(name='prune',
                      brief='Purges inactive members from the Discord server')
    async def prune(self, ctx):
        prune_count = await ctx.guild.prune_members(
            days=30,
            compute_prune_count=True,
            roles=ctx.guild.roles or None,
            reason='Pruned for inactivity')
        await ctx.send(
            f'Pruned {prune_count} inactive members from the server.')
Beispiel #15
0
class Inquisition(commands.Cog):
    """Runs the Inquisition channel."""
    def __init__(self, bot, channel_id):
        self.bot = bot
        self.channel = bot.get_channel(channel_id)
        self.info_suffix = "Use the '!inquisition question' (!inq q <question>) command to ask a question."

    @commands.command(aliases=["q"])
    @commands.guild_only()
    async def question(self, ctx, *, question_text):
        """Ask a question in the Inquisition Channel."""
        if ctx.channel != self.channel:
            await ctx.channel.send("This is not the Inquisition channel.")
            return
        message = await ctx.channel.send(embed=Embed(
            title="{} asked a question:".format(ctx.author.display_name),
            description=question_text,
            color=ctx.bot.colors['default']))
        await message.pin()
        await ctx.channel.edit(
            topic="{} - {}".format(question_text, self.info_suffix))

    @commands.command(hidden=True)
    @commands.guild_only()
    @commands.check_any(commands.is_owner(), commands.has_role('Operator'))
    # TODO: Check for any role in config.json
    async def inqsetup(self, ctx):
        """Set the Inquisition Channel"""
        if ctx.channel.type != ChannelType.text:
            await ctx.channel.send(
                embed=ctx.bot.error_embed("Not available here."))
            return
        self.channel = ctx.channel
        with open(config_file, 'w') as file:
            file.write(str(self.channel.id))
        await ctx.channel.send(
            embed=Embed(title="Inquisition",
                        description="Let the Inquisition begin! {}".format(
                            self.info_suffix),
                        color=ctx.bot.colors['confirm']))
Beispiel #16
0
def is_owner():
    return commands.has_role('administrator')
Beispiel #17
0
class Quote(commands.Cog):

    star_reactions = ['тнР', 'ЁЯМЯ']

    def __init__(self, bot: NRus):
        self.bot = bot
        self.delete_queue = {}

    def cog_check(self, ctx):
        return bool(ctx.guild)

    @commands.Cog.listener('on_raw_reaction_add')
    async def on_raw_reaction_add(self,
                                  payload: discord.RawReactionActionEvent):
        if payload.emoji.name in self.star_reactions:
            channel = self.bot.get_channel(payload.channel_id)
            message = await channel.fetch_message(payload.message_id)
            if message.author.id == self.bot.user.id:
                return
            star_count = 0
            for reaction in message.reactions:
                if reaction.emoji in self.star_reactions:
                    star_count += reaction.count
            if star_count == 1:
                await self.quote_from_message(message, payload.user_id)

    @commands.group(
        aliases=['q'],
        invoke_without_command=True,
        usage=
        '<quote> <author> [authors ...] or <quote> - <author> [authors ...]',
        help=
        "- On its own, an alias for `quote add` -- Try `help quote`.\n\nMost commands use 1+ authors"
    )
    async def quote(self, ctx: commands.Context, *, text) -> None:
        author_ids, quote_text = self.get_authors(text.strip())
        quote_text = quote_text.rstrip('-').rstrip(
        )  # Strip whitespace and '-' characters from the end of quote_text
        if author_ids is None:
            await ctx.send(
                f'{ctx.message.author.mention} No authors were found :(')
            return
        embed = await self.store_quote(ctx.message,
                                       author_ids,
                                       quote_text=quote_text)
        await ctx.send(f'{ctx.message.author.mention}', embed=embed)

    @quote.command(usage='<quote> <author> [authors ...]',
                   help='- Add a quote to the database')
    async def add(self, ctx: commands.Context, *, text: str):
        await self.quote(ctx, text=text)

    @quote.command(aliases=['s'],
                   usage='<phrase> [authors ...] [number] ',
                   help='- Search for quotes matching phrase')
    async def search(self, ctx: commands.Context, *, text: str):
        number, text = self.get_number_matches(text.strip())
        authors, phrase = self.get_authors(text.strip())
        if number is None:
            number = 1  # Set to default if not amount specified
        elif number > 6:  # TODO Make this configurable on a guild by guild basis
            await ctx.send(
                f'{ctx.message.author.mention} Sending > 6 quotes from a search not permitted.'
            )
            return
        elif number < 1:
            await ctx.send(
                f'{ctx.message.author.mention} Cannot send less than 1 quote.')
        query = {'$text': {'$search': phrase}}
        if authors:
            query.update({'author_id': authors})
        result: AsyncIOMotorCursor = self.bot.db[str(ctx.guild.id)].find(
            self.create_quote_query(query), {'score': {
                '$meta': 'textScore'
            }},
            limit=number)
        result.sort([('score', {'$meta': 'textScore'})])
        e = discord.Embed()
        i = 0
        async for i, quote in utils.async_enumerate(result, start=1):
            e = self.create_quote_embed(quote, self.nth_number_str(i), e=e)
        if i == 0:
            await ctx.send(f'No matches for {phrase} found.')
            return
        elif i > 1:
            title = f'{ctx.author.mention} Best matches for {phrase}:'
        else:
            title = f'{ctx.author.mention} Best match for {phrase}:'
        await ctx.send(title, embed=e)

    @quote.command(name='list',
                   usage='[authors ...] [number=6]',
                   help='- List most recent [number] quotes by [authors]')
    async def list_(self,
                    ctx: commands.Context,
                    *,
                    text: Optional[str] = None):
        if text:
            n, authors = self.get_number_and_authors(text)
            if n is None:
                n = 6  # Set to default if no amount given
            if n > 6:
                await ctx.send(
                    f'{ctx.author.mention} Sending > 6 quotes not permitted')
                return
            elif n < 1:
                await ctx.send(f'{ctx.author.mention} Cannot send < 1 quote')
        else:
            n = 6
            authors = None
        query = {}
        if authors is not None:
            query.update({
                'author_id': authors
            })  # Is formatted into correct MongoDB call by create_quote_query
        results = self.bot.db[str(ctx.guild.id)].find(
            self.create_quote_query(query), limit=n)
        results.sort('time', pymongo.DESCENDING)
        e = discord.Embed()
        i = 0
        async for i, quote in utils.async_enumerate(results, start=1):
            self.create_quote_embed(quote, self.nth_number_str(i), e)
        title = f'{ctx.author.mention} Most recent quote{"s" if i > 1 else ""}'
        if i:
            await ctx.send(title, embed=e)
        else:
            await ctx.send(f'{ctx.message.author.mention} No quotes stored.')

    @commands.check_any(commands.has_permissions(administrator=True),
                        commands.has_permissions(manage_messages=True),
                        commands.has_role(699765480566554645))
    @quote.command(hidden=True, help='- Not Yet Implemented')
    async def delete(self, ctx: commands.Context):
        await ctx.send(
            f"{ctx.author.mention} Sorry haven't implemented that yet :(")

    @quote.command(aliases=['r'],
                   usage='[authors ...]',
                   help='- Display a random quote')
    async def random(self, ctx, *author: Optional[discord.Member]) -> None:
        pipeline = []
        if author:
            pipeline.append({
                '$match': {
                    'author_id': {
                        '$all': [*map(lambda a: a.id, author)]
                    }
                }
            })
        pipeline.append({'$sample': {'size': 1}})
        result = self.bot.db[str(ctx.guild.id)].aggregate(pipeline)
        quote_ = await result.to_list(1)
        e = self.create_quote_embed(quote_[0], 'Random Quote:')
        await ctx.send(ctx.author.mention, embed=e)

    @quote.command(
        aliases=['number', 'countquotes'],
        usage='[authors ...]',
        help='- Count quotes stored, optionally by the specified authors')
    async def count(self,
                    ctx: commands.Context,
                    *,
                    text: Optional[str] = None) -> None:
        query = {}
        if text:
            authors = self.get_authors(text)
            if authors[1].strip() == '':
                if authors[0]:
                    query.update(
                        self.create_quote_query({'author_id': authors[0]}))
                else:
                    authors = ((), )
            else:
                await ctx.send(f'Unexpected argument: {authors[1]}')
                return
        else:
            authors = ((), )
        print(query)
        n = await self.bot.db[str(ctx.guild.id)].count_documents(query)
        if n == 1:
            response = f'{ctx.author.mention} there is 1 quote stored'
        else:
            response = f'{ctx.author.mention} there are {n} quotes stored'

        attribution = self.get_attribution_str(authors[0])
        if attribution:
            await ctx.send(f'{response} by {attribution}')
        else:
            await ctx.send(response)

    def get_number_and_authors(
            self, text: str) -> Union[str, Tuple[Optional[int], Tuple[int]]]:
        number, text = self.get_number_matches(text)
        authors, text = self.get_authors(text.strip())
        text = text.strip()
        if text != '':
            return text
        return number, authors

    async def quote_from_message(self, message: discord.Message,
                                 quoter_id: int) -> None:
        e = await self.store_quote(message, (message.author.id, ),
                                   quoter_id=quoter_id)
        await message.channel.send(f'<@!{quoter_id}>', embed=e)

    async def store_quote(self,
                          message: discord.Message,
                          author_ids: Tuple[int],
                          quote_text: Optional[str] = None,
                          quoter_id: Optional[int] = None) -> discord.Embed:
        quote_object = {
            'author_id': author_ids,
            'quote': quote_text,
            'time': message.created_at,
            'quoter_id': quoter_id
        }
        if quoter_id is None:
            quote_object['quoter_id'] = message.author.id
        if quote_text is None:
            quote_object['quote'] = message.content
        collection_name = str(message.guild.id)
        if collection_name not in self.bot.indexed:
            await self.bot.db[collection_name].create_index([('quote',
                                                              pymongo.TEXT)])
            self.bot.indexed.append(collection_name)
        else:
            query = self.create_quote_query(quote_object,
                                            ignore=['time', 'quoter_id'])
            find_result = await self.bot.db[collection_name].find_one(query)
            if find_result is not None:
                e = discord.Embed()
                e.add_field(name='Error:',
                            value='Quote Already Exists',
                            inline=False)
                return self.create_quote_embed(quote_object,
                                               field_name='Quote:',
                                               e=e)
        await self.bot.db[collection_name].insert_one(quote_object)
        return self.create_quote_embed(quote_object)

    @staticmethod
    def get_attribution_str(authors: Tuple[int]) -> str:
        author_str = ''
        author_len = len(authors)
        if not author_len:
            pass
        elif author_len == 1:
            author_str += utils.create_mention(authors[0])
        elif author_len == 2:
            author_str += ' and '.join(map(utils.create_mention, authors))
        else:
            author_str += ', '.join(map(utils.create_mention, authors[:-1]))
            author_str += ', and ' + utils.create_mention(authors[-1])
        return author_str

    @staticmethod
    def get_authors(text: str) -> Tuple[Optional[Tuple[int]], str]:
        match: Match = AUTHORS_PATTERN.search(text)
        if not match:
            return None, text
        start = match.start()
        text, authors = text[:start], text[start:]
        author_ids: Set = set(BASIC_INT_PATTERN.findall(authors))
        return tuple(map(int, author_ids)), text.strip()

    @staticmethod
    def create_quote_query(query: Dict[str, Any],
                           author_type='and',
                           ignore=()):
        if author_type not in ['and', 'or']:
            raise ValueError('Author Type must equal "and" or "or"')
        out_query = {}
        authors: Tuple = query.get('author_id', ())
        if authors:
            if author_type == 'and':
                out_query['author_id'] = {'$all': authors}
            else:
                out_query['$or'] = [{'author_id': a} for a in authors]
        for key, value in query.items():
            if key not in ignore and key != 'author_id':
                out_query[key] = value
        return out_query

    @staticmethod
    def get_number_matches(text: str) -> Tuple[Optional[int], str]:
        """Returns number from the end of string or -1 if no number is found, along with the remainder of string"""
        match: Match = GET_NUMBER_PATTERN.match(text)
        if match is None:
            return None, text
        return int(match.group(1)), text[:match.start()].strip()

    @staticmethod
    def nth_number_str(n: int) -> str:
        last_n = str(n)[-1]
        conversion_dict = {'1': 'st', '2': 'nd', '3': 'rd'}
        return f'{n}{conversion_dict.get(last_n, "th")}'

    @classmethod
    def create_quote_embed(cls,
                           quote: dict,
                           field_name: Optional[str] = 'Quote Stored:',
                           e: Optional[discord.Embed] = None) -> discord.Embed:
        if e is None:
            e: discord.Embed = discord.Embed()
        attribution = f'- {cls.get_attribution_str(quote["author_id"])}\nQuoted by <@!{quote["quoter_id"]}>'
        e.add_field(name=field_name, value=f'{quote["quote"]}\n{attribution}')
        return e  # TODO add check to see if embed is too long
Beispiel #18
0
 def predicate(ctx):
     return commands.check_any(
     commands.is_owner(),
     commands.has_role('moderator')
     )
Beispiel #19
0
        except discord.errors.HTTPException:
            await ctx.send(
                f"Something went wrong when reacting with \"{emoji}\". Are you sure it's an emoji?"
            )
        except:
            raise


@list_emoji.error
async def list_error(ctx, error):
    if not await general_error(ctx, error): raise


@bot.command(name="activate",
             help=" - Activates the bot in the channel in which it's run.")
@commands.check_any(commands.has_role(ROLE_NEEDED),
                    commands.has_permissions(manage_roles=True))
async def activate(
    ctx
):  # If it's not already there, it adds a dictionary under the channel in which this is run
    if ctx.channel not in EmojiAssignments:
        EmojiAssignments[ctx.channel] = {}
        await ctx.send(f"RoleBot is now active in {ctx.channel.name}")
    else:
        await ctx.send(f"RoleBot is already active in {ctx.channel.name}")


@activate.error
async def activate_error(ctx, error):
    if not await general_error(ctx, error): raise
Beispiel #20
0
class Modmail(commands.Cog, name="Modmail System"):
    def __init__(self, client):
        self.client = client
        self.IST = pytz.timezone('Asia/Kolkata')
        print("Caching Modmail Data...")
        self.active_channels_dict = {
            i['_id']: i["channel_id"]
            for i in self.client.sent_users.find()
        }
        self.ban_dict = {
            i['_id']: {
                'reason': i['reason'],
                'mod': i['mod']
            }
            for i in self.client.blacklisted_users.find()
        }
        with open("data.json") as f:
            data = json.load(f)
            f.close()
        self.category_id = data['category_id']
        self.server_id = data['guild_id']
        self.mod_role_id = data['mod_role_id']
        self.log_channel_id = data['log_channel_id']
        self.guild = self.client.get_guild(self.server_id)
        self.log_channel = discord.utils.get(self.guild.channels,
                                             id=data['log_channel_id'])
        self.msg = None
        print("Done")

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

    @commands.Cog.listener()
    async def on_message(self, message):
        modmail_category = discord.utils.get(self.guild.categories,
                                             id=int(self.category_id))
        mod_role = discord.utils.get(self.guild.roles,
                                     id=int(self.mod_role_id))
        if message.author == self.client.user:
            return
        if not message.guild:
            if message.author not in self.guild.members:
                message_dm = await message.author.send(
                    "You are not in **Gallant Asia**. Join the server to use modmail and connect with the staffs.\n"
                    "Click on ✅ to get invite link.")
                await message_dm.add_reaction('✅')

                def check(reaction, user):
                    return user == message.author and str(
                        reaction.emoji) == '✅'

                try:
                    _, user_ = await self.client.wait_for('reaction_add',
                                                          check=check,
                                                          timeout=10.0)
                except asyncio.TimeoutError:
                    pass
                else:
                    await user_.send("https://discord.gg/NPFqwc9")
                return
            if message.author.id in self.ban_dict:
                await message.author.send(
                    f"You are banned from using Modmail.\n`Reason: {self.ban_dict[message.author.id]['reason']}`"
                )
                return
            if message.author.id not in self.active_channels_dict:
                overwrites = {
                    self.guild.default_role:
                    discord.PermissionOverwrite(read_messages=False),
                    self.guild.me:
                    discord.PermissionOverwrite(read_messages=True),
                    mod_role:
                    discord.PermissionOverwrite(read_messages=True)
                }
                channel = await self.guild.create_text_channel(
                    f"{message.author.name}",
                    overwrites=overwrites,
                    category=modmail_category)
                post = {'_id': message.author.id, "channel_id": channel.id}
                self.client.sent_users.insert_one(post)
                self.active_channels_dict[message.author.id] = channel.id
                self.msg = await self.log_channel.send(
                    content=channel.mention,
                    embed=discord.Embed(
                        title='New Thread',
                        description=
                        f"New thread created by {message.author.name}({message.author.name})\n"
                        f"Channel Created => {channel.mention}",
                        timestamp=datetime.now(self.IST),
                        color=discord.Color.gold()))
                files = [
                    await attachment.to_file()
                    for attachment in message.attachments
                ] if message.attachments != [] else None
                await message.author.send(
                    "Thank you for your message! You've opened up a new thread with our team of supportive moderators and admins."
                    "As long as the bot is online, messages you send here will be forwarded to the team.\n"
                    "If you've realised that you no longer need our help, reply with 'close' and we'll close your thread."
                )
                await channel.send(files=files,
                                   embed=discord.Embed(
                                       title='Reply with *reply',
                                       description=message.content,
                                       timestamp=datetime.now(self.IST),
                                       color=discord.Color.green()))
            else:
                channel = discord.utils.get(self.guild.channels,
                                            id=self.active_channels_dict.get(
                                                message.author.id))
                await self.log_channel.send(
                    content=channel.mention,
                    embed=discord.Embed(
                        title='New message',
                        description=
                        f" Message from {message.author.name}({message.author.name})\n",
                        timestamp=datetime.now(self.IST),
                        color=discord.Color.random()))
                await message.add_reaction("✅")
                await channel.send(
                    embed=discord.Embed(title='Reply with *reply or *r',
                                        description=message.content,
                                        timestamp=datetime.now(self.IST),
                                        color=discord.Color.green()))

    @commands.Cog.listener()
    async def on_member_remove(self, member):
        if member.id in self.active_channels_dict.keys():
            channel = discord.utils.get(
                self.guild.channels, id=self.active_channels_dict[member.id])
            try:
                self.client.sent_users.delete_one({'_id': member.id})
                del self.active_channels_dict[member.id]
            except KeyError:
                pass
            await member.send(
                'You left our server. Your thread has been closed.\n'
                'Hope to see you back soon.\n- Gallant Asia Management Team.')
            await channel.send(
                f"{member.name} has left the server. Thread has been closed.Channel will be deleted in 5 minutes."
            )
            await self.log_channel.send(
                content=channel.mention,
                embed=discord.Embed(
                    title='Thread closed!',
                    description=
                    f'Thread {channel.mention} has been closed due to {member.name} left the server.',
                    color=discord.Color.orange()))
            await asyncio.sleep(300.0)
            check = discord.utils.get(self.guild.channels, id=channel.id)
            if check is not None:
                await channel.delete()
                await self.log_channel.send(embed=discord.Embed(
                    title='Ticket deleted.',
                    description=f"{member.name}'s ticket has been deleted.",
                    color=discord.Color.red()))

    @commands.command(aliases=['r'])
    @commands.check_any(commands.has_permissions(administrator=True),
                        commands.has_any_role("Moderator", "Head Mod"))
    async def reply(self, ctx, *, message):
        if isinstance(ctx.channel, discord.DMChannel):
            return
        user = discord.utils.get(self.guild.members,
                                 id=self.get_key(ctx.channel.id))
        if user is not None:
            var = 'Community Lead' if ctx.author.top_role.name == '.' else ctx.author.top_role.name
            files = [
                await attachment.to_file()
                for attachment in ctx.message.attachments
            ] if ctx.message.attachments != [] else None
            await user.send(
                content=
                f"**({var}){ctx.author.name}#{ctx.author.discriminator}:** {message}",
                files=files)
            await ctx.message.add_reaction('✅')
            await self.log_channel.send(
                content=ctx.channel.mention,
                embed=discord.Embed(
                    description=
                    f'{ctx.author.name} replied to {ctx.channel.mention}',
                    timestamp=datetime.now(self.IST),
                    color=discord.Color.random()))
        else:
            await ctx.send(
                'Some error occurred. Maybe you are not using the command in a thread channel.'
            )

    @commands.command()
    @commands.check_any(commands.has_permissions(administrator=True),
                        commands.has_any_role("Moderator", "Head Mod"))
    async def close(self, ctx):
        if isinstance(ctx.channel, discord.DMChannel):
            return
        if ctx.channel.id in self.active_channels_dict.values():
            self.client.sent_users.delete_one(
                {'_id': self.get_key(ctx.channel.id)})
            user = discord.utils.get(self.guild.members,
                                     id=self.get_key(ctx.channel.id))
            try:
                del self.active_channels_dict[user.id]
            except KeyError:
                pass
            await user.send('Your thread has been closed.')
            await ctx.channel.send(
                'Thread marked as closed. Channel will be deleted in 5 minutes.'
            )
            await self.log_channel.send(
                content=ctx.channel.mention,
                embed=discord.Embed(
                    title='Thread closed!',
                    description=
                    f'Thread {ctx.channel.mention} has been marked as closed by {ctx.author.mention}',
                    color=discord.Color.orange()))
            await asyncio.sleep(300.0)
            check = discord.utils.get(self.guild.channels, id=ctx.channel.id)
            if check is not None:
                await ctx.channel.delete()
                await self.log_channel.send(embed=discord.Embed(
                    title='Ticket deleted.',
                    description=
                    f"{user.name}({user.mention})'s ticket has been deleted.",
                    color=discord.Color.red()))

    @commands.command()
    @commands.is_owner()
    async def delete(self, ctx, user_id):
        try:
            del self.active_channels_dict[user_id]
            self.client.sent_users.delete_one({"_id": user_id})
            await ctx.send("Deleted.")
        except KeyError:
            await ctx.send(f"{user_id} not found in local database.")

    @commands.command()
    @commands.has_permissions(administrator=True)
    async def list(self, ctx):
        text = ''
        for key, val in self.active_channels_dict.items():
            text += f"<@{key}> => <#{val}>\n"
        await ctx.send(text)

    def get_key(self, value):
        for key, val in self.active_channels_dict.items():
            if val == value:
                return key
        return None

    @commands.command(aliases=['bl', 'mban'])
    @commands.check_any(commands.has_permissions(administrator=True),
                        commands.has_role('Moderator'))
    async def blacklist(self, ctx, user: discord.Member, reason):
        self.ban_dict[user.id] = dict(
            reason=reason, mod=f'{ctx.author.name}#{ctx.author.discriminator}')
        post = {
            '_id': user.id,
            'reason': reason,
            'mod': f'{ctx.author.name}#{ctx.author.discriminator}'
        }
        self.client.blacklisted_users.insert_one(post)
        await ctx.send(
            discord.Embed(title=f'Banned {user.name}#{user.discriminator}',
                          description=f"**Reason**: {reason}",
                          color=discord.Color.red(),
                          timestamp=datetime.now(self.IST)).set_footer(
                              text=f"Mod - {ctx.author.name}"))

    @commands.command()
    @commands.check_any(commands.has_permissions(administrator=True),
                        commands.has_role('Moderator'))
    async def banlist(self, ctx):
        embed = discord.Embed(title="Banned users list!",
                              description='',
                              colour=ctx.author.color)
        for x, y in self.ban_dict.items():
            embed.description += f"<@{x}>\n**Reason**: {y['reason']}\nMod: {y['mod']}\n-----------------------------------------"
        await ctx.send(embed=embed)
Beispiel #21
0
def has_server_perms():
    """Perms to manage other people on the server"""
    return commands.check_any(is_guild_owner(), commands.is_owner(), commands.has_role(utils.bot_manager_role))
class Roles(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        conn = sqlite3.connect('databases/roles.db')
        c = conn.cursor()
        try:
            c.execute(
                'CREATE TABLE IF NOT EXISTS roles(name TEXT, joinable INT)')
        except sqlite3.OperationalError as error:
            print(f'Sqlite operational error: {error}')
        conn.commit()
        conn.close()

    @commands.check_any(commands.is_owner(), commands.has_role('Admin'))
    @commands.command(name='createrole',
                      brief='Creates a self-joinable role',
                      aliases=['newrole'])
    async def createrole(self,
                         ctx,
                         role: str,
                         color: discord.Colour,
                         joinable=True):
        conn = sqlite3.connect('databases/roles.db')
        c = conn.cursor()
        name = (role, )
        search = c.execute('SELECT * FROM roles WHERE name=?', name)
        data = c.fetchall()
        if len(data) > 0:
            await ctx.send('That role already exists.')
        else:
            print('Running createrole')
            await ctx.guild.create_role(name=role, color=color)
            print('Role created.')
            if joinable is True:
                # Stash the role in the database and backup to github.
                data = (role, joinable)
                c.execute('INSERT INTO roles VALUES (?,?)', data)
                conn.commit()
                conn.close()
            cmd = subprocess.run(
                'git add databases/roles.db && git commit -m "Database Update" && git push [email protected]:ConstantStealth/BillyBobDiscordBot-Private.git',
                shell=True)
            await ctx.send('Created role {}.'.format(role))

        role_cache_updated = True

    @commands.check_any(commands.is_owner(), commands.has_role('Admin'))
    @commands.command(name='deleterole',
                      brief='Deletes a self-joinable role',
                      aliases=['removerole'])
    async def deleterole(self, ctx, *, role_name, reason=None):
        role = discord.utils.get(ctx.guild.roles, name=role_name)
        if role is not None:
            conn = sqlite3.connect('databases/roles.db')
            c = conn.cursor()
            name = (role_name, )
            search = c.execute('SELECT * FROM roles WHERE name=?', name)
            data = c.fetchall()
            if len(data) > 0:
                deleted = c.execute('DELETE FROM roles WHERE name=?', name)
            else:
                await ctx.send('That role does not exist.')
            conn.commit()
            conn.close()
            role_cache_updated = True
            await role.delete(reason='Removed by command')
            await ctx.send(f'Deleted role {role_name}.')
            cmd = subprocess.run(
                'git add databases/roles.db && git commit -m "Database Update" && git push [email protected]:ConstantStealth/BillyBobDiscordBot-Private.git',
                shell=True)
        else:
            await ctx.send(f'{role_name} does not exist.')

    @commands.command(name='joinrole',
                      brief='Join a self-joinable role',
                      aliases=['subscribe', 'join'])
    async def joinrole(self, ctx, *, role_name: str):
        role = discord.utils.get(ctx.guild.roles, name=role_name)
        conn = sqlite3.connect('databases/roles.db')
        c = conn.cursor()
        name = (role_name, )
        search = c.execute('SELECT * FROM roles WHERE name=?', name)
        data = c.fetchall()
        conn.close()
        if role is not None:
            roles = ctx.author.roles
            if role in roles:
                await ctx.author.remove_roles(role)
                await ctx.send(f'You have left {role_name}.')
            elif len(data) > 0:
                await ctx.author.add_roles(role)
                await ctx.send(f'You have joined {role_name}.')
            else:
                await ctx.send(
                    f' Role {role_name} does not exist, please check the available self-joinable roles with the .roles command.'
                )
        else:
            await ctx.send(
                f' Role {role_name} does not exist, please check the available self-joinable roles with the .roles command.'
            )

    @commands.command(name='rolelist',
                      brief='Displays a list of self-joinable roles',
                      aliases=['roleslist', 'listroles', 'roles'])
    async def rolelist(self, ctx):
        conn = sqlite3.connect('databases/roles.db')
        c = conn.cursor()
        joinable = (True, )
        search = c.execute('SELECT * FROM roles WHERE joinable=?', joinable)
        roles = c.fetchall()
        msg = ""
        for role in roles:
            msg = f'{msg}{role[0]}\n'
        msg = f'```\n{msg}```'
        conn.close()
        await ctx.send('Below is a list of self-joinable roles: %s' % msg)

    @commands.check_any(commands.is_owner(), commands.has_role('Admin'))
    @commands.command(
        name='backupdb',
        brief='Backup new/updated database file from server to GitHub',
        aliases=['updatedb', 'dbupdate'])
    async def backupdb(self, ctx):
        await ctx.send('Committing and pushing updated database to GitHub... ')
        cmd = subprocess.run(
            'git add databases/roles.db && git commit -m "Database Update" && git push [email protected]:ConstantStealth/BillyBobDiscordBot-Private.git',
            shell=True)
        if cmd.returncode == 0:
            await ctx.send('The database has been updated to GitHub')
        else:
            await ctx.send(
                'There was an error updating the database to GitHub, the database may already be up to date.'
            )
Beispiel #23
0
 def predicate(ctx):
     return commands.check_any(commands.has_role(STUDENT_ROLE_NAME))
Beispiel #24
0
 def predicate(ctx):
     return commands.check_any(commands.is_owner(), commands.has_role(MODERATOR_ROLE_NAME))
Beispiel #25
0
 def predicate(ctx):
     return commands.check_any(commands.has_role(CHILL_ROLE_NAME))
Beispiel #26
0
class Basic(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.Cog.listener()
    async def on_command_error(self, ctx, ex):
        channel = await ctx.author.create_dm()
        print(ex)
        if isinstance(ex, commands.CommandOnCooldown):
            await channel.send(ex)
        elif ctx.message.channel.name != 'bot-commands':
            await channel.send("Please keep bot interactions within the #bot-commands channel.")
        else:
            await channel.send("Something went wrong. Please DM an organizer if you believe this is not intended.")
            jason = self.bot.get_user(173263365777522688)
            dm = await jason.create_dm()
            await dm.send(ex)

    @commands.command(help_command="!ping",
                      description="Ping the bot",
                      help="Ping the bot")
    @commands.cooldown(1, 60, commands.BucketType.user)
    @in_bot_commands()
    async def ping(self, ctx):
        if len(ctx.message.content) > 5:
            dm = await ctx.author.create_dm()
            await dm.send("Too many arguments for !ping (try just !ping)")
            return
        await ctx.send(f"Online! Latency: {self.bot.latency * 1000:.03f}ms")

    @commands.command(help_command="!room @user1 @user2 ...",
                      description="Create a private voice channel with select users",
                      help="Create a private voice channel with select users")
    @commands.guild_only()
    @commands.cooldown(1, 60, commands.BucketType.user)
    @commands.check_any(commands.has_role("Hacker"), commands.has_role("Organizer"),
                        commands.has_role("Mentor"), commands.has_role("Sponsor"))
    @in_bot_commands()
    async def room(self, ctx):
        guild = ctx.guild
        author = ctx.author
        active_check = True
        if len(ctx.message.mentions) == 0:
            dm = await ctx.author.create_dm()
            await dm.send("Please specify 1 or more specific members (using @) when using !room")
            return
        channel = await create_channel(guild, author, ctx.message.mentions)
        await ctx.send("Room created!")
        while True:
            if len(channel.members) == 0:
                if active_check is True:
                    active_check = False
                else:
                    await channel.delete()
                    await ctx.send("%s's room deleted due to inactivity" % author.name)
                    return
            else:
                active_check = True
            await asyncio.sleep(300)

    @commands.command(help_command="!invite", description="Create a server invite to share with others", help="Create a server invite for a friend.")
    @commands.guild_only()
    @commands.cooldown(1, 60, commands.BucketType.user)
    @commands.check(commands.has_role("Hacker") or commands.has_role("Organizer") or
                    commands.has_role("Mentor") or commands.has_role("Sponsor"))
    @in_bot_commands()
    async def invite(self, ctx):
        link = await ctx.channel.create_invite(max_age=300)
        await ctx.send(link)

    # @commands.command(help_command="!sponsors", description="See our list of sponsors.",
    #                   help="See our list of sponsors.")
    # @commands.guild_only()
    # @commands.cooldown(1, 60, commands.BucketType.user)
    # @commands.check(commands.has_role("Hacker") or commands.has_role("Organizer") or
    #                 commands.has_role("Mentor") or commands.has_role("Sponsor"))
    # @in_bot_commands()
    # async def sponsors(self, ctx):
    #     guild = ctx.guild
    #     sponsor_category = None
    #     for category in guild.categories:
    #         if category.name == "Sponsors":
    #             sponsor_category = category
    #             break
    #     if sponsor_category is None:
    #         return
    #     message = ""
    #     for channel in sponsor_category.channels:
    #         if channel.name != "sponsor-general":
    #             message += f"{channel}, "
    #     message = message[:-2]
    #     await ctx.send(message)


    @commands.command(help_command="!request <organizer/mentor/sponsor> [company_name] message", help="Request help from an organizer, sponsor, or mentor.")
    @commands.guild_only()
    @commands.cooldown(1, 60, commands.BucketType.user)
    @commands.check_any(commands.has_role("Hacker"), commands.has_role("Organizer"),
                        commands.has_role("Mentor"), commands.has_role("Sponsor"))
    @in_bot_commands()
    async def request(self, ctx, *args):
        guild = ctx.guild
        author = ctx.author
        user_to_alert = args[0].lower()

        if user_to_alert == "organizer" or user_to_alert == "mentor" or user_to_alert == "sponsor":
            channel_name = args[1].lower() if user_to_alert == "sponsor" else user_to_alert + "s"
            message = " ".join(args[2:]) if user_to_alert == "sponsor" else " ".join(args[1:])

            # this part assumes each company has its own channel called "#google", "#microsoft", etc
            # also assumes there is "#mentors" and "#organizers"
            channel_to_alert = discord.utils.get(guild.text_channels, name=channel_name)
            
            if channel_to_alert is not None:
                await channel_to_alert.send(f"{channel_to_alert.mention} From {author.mention}: {message}")
            else:
                # should never get here except if company is mispelled, as long as we have "#organizers" and "#mentors"
                dm = await ctx.author.create_dm()
                if user_to_alert == "sponsor":
                    await dm.send(f"Make sure you spelt the company name right. If the error still persists, please contact an organizer.")
                    if "organizer" in [role.name.lower() for role in author.roles]:
                        await dm.send(f"Since you are an organizer, consider making the channel \"#{channel_name}\" to prevent this from happening again?")
                else:
                    await dm.send(f"Oops! We've made an error on our end. Please let one of the organizers know (through other means) immediately!")
                return
        else: 
            dm = await ctx.author.create_dm()
            await dm.send(f"{user_to_alert} is not a valid argument. The available options are: organizer, sponsor, and mentor.")
            return

        await ctx.send("Request received! Someone will be in touch shortly. ")
Beispiel #27
0
class Administration(commands.Cog):
    """Commands for bot administration."""
    def __init__(self, bot: commands.Bot):
        self.bot = bot

    @commands.check_any(commands.is_owner(),
                        commands.has_role(718006431231508481),
                        commands.has_role(930346842586218607))
    @commands.group(aliases=("am", ),
                    invoke_without_command=True,
                    case_insensitive=True)
    async def admin(self, ctx):
        pass

    @commands.check_any(commands.is_owner(),
                        commands.has_role(718006431231508481),
                        commands.has_role(930346842586218607))
    @admin.command(aliases=("sp", ))
    async def suspend(self,
                      ctx,
                      users: commands.Greedy[FetchUserConverter],
                      *,
                      reason: str = None):
        """Suspend one or more users."""

        await self.bot.mongo.db.member.update_many(
            {"_id": {
                "$in": [x.id for x in users]
            }},
            {"$set": {
                "suspended": True,
                "suspension_reason": reason
            }},
        )
        await self.bot.redis.hdel("db:member", *[int(x.id) for x in users])
        users_msg = ", ".join(f"**{x}**" for x in users)
        await ctx.send(f"Suspended {users_msg}.")

    @commands.check_any(commands.is_owner(),
                        commands.has_role(718006431231508481),
                        commands.has_role(930346842586218607))
    @admin.command(aliases=("usp", ))
    async def unsuspend(self, ctx, users: commands.Greedy[FetchUserConverter]):
        """Unuspend one or more users."""

        await self.bot.mongo.db.member.update_many(
            {"_id": {
                "$in": [x.id for x in users]
            }},
            {"$unset": {
                "suspended": 1,
                "suspension_reason": 1
            }},
        )
        await self.bot.redis.hdel("db:member", *[int(x.id) for x in users])
        users_msg = ", ".join(f"**{x}**" for x in users)
        await ctx.send(f"Unsuspended {users_msg}.")

    @commands.check_any(commands.is_owner(),
                        commands.has_role(718006431231508481),
                        commands.has_role(930346842586218607))
    @admin.command(aliases=("spawn", ))
    async def randomspawn(self, ctx):
        await self.bot.get_cog("Spawning").spawn_pokemon(ctx.channel)

    @commands.check_any(commands.is_owner(),
                        commands.has_role(718006431231508481),
                        commands.has_role(930346842586218607))
    @admin.command(aliases=("giveredeem", "ar", "gr"))
    async def addredeem(self, ctx, user: FetchUserConverter, num: int = 1):
        """Give a redeem."""

        await self.bot.mongo.update_member(user, {"$inc": {"redeems": num}})
        await ctx.send(f"Gave **{user}** {num} redeems.")

    @commands.check_any(commands.is_owner(),
                        commands.has_role(718006431231508481),
                        commands.has_role(930346842586218607))
    @admin.command(aliases=("givecoins", "ac", "gc"))
    async def addcoins(self, ctx, user: FetchUserConverter, amt: int):
        """Add to a user's balance."""

        await self.bot.mongo.update_member(user, {"$inc": {"balance": amt}})
        await ctx.send(f"Gave **{user}** {amt} Pokécoins.")

    @commands.check_any(commands.is_owner(),
                        commands.has_role(718006431231508481),
                        commands.has_role(930346842586218607))
    @admin.command(aliases=("giveshard", "as", "gs"))
    async def addshard(self, ctx, user: FetchUserConverter, amt: int):
        """Add to a user's shard balance."""

        await self.bot.mongo.update_member(user,
                                           {"$inc": {
                                               "premium_balance": amt
                                           }})
        await ctx.send(f"Gave **{user}** {amt} shards.")

    @commands.check_any(commands.is_owner(),
                        commands.has_role(718006431231508481),
                        commands.has_role(930346842586218607))
    @admin.command(aliases=("givevote", "av", "gv"))
    async def addvote(self, ctx, user: FetchUserConverter, amt: int = 1):
        """Add to a user's vote streak."""

        await self.bot.mongo.update_member(
            user,
            {
                "$set": {
                    "last_voted": datetime.utcnow()
                },
                "$inc": {
                    "vote_total": amt,
                    "vote_streak": amt
                },
            },
        )

        await ctx.send(f"Increased vote streak by {amt} for **{user}**.")

    @commands.check_any(commands.is_owner(),
                        commands.has_role(718006431231508481),
                        commands.has_role(930346842586218607))
    @admin.command(aliases=("givebox", "ab", "gb"))
    async def addbox(self,
                     ctx,
                     user: FetchUserConverter,
                     box_type,
                     amt: int = 1):
        """Give a user boxes."""

        if box_type not in ("normal", "great", "ultra", "master"):
            return await ctx.send("That's not a valid box type!")

        await self.bot.mongo.update_member(
            user,
            {
                "$set": {
                    "last_voted": datetime.utcnow()
                },
                "$inc": {
                    f"gifts_{box_type}": amt
                },
            },
        )

        if amt == 1:
            await ctx.send(f"Gave **{user}** 1 {box_type} box.")
        else:
            await ctx.send(f"Gave **{user}** {amt} {box_type} boxes.")

    @commands.check_any(commands.is_owner(),
                        commands.has_role(718006431231508481),
                        commands.has_role(930346842586218607))
    @admin.command(aliases=("g", ))
    async def give(self, ctx, user: FetchUserConverter, *, arg: str):
        """Give a pokémon."""

        shiny = False

        if arg.lower().startswith("shiny"):
            shiny = True
            arg = arg.lower().replace("shiny", "").strip()

        species = self.bot.data.species_by_name(arg)

        if species is None:
            return await ctx.send(f"Could not find a pokemon matching `{arg}`."
                                  )

        ivs = [mongo.random_iv() for i in range(6)]

        await self.bot.mongo.db.pokemon.insert_one({
            "owner_id":
            user.id,
            "owned_by":
            "user",
            "species_id":
            species.id,
            "level":
            1,
            "xp":
            0,
            "nature":
            mongo.random_nature(),
            "iv_hp":
            ivs[0],
            "iv_atk":
            ivs[1],
            "iv_defn":
            ivs[2],
            "iv_satk":
            ivs[3],
            "iv_sdef":
            ivs[4],
            "iv_spd":
            ivs[5],
            "iv_total":
            sum(ivs),
            "shiny":
            shiny,
            "idx":
            await self.bot.mongo.fetch_next_idx(user),
        })

        await ctx.send(f"Gave **{user}** a {species}.")

    @commands.check_any(commands.is_owner(),
                        commands.has_role(718006431231508481),
                        commands.has_role(930346842586218607))
    @admin.command()
    async def setup(self, ctx, user: FetchUserConverter, num: int = 100):
        """Test setup pokémon."""

        # This is for development purposes.

        pokemon = []
        idx = await self.bot.mongo.fetch_next_idx(user, reserve=num)

        for i in range(num):
            spid = random.randint(1, 898)
            ivs = [mongo.random_iv() for i in range(6)]
            pokemon.append({
                "owner_id": user.id,
                "owned_by": "user",
                "species_id": spid,
                "level": 80,
                "xp": 0,
                "nature": mongo.random_nature(),
                "iv_hp": ivs[0],
                "iv_atk": ivs[1],
                "iv_defn": ivs[2],
                "iv_satk": ivs[3],
                "iv_sdef": ivs[4],
                "iv_spd": ivs[5],
                "iv_total": sum(ivs),
                "shiny": False,
                "idx": idx + i,
            })

        await self.bot.mongo.db.pokemon.insert_many(pokemon)
        await ctx.send(f"Gave **{user}** {num} pokémon.")
Beispiel #28
0
                        (str(temprow).lower(), ))
                    rows = cur.fetchall()
                    temprows = str(rows[0])[1:-2]
                    print(temprows)
                    cur.execute(
                        "SELECT TEXT FROM wordcount WHERE LOWER(TEXT)=?",
                        (str(temprow).lower(), ))
                    rows = cur.fetchall()
                    temprows2 = str(rows[0])[2:-3]
                    response = temprows2 + ' count: ' + temprows
                    await message.channel.send(response)
    await bot.process_commands(message)


@bot.command()
@commands.check_any(commands.has_role('Ultimate Weebs'), commands.is_owner())
async def addcounter(ctx, letext):
    print("in addcounter")
    cur = dbconn.cursor()
    cur.execute("SELECT 1 FROM wordcount WHERE LOWER(TEXT)=?",
                (letext.lower(), ))
    rows = cur.fetchall()
    if not rows:
        cur.execute("INSERT INTO wordcount (TEXT) VALUES (?)", (letext, ))
        dbconn.commit()
        tempstring = letext + " succesfully added"
    else:
        tempstring = letext + " already exists"
    print(tempstring)
    await ctx.send(tempstring)
Beispiel #29
0
class Topics(commands.Cog):
    """Get topics for discussion."""

    def __init__(self, bot: Bot):
        self.bot = bot

        self.messages = None

    async def gen_topic(self):
        topic = await self.bot.db.get_random_topic()

        embed = Embed(
            description=topic["topic"],
            colour=0x87CEEB,
            timestamp=topic["created_at"],
        )

        user = self.bot.get_user(topic["author_id"])

        embed.set_footer(
            text=f"From: {user if user else 'unknown'} • ID: {topic['id']} • Created:"
        )

        return embed

    @commands.command(name="topic")
    @commands.cooldown(rate=1, per=60, type=commands.BucketType.channel)
    @in_channel(264417177094848512, 737760236013748295, 779479420481175554)
    async def get_topic(self, ctx: Context):
        """Get a topic to talk about."""

        embed = await self.gen_topic()

        msg = await ctx.reply(embed=embed)

        await msg.add_reaction("🔁")

        self.message = TopicMessage(msg)

    @commands.command(name="newtopic")
    @commands.cooldown(rate=1, per=600, type=commands.BucketType.member)
    @commands.check_any(commands.is_owner(), commands.has_any_role(339445127917338635, 337442104026595329))
    @in_channel(264417177094848512, 737760236013748295)
    async def new_topic(self, ctx: Context, *, topic: str):
        """Create a new topic."""

        if len(topic) > 200:
            return await ctx.reply("Topics must be 200 characters or less.")

        topic = await self.bot.db.create_topic(ctx.author.id, topic)

        await ctx.reply(f"Topic created! ID: {topic['id']}")

    @commands.command(name="importtopics")
    @commands.check_any(commands.is_owner(), commands.has_role(337442104026595329))
    async def import_topics(self, ctx: Context):
        """Import topics from a text file."""

        if not ctx.message.attachments:
            return await ctx.reply("You must attach a file for this.")

        async with ctx.typing():
            file = await self.bot.sess.get(ctx.message.attachments[0].url)
            file = await file.text()

            ids = []

            for line in file.split("\n"):
                if line:
                    topic = await self.bot.db.create_topic(ctx.author.id, line)
                    ids.append(topic['id'])

            await ctx.reply(f"Successfully inserted {len(ids)} topics")

    @commands.command(name="deltopic")
    @commands.check_any(commands.is_owner(), commands.has_role(337442104026595329))
    async def del_topic(self, ctx: Context, id: int):
        """Delete a topic."""

        await self.bot.db.delete_topic(id)

        await ctx.message.add_reaction("👌")

    @commands.command(name="topicinfo")
    @commands.check_any(commands.is_owner(), commands.has_role(337442104026595329))
    async def topic_info(self, ctx: Context, id: int):
        """Get information about a topic."""

        topic = await self.bot.db.get_topic_by_id(id)

        if not topic:
            return await ctx.reply("Not a valid topic.")

        await ctx.reply(f"ID: {topic['id']}\nCreated by: {ctx.guild.get_member(topic['author_id'])} ({topic['author_id']})\nData:```\n{topic['topic']}```")

    @commands.command(name="lstopics")
    @commands.check_any(commands.is_owner(), commands.has_role(337442104026595329))
    async def list_topics(self, ctx: Context):
        """List all topics."""

        topics = await self.bot.db.get_topics()

        data = "\n".join([f"{str(topic['id']).zfill(4)}: {topic['topic']}" for topic in topics])

        await ctx.reply(f"There are a total of {len(topics)} topics:", file=File(StringIO(data), filename="topics.txt"))

    @commands.Cog.listener()
    async def on_reaction_add(self, reaction: Reaction, member: Member):
        """Allows for refreshing the topic."""

        if not isinstance(member, Member):
            return

        if member == self.bot.user:
            return

        if not self.message:
            return

        if self.message.msg.id != reaction.message.id:
            return

        if self.message.time + 30 < time():
            return

        self.message.users.add(member.id)

        if len(self.message.users) >= 4:
            await self.message.msg.edit(embed=await self.gen_topic())
            self.message = None
Beispiel #30
0
class Tempchannels(commands.Cog):
    """Allows users to create temporary channels."""
    def __init__(self, bot, category_id):
        self.bot = bot
        self.category = bot.get_channel(category_id)
        self.category_name = "\U000023F2 Temporary Channels"

        self.reminder = timedelta(days=2)
        self.timeout = timedelta(hours=8)

        self.cleanup_channels.start()

    @tasks.loop(minutes=1.0)
    async def cleanup_channels(self):
        if self.category is not None:
            time = datetime.utcnow()
            for channel in self.category.channels:
                message_query = await channel.history(limit=1).flatten()
                if len(message_query) == 0:
                    break
                last_message = message_query[0]
                age = time - last_message.created_at
                if last_message.author.id == self.bot.user.id:
                    if age >= self.timeout:
                        await channel.delete()
                else:
                    if age >= self.reminder:
                        await channel.send(embed=Embed(
                            title="Channel scheduled for deletion:",
                            description=
                            "If this channel remains inactive, I will delete it.",
                            color=self.bot.colors['default']))

    @commands.command(aliases=["tempchan", "tc"])
    @commands.guild_only()
    async def tempchannel(self, ctx, name):
        """Create a new Temporary Channels category."""
        if self.category is None:
            await ctx.channel.send(embed=ctx.bot.error_embed(
                "The Temporary Channels Category is not set up yet."))
            return
        channel = await ctx.guild.create_text_channel(name,
                                                      category=self.category)
        member = ctx.guild.get_member(ctx.author.id)
        await channel.set_permissions(member,
                                      manage_channels=True,
                                      manage_messages=True)
        await channel.send(
            embed=Embed(title="Welcome to {}!".format(str(channel)),
                        description="A new Temporary Channel moderated by {}.".
                        format(member.display_name),
                        color=ctx.bot.colors['default']))

    @commands.command()
    @commands.check_any(commands.is_owner(), commands.has_role('Operator'))
    # TODO: Check for any role in config.json
    async def tempchannelssetup(self, ctx):
        """Setup the Temporary Channels category."""
        self.category = await ctx.guild.create_category(self.category_name)
        with open(config_file, 'w') as file:
            file.write(str(self.category.id))
        await ctx.channel.send(embed=ctx.bot.confirm_embed(
            "Temporary Channels Category is set up."))