Adding Prometheus Metrics to Your Discord Bot

By Apollo-Roboto | Published ()

Python Discord Prometheus Grafana Library PyPi Analytics Bot Extension Metrics Open Source

discord-ext-prometheus is an extension library I made to make it easy to add Prometheus metrics to your Discord bots. It also supports sharding for larger bots.

Prometheus is a popular open-source monitoring and alerting system. It allows users to collect and store metrics from their applications and infrastructure, and then visualize and analyse those metrics using tools like Grafana.

Here are the exposed metrics:

NameDocumentationLabels
discord_connectedDetermines if the bot is connected to Discordshard
discord_latencyLatency to Discordshard
discord_event_on_interactionAmount of interactionsshard, interaction, command
discord_event_on_commandAmount of commandsshard, command
discord_stat_total_guildsAmount of guild this bot is a member ofNone
discord_stat_total_channelsAmount of channels this bot is has access toNone
discord_stat_total_usersAmount of users this bot can seeNone
discord_stat_total_commandsAmount of commandsNone
loggingLog entrieslogger, level

Installation

To use this extension, simply install it via pip:

python -m pip install discord-ext-prometheus

Then, in your bot’s code, you can import and add the discord.ext.prometheus Cog to the bot using bot.add_cog(). Here is an example:

import asyncio
from discord.ext import commands
from discord.ext.prometheus import PrometheusCog

async def main():
	bot = commands.Bot(
		command_prefix='!',
		intents=Intents.all(),
	)

	await bot.add_cog(PrometheusCog(bot))

	await bot.start('YOUR TOKEN')

asyncio.run(main())

Once the cog is added, the metrics will be exposed at localhost:8000/metrics.

It’s also possible to add logging metrics if you need to visualize warnings and errors. To do so, import the LoggingHandler and add it to your logger handlers. Here is an example with a simple bot:

import asyncio
import logging
from discord.ext import commands
from discord.ext.prometheus import PrometheusCog, PrometheusLoggingHandler

logging.basicConfig(level=logging.INFO)
logging.getLogger().addHandler(PrometheusLoggingHandler())

async def main():
	bot = commands.Bot(
		command_prefix='!',
		intents=Intents.all(),
	)

	await bot.add_cog(PrometheusCog(bot))

	@bot.listen()
	async def on_ready():
		logging.info(f'Logged in as {bot.user.name}#{bot.user.discriminator}')

	logging.info('Starting the bot')
	await bot.start('YOUR TOKEN')

asyncio.run(main())

Grafana

I also made a Grafana dashboard that uses those metrics. It’s available for free on Grafana Dashboards.

Grafana Preview

GitHub Icon

Copyright © 2024 | Apollo-Roboto

Powered by Github Pages, Hugo and Tailwindcss