POST Discord Bot Stats to discordbotlist.com with aiohttp

Free lines Python 5 revisions 485 a year ago 10 months ago
import json
import aiohttp
from discord.ext.commands import Cog, Bot

# To see this in action, check here:
# https://discordbotlist.com/bots/492873992982757406

class DiscordBotListComAPI(Cog):
    """Handles interaction with the https://discordbotlist.com API
    You can post:
     - Guild count
     - User count
     - Voice connections

    This even automatically updates the data as your bot joins a new guild!

    def __init__(self, bot: Bot):
        self.bot = bot
        self.token = "xxxxx" # Your token goes here
        self.url = f"https://discordbotlist.com/api/bots/{bot.user.id}/stats"
        self.headers = {"content-type": "application/json", "Authorization": f"Bot {self.token}"}

    # Check for events
    async def on_ready(self):
        """Update on start"""
        await self.post_stats()
    async def on_guild_join(self, guild):
        """Update when joining a guild"""
        await self.post_stats()

    async def on_guild_remove(self, guild):
        """Update when leaving a guild"""
        await self.post_stats()
    # This function creates the ClientSession
    # Must be created in an async function idk don't ask me why
    async def post_stats(self):
        except AttributeError: # not defined yet
            self.http = aiohttp.ClientSession(loop= self.bot.loop)
        payload = json.dumps({
            "guilds": len(self.bot.guilds),
            "users": len(list(self.bot.get_all_members())),
            "voice_connections": len(self.bot.voice_clients)
        await self.poster(payload)

    # Now finally on to the actual poster!
    async def poster(self, payload):
        async with self.http.post(self.url, data= payload, headers= self.headers) as resp:
            response = await resp.text()
            print(f"Discordbotlist.com returned status [{resp.status}]: {response}")

def setup(bot: Bot):

Automatically updates and sends data to https://discordbotlist.com. Uses:

  • Python 3.7.2
  • Discord.py rewrite (commands extension)

See an example of this here