Esempio n. 1
0
    async def stats(self, ctx):
        if not util.check_ratelimiting(ctx):
            return
            
        process = psutil.Process(os.getpid())
        uptime = time.time() - start_time

        cur = db.get_cursor()
        db.execute(cur, 'SELECT * FROM stats')

        row = cur.fetchone()
        result = dict(row)

        result['memory_usage'] = "{:.3f} MB".format(process.memory_info().rss / 1024 / 1024)
        result['database_size'] = "{:.3f} MB".format(os.path.getsize(config.DB_PATH) / 1024 / 1024)
        result['uptime'] = to_hhmmss(uptime)

        embed = discord.Embed(title='Bot Statistics', colour=0x3498DB)
        embed.set_thumbnail(url=self.bot.user.avatar_url)

        for col in result:
            val = result[col]
            valstr = str(result[col])
            if isinstance(val, int):
                valstr = f'{val:,}'

            embed.add_field(name=str(col), value=valstr, inline=True)

        await ctx.send(embed=embed)
Esempio n. 2
0
    async def quote(self, ctx, id=-1):
        if not util.check_ratelimiting(ctx):
            return

        with ctx.typing():
            cur = db.get_cursor()

            # specific quote id
            if id != -1:
                db.execute(cur, 'SELECT * FROM quotes WHERE id=? LIMIT 1', (id,))
            # random quote
            else:
                db.execute(cur, 'SELECT * FROM quotes ORDER BY RANDOM() LIMIT 1')

            row = cur.fetchone()

            if row is None:
                await ctx.reply('There is no quote with ID ' + str(id))
            else:
                user = self.bot.get_user(int(row["submitter"]))
                username = row["submitter_name"]
                if not user is None:
                    username = user.name

                speaker = self.get_speaker(row["speaker"])
                dt = datetime.datetime.utcfromtimestamp(row["date"] / 1000)
                embed = discord.Embed(title='Quote #' + str(row["id"]), colour=0xFFFFFF, description=row["text"],
                                      timestamp=dt)
                embed.set_author(name=speaker["name"], icon_url=speaker["picture_url"],
                                 url="http://bot.montclairpublicaccess.info/quotes.php")
                embed.set_footer(text="Submitted by " + username)
                await ctx.reply(embed=embed)
Esempio n. 3
0
    async def identicon(self, ctx, *, args=None):
        if not util.check_ratelimiting(ctx):
            return

        name = ctx.author.name
        if args is not None:
            name = args

        hash = hashlib.sha256(name.encode()).hexdigest()

        app = '/identicon/' + hash + '.png'
        url = config.WWWDATA_URL + app
        path = os.path.realpath(config.WWWDATA_PATH + app)
        if not os.path.isfile(path):
            img = self.generator.generate(name, 250, 250, output_format="png")

            with open(path, "wb") as f:
                f.write(img)

        embed = discord.Embed(title="Identicon for `" + name + "`",
                              colour=0xFFE97F,
                              description=url)
        embed.set_image(url=url)

        await ctx.send(embed=embed)
Esempio n. 4
0
    async def sentencestats(self, ctx):
        if not util.check_ratelimiting(ctx):
            return

        embed = discord.Embed(title="Stats")
        embed.add_field(name="Root Words", value=f'{len(self.obkov.words):,}')
        embed.add_field(name="Last Generation Duration", value=f'{self.obkov.last_generation_duration * 1000:.3f} ms')
        embed.add_field(name="Database Size", value=f'{os.path.getsize(config.OBKOV_PATH) / 1024:.3f} kB')

        await ctx.send(embed=embed)
Esempio n. 5
0
    async def urbandictionary(self, ctx, *words):
        if not util.check_ratelimiting(ctx):
            return

        if len(words) < 1:
            await ctx.send_help(ctx.command)
            return

        async with ctx.typing():
            start = time.time()
            phrase = ' '.join(words)
            url = "https://api.urbandictionary.com/v0/define?term=" + urllib.parse.quote(
                phrase)

            try:
                r = requests.get(url)
                json = r.json()
                list = json['list']

                if len(list) < 1:
                    await ctx.reply("No results for `" + phrase + "`")
                    return

                definition = list[0]
                text = self.parse_definition(definition['definition'])
                example = self.parse_definition(definition['example'])

                timestamp = parser.parse(definition['written_on'])

                embed = discord.Embed(title=definition['word'],
                                      url=definition['permalink'],
                                      timestamp=timestamp,
                                      color=self.get_word_colour(
                                          definition['defid']))
                embed.add_field(name="Definition", value=text, inline=False)
                if example:
                    embed.add_field(name="Example",
                                    value=example,
                                    inline=False)
                embed.set_footer(
                    text=
                    f"Definition #{definition['defid']} • � {definition['thumbs_up']:,} / 👎 {definition['thumbs_down']:,} • Submitted by {definition['author']}"
                )

                end = time.time()
                delta = end - start
                if delta < 0.5:
                    await asyncio.sleep(0.5 - delta)

                await ctx.reply(embed=embed)
            except Exception as e:
                await ctx.reply("Failed to look up `" + phrase + "`: " +
                                str(e))
Esempio n. 6
0
    async def quotestats(self, ctx):
        if not util.check_ratelimiting(ctx):
            return

        cur = db.get_cursor()
        db.execute(cur, 'SELECT COUNT(id) FROM quotes')
        row = cur.fetchone()

        if not row:
            await ctx.send('Failed to get stats')
            return

        embed = discord.Embed(title="Quote Database Statistics", color=0x1ABC9C)
        embed.add_field(name="Number of quotes", value=row[0])

        await ctx.send(embed=embed)
Esempio n. 7
0
    async def sentence(self, ctx, root_word=None):
        if not util.check_ratelimiting(ctx):
            return

        with ctx.typing():
            message = self.obkov.generate_sentence(root_word)

            if self.obkov.last_generation_duration < WAIT_TIME:
                await asyncio.sleep((WAIT_TIME - self.obkov.last_generation_duration) / 1000)

            if message is None and root_word is not None:
                await ctx.reply(f'I have nothing to say about "{root_word}".')
                return

            if message:
                if len(message) > 1950:
                    message = message[:1950]
                    message += "..."

                await ctx.reply(message)
Esempio n. 8
0
    async def sex(self, ctx):
        if not util.check_ratelimiting(ctx):
            return

        await ctx.reply(random.choice([
            "Abstinence is good for the soul", "Pre-marital sex is a sin.",
            "No.",
            "Why don't you go abuse <@115424328576663557>'s styrofoam hole instead",
            "<@&739564035648782487>s please help",
            "No. Go read the Neon Bible instead.", "SINNER!",
            f"NO! EVERYONE SHAME {ctx.author.mention}",
            "I am currently being attacked by a swarm of bees. Please try again later.",
            "I'm only 3 years old...",
            "Sorry, you look too much like Dan Schneider"
        ]),
                        allowed_mentions=discord.AllowedMentions(
                            everyone=False,
                            users=[ctx.author],
                            roles=False,
                            replied_user=True))
Esempio n. 9
0
    async def editquote(self, ctx):
        if not util.check_ratelimiting(ctx):
            return

        await ctx.reply("Please use the website to edit quotes: <http://bot.montclairpublicaccess.info/quotes.php>")