Exemplo n.º 1
0
    async def channel_pie(self, ctx, channel: discord.TextChannel):
        if (ctx.author.id != 141695444995670017):
            return
        await ctx.send("Generating graph of channel message distribution.")
        # Graph generation!
        fig = pyplot.figure(num=None, figsize=(16, 6), dpi=100)
        fig.patch.set_alpha(1)
        fig.patch.set_facecolor('#DEB887')
        fig.tight_layout()
        ax = fig.add_subplot(1, 1, 1)
        session = self.Session()
        await validate_serverdb(session, ctx.guild)
        message_query = session.query(Channeldb).filter_by(
            id=channel.id).first().messages.filter_by(
                channel_id=channel.id).order_by(asc(Messagedb.date))
        member_stat_dict = {}
        print("Beginning message analysis.")
        bar = IncrementalBar(
            "Processing",
            max=message_query.count(),
            suffix=
            f"Elapsed: %(elapsed)ds - %(percent).1f%% - %(remaining)d left - %(eta)ds remaining"
        )
        bar.check_tty = False
        start = time.perf_counter()
        for message in message_query:
            member_id = message.author.first().id
            member_name = discord.utils.get(ctx.guild.members, id=member_id)
            if member_name is None:
                continue
            if member_stat_dict.get(member_name) is None:
                member_stat_dict[member_name] = 1
            else:
                member_stat_dict[
                    member_name] = member_stat_dict[member_name] + 1
            bar.next()
        end = time.perf_counter()
        print(f"\nMessage analysis finished in {end-start:0.4f} seconds.")
        sorted_dict = sorted(member_stat_dict.items(),
                             key=operator.itemgetter(1))
        names, count = zip(*sorted_dict)
        fig1, ax = pyplot.subplots()
        ax.set_facecolor('#FFFDD0')
        ax.pie(count,
               labels=names,
               autopct='%1.1f%%',
               shadow=True,
               startangle=90,
               rotatelabels=True)
        ax.axis('equal'
                )  # Equal aspect ratio ensures that pie is drawn as a circle.
        pyplot.savefig("graph.png", facecolor=fig.get_facecolor())

        raw_graph = open('graph.png', 'rb')
        photo = discord.File(fp=raw_graph, filename="graph.png")
        await ctx.send(file=photo)
        raw_graph.close()