Example #1
0
    async def set(self, ctx, tz_name: str):
        """Set your current timezone"""
        try:
            local_tz = pytz.timezone(tz_name)
        except pytz.exceptions.UnknownTimeZoneError:
            await ctx.reply(f'The timezone "**{tz_name}**" does not exist')
            return

        with self.cursor_context(commit=True) as cursor:
            cursor.execute(
                *db_util.select("profiles").items("id").limit(1).where(
                    id_user=ctx.author.id).build)
            row = cursor.fetchone()

        with self.cursor_context(commit=True) as cursor:
            if not row:
                cursor.execute(*db_util.insert("profiles").items(
                    id_user=ctx.author.id, timezone=tz_name).build)
            else:
                cursor.execute(*db_util.update("profiles").items(
                    timezone=tz_name).where(id=row[0]).build)

        utc = pytz.utc
        time_now = datetime.datetime.utcnow()
        time_now_utc = utc.localize(time_now)
        time_now_localized = time_now_utc.astimezone(local_tz)
        time_now_formatted = time_now_localized.strftime('%Y-%m-%d %H:%M:%S')
        await ctx.reply(
            f'Your timezone has been set to "**{tz_name}**", your local time is **{time_now_formatted}**'
        )
Example #2
0
    async def process(self, ctx, timestamp: str = None):
        """Process every question with your :upvote: reaction on it, save it to the database and remove it"""
        saved = []
        with self.cursor_context() as cursor:
            # Get the last stream ID
            res = cursor.execute(*db_util.select("streams", "id").limit(1)
                                 .where(id_server=ctx.guild.id).order(date="desc").build)
            if not res:
                await ctx.reply('No streams have been found !')
                return

            row = cursor.fetchone()

        stream_id = row[0]
        destination = self.bot.get_channel(self.config.bot.channel.ama_destination)
        if destination is None:
            await ctx.reply('There is no destination channel.')
            return

        async for msg in ctx.channel.history(limit=200):
            to_save = False
            for reaction in msg.reactions:
                if reaction.emoji.name == 'upvote':
                    from_me = discord.utils.get(reaction.users().flatten(), id=ctx.author.id) is not None
                    to_save = from_me
                    break

            if to_save:
                question_details = msg.content.split('\n-----------------------\n')
                if len(question_details) != 2:
                    await ctx.reply('question_details fail.')
                    continue

                question_infos = question_details[0].split(' | ')
                if len(question_infos) != 3:
                    await ctx.reply('question_infos fail.')
                    continue

                saved.append(msg)
                q_content = question_details[1]
                q_author = question_infos[0].replace('From ', '')
                q_date = datetime.strptime(question_infos[1].replace(' UTC', ''), '%c')
                q_timestamp = '' if timestamp is None else timestamp

                with self.cursor_context(commit=True) as cursor:
                    cursor.execute(*db_util.insert("questions")
                                   .items(id_server=ctx.guild.id, id_stream=stream_id, author=q_author,
                                          datetime=q_date.strftime('%Y-%m-%d %H:%M:%S'), question=q_content,
                                          timestamp=q_timestamp))

        if saved:
            for msg in saved:
                await msg.delete()

        await ctx.reply('{} message(s) transferred to {}.'.format(len(saved), destination.name))
Example #3
0
    def get_message(self, guild):
        with self.cursor_context() as cursor:
            res = cursor.execute(*db_util.select("welcomes", items="message").where(id_server=guild.id).build)
            if not res:
                cursor.execute(*db_util.insert("welcomes").items(id_server=guild.id, message="").build)
                return None

            row = cursor.fetchone()

        text = row[0]
        return text
Example #4
0
    async def name(self, ctx):
        with self.cursor_context(commit=True) as cursor:
            cursor.execute(*db_util.select("event_logs").items("id_user")
                           .where(id_server=325197025719091201).distinct.build)
            rows = cursor.fetchall()

        if rows:
            with self.cursor_context(commit=True) as cursor:
                for row in rows:
                    user = await self.bot.get_user_info(row[0])
                    if user is None:
                        continue

                    cursor.execute(*db_util.insert("users", id_user=user.id, user_name=str(user)))
        await ctx.author.send('Done')
Example #5
0
    async def cog_before_invoke(self, ctx):
        if ctx.invoked_subcommand.name != "list":
            tag = ctx.kwargs.get("tag")

            # Check if tag exists in database
            with self.cursor_context() as cursor:
                cursor.execute(
                    *db_util.select("tags").items("name", "channel").limit(
                        1).where(id_server=ctx.guild.id, name=tag).build)
                row = cursor.fetchone()

            if not row:
                await ctx.reply('The tag "{}" does not exist'.format(tag))
                raise ThrowawayException

            tag_name = row[0]
            channel_id = row[1]

            # Check if the role associated with the tag exists, if not, create it
            tag_role = discord.utils.get(ctx.guild.roles, name=tag_name)
            if tag_role is None:
                tag_role = await ctx.guild.create_role(name=tag_name,
                                                       mentionable=True,
                                                       reason="Tag creation")

            # Get the linked channel if applicable
            channel = self.bot.get_channel(channel_id) if channel_id else None

            # Check if the author already has tag_role
            has_role = discord.utils.get(ctx.author.roles,
                                         id=tag_role.id) is not None

            ctx.custom["linked_channel"] = channel
            ctx.custom["tag_role"] = tag_role
            ctx.custom["has_role"] = has_role
Example #6
0
    async def list(self, ctx):
        """Lists the available tags"""
        with self.cursor_context() as cursor:
            cursor.execute(*db_util.select("tags").items(
                "name", "description", "channel").order(">name").where(
                    id_server=ctx.guild.id).build)
            rows = cursor.fetchall()

        embed = discord.Embed(
            title="List of the available tags",
            type="rich",
            colour=discord.Colour.from_rgb(0, 174, 134),
            description=
            "You can add those tags to your profile by using the command **+tag** :"
            "```\nExample: +Gamer```or remove them by using the command **-tag** :"
            "```\nExample: -Gamer```\n**These commands only work in #bot-commands **\n\n"
            "Role list:")
        for row in rows:
            value = row[1]

            channel = self.bot.get_channel(row[2]) if row[2] else None
            if channel is not None:
                value += f' (Make {channel.mention} visible)'

            embed.add_field(name=row[0], value=value, inline=False)

        if not embed.fields:
            embed.add_field(
                name="None defined",
                value="No roles have been defined for self-assignment")

        await ctx.reply(embed=embed)
Example #7
0
    async def on_message(self, message):
        if not message.content.startswith(
                self.bot.command_prefix) and not message.author.bot:
            guild = message.guild
            author = message.author
            channel = message.channel
            if guild is not None:
                with self.cursor_context() as cursor:
                    db_util.select("statistics_global").items(
                        "id",
                        "msg_count").where(id_server=guild.id,
                                           id_user=author.id,
                                           id_channel=channel.id).run(cursor)
                    row = cursor.fetchone()

                with self.cursor_context(commit=True) as cursor:
                    if not row:
                        db_util.insert("statistics_global").items(
                            id_server=guild.id,
                            id_user=author.id,
                            id_channel=channel.id,
                            msg_count=1).run(cursor)
                    else:
                        row_id = row[0]
                        db_util.update("statistics_global").items(
                            msg_count=DBFunction("msg_count+1")).where(
                                id=row_id).run(cursor)
Example #8
0
    async def on_message(self, message):
        if message.author.bot or message.content[:1] not in '+-' or \
                message.channel.id != self.bot.config.bot.channel.bot_commands:
            return

        sign = message.content[:1]
        specified_tag = message.content[1:]
        if specified_tag == "":
            return

        # Check if tag exists in database
        with self.cursor_context() as cursor:
            cursor.execute(
                *db_util.select("tags").items("name", "channel").limit(1).
                where(id_server=message.guild.id, name=specified_tag).build)
            row = cursor.fetchone()

        if not row:
            await message.channel.send(
                'The tag **{}** does not exist, {}.'.format(
                    specified_tag, message.author.mention))
            return

        tag_name = row[0]
        tag_role = discord.utils.get(message.guild.roles, name=tag_name)
        if tag_role is None:
            tag_role = await message.guild.create_role(name=tag_name,
                                                       mentionable=False,
                                                       reason="Tag creation")

        has_role = discord.utils.get(message.author.roles,
                                     id=tag_role.id) is not None
        msg_str = self.on_msg_dict[sign]

        await message.channel.send('{} have the **{}** tag, {}.'.format(
            msg_str["pre"][has_role], tag_role.name, message.author.mention))

        if (has_role and sign == "-") or (not has_role and sign == "+"):
            callback = self.on_msg_dict["method"](message, has_role)
            await callback(tag_role)
Example #9
0
    async def time(self, ctx, user: discord.Member):
        """Displays a user local time"""
        utc = pytz.utc
        time_now = datetime.datetime.utcnow()
        time_now_utc = utc.localize(time_now)

        with self.cursor_context() as cursor:
            cursor.execute(*db_util.select("profiles").items("timezone").where(
                id_user=user.id).build)
            row = cursor.fetchone()

        if not row:
            await ctx.reply(
                f'The user **{user.name}** has not set his timezone')
            return
        tz_name = row[0]

        local_tz = pytz.timezone(tz_name)
        time_now_localized = time_now_utc.astimezone(local_tz)
        time_now_formatted = time_now_localized.strftime('%Y-%m-%d %H:%M:%S')
        await ctx.reply(
            f'**{user.name}**\'s local time is **{time_now_formatted}**')
Example #10
0
 async def on_member_unban(self, guild, user):
     with self.cursor_context(commit=True) as cursor:
         db_util.insert("event_logs").items(id_server=guild.id,
                                            id_user=user.id,
                                            date_utc=DBFunction("NOW()"),
                                            event_type="left").run(cursor)