These developer pages document how to use our API to help you create and grow awesome bots for your community!
These developer pages document how to use our API to help you create and grow awesome bots for your community!
If you need some help or think you have spotted a problem with our API you can talk to us in our #api channel in our discord server. In the server you can ask questions about our official API Libraries or general queries about the API.
Our API is a HTTPS/REST for general operations such as sending POST requests and receiving GET requests
Base URL |
---|
https://top.gg/api |
To access our API you need to authorize yourself, this can be done by using your discord bot list token. Your token can be obtained from the My Bots page.
Authentication is performed with the Authorization
HTTP header in the format Authorization: TOKEN
Example Authorization Header | |
---|---|
Authorization: | eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjI2NDgxMTYxMzcwODc0Njc1MiIsImJvdCI6dHJ1ZSwiaWF0IjoxNDgzMDk5MjAwfQ.8tpNASxdSsfkVF7YparhyV1Ouy5ORQ3AM2jitd_Y-PI |
We currently have three different official libraries to help you save time in your bot!
We currently don't endorse any unofficial libraries for the API, but if you think you could contribute to our current libraries check out our github repos and maybe submit a PR. If you think we should endorse your unofficial library for a language we don't already support hit us up at [email protected]
or DM a Website Administrator
This is our official JavaScript Library for top.gg, if you have any issues please submit an issue on our github.
npm install dblapi.js
Example of posting server count with supported libraries (Discord.js and Eris)
const Discord = require("discord.js"); const client = new Discord.Client(); const DBL = require("dblapi.js"); const dbl = new DBL('Your top.gg token', client); // Optional events dbl.on('posted', () => { console.log('Server count posted!'); }) dbl.on('error', e => { console.log(`Oops! ${e}`); })
Example of using webhooks to receive vote updates
const DBL = require('dblapi.js'); const dbl = new DBL(yourDBLTokenHere, { webhookPort: 5000, webhookAuth: 'password' }); dbl.webhook.on('ready', hook => { console.log(`Webhook running at http://${hook.hostname}:${hook.port}${hook.path}`); }); dbl.webhook.on('vote', vote => { console.log(`User with ID ${vote.user} just voted!`); });
new DBL(token, [options], [client])
or
new DBL(token, [client])
Arguments | ||||
---|---|---|---|---|
Parameter | Type | Optional | Default | Description |
token | String | No | Your bot's top.gg token. Obtainable from the My Bots page. | |
options | Object | Yes | {} |
DBL client options listed below |
options.statsInterval | Number | Yes | 1800000 (30 minutes) |
How often the autoposter should post stats in ms. May not be smaller than 900000 (15 minutes). |
options.webhookPort | Number | Yes | The port to run the webhook on. Will activate webhook when set. | |
options.webhookAuth | String | Yes | The string for Authorization you set on the site for verification. | |
options.webhookPath | String | Yes | '/dblwebhook' |
The path for the webhook request. |
options.webhookServer | http.Server | Yes | An existing server to run the webhook on. Will activate webhook when set. | |
client | Client | Yes | A discord.js or Eris client. If set, the module will automatically handle posting of the bot's server count. |
If you don't have options to set but want to set the client. You can put the client where options are.
.postStats(serverCount, [shardId], [shardCount])
Post Stats to Discord Bot List.
Arguments | |||
---|---|---|---|
Parameter | Type | Optional | Description |
serverCount | Number | No | The server count of your bot. |
shardId | Number | Yes | The ID of this shard. |
shardCount | Number | Yes | The count of all shards of your bot. |
Returns: Promise
Example
client.on('ready', () => { setInterval(() => { dbl.postStats(client.guilds.size, client.shards.Id, client.shards.total); }, 1800000); });
.getStats(id)
Gets stats from a bot. See more: Get Bot's Stats
Arguments | ||||
---|---|---|---|---|
Parameter | Type | Optional | Default | Description |
id | Snowflake | Yes | The ID of the current bot (requires client to be set) | The ID of the bot you want to get the stats from. |
Returns: Promise<Object>
Example
dbl.getStats("264811613708746752").then(stats => { console.log(stats) // {"server_count":2,"shards":[]} });
.getBot(id)
Gets information about a bot. See more: Get Bot
Arguments | ||||
---|---|---|---|---|
Parameter | Type | Optional | Default | Description |
id | Snowflake | Yes | The ID of the current bot (requires client to be set) | The ID of the bot you want to get the information from. |
Returns: Promise<Object>
Example
dbl.getBot("264811613708746752").then(bot => { console.log(bot.username) // "Luca" });
.getUser(id)
Gets information about a user. See more: Get User
Arguments | ||||
---|---|---|---|---|
Parameter | Type | Optional | Description | |
id | Snowflake | No | The ID of the user you want to get the information from. |
Returns: Promise<Object>
Example
dbl.getUser("95579865788456960").then(user => { console.log(user.username) // "Tonkku" });
.getBots([query])
Gets a list of bots matching your query. See more: Get Bots
Arguments | ||||
---|---|---|---|---|
Parameter | Type | Optional | Default | Description |
query | Object | Yes | {} |
The query for the search. |
query.limit | Number | Yes | 50 | The amount of bots to return. Max. 500 |
query.offset | Number | Yes | 0 | Amount of bots to skip |
query.search | String | Yes | A search string in the format of field: value field2: value2 |
|
query.sort | String | Yes | The field to sort by. Prefix with - to reverse the order |
|
query.fields | String | Yes | All fields | A comma separated list of fields to show. |
Returns: Promise<Object>
Example
dbl.getBots({sort: 'points', limit: 5}).then(bots => { console.log(bots.results.length) // 5 console.log(bots.results[0].username) // "Pokécord" });
.getVotes()
Gets votes from your bot. See more: Get Bot's Last 1000 Votes
Returns: Promise<Object>
Example
dbl.getVotes().then(votes => { if (votes.find(vote => vote.id == "95579865788456960")) console.log("Tonkku has voted!!!") });
.hasVoted(id)
Returns true if a user has voted for your bot in the last 12h. See more: Individual User Id Voting Check for the past 12 hours.
Arguments | ||||
---|---|---|---|---|
Parameter | Type | Optional | Description | |
id | Snowflake | No | The ID of the user to check for. |
Returns: Promise<Boolean>
Example
dbl.hasVoted("95579865788456960").then(voted => { if (voted) console.log("Tonkku has voted!!!") });
.isWeekend()
Returns true if the weekend multiplier is currently active. See more: Voting Multiplier
Returns: Promise<Boolean>
Example
dbl.isWeekend().then(weekend => { if (weekend) console.log("Woo! Multiplier time!") });
posted
Emitted when the stats have been posted successfully by the autoposter.
Example
dbl.webhook.on('posted', () => { console.log('Server count posted!'); });
error
Emitted when the autoposter post request failed.
Example
dbl.webhook.on('error', e => { console.log(`Oops! ${e}`); });
ready
Emitted when the webhook is ready to listen.
Parameters | ||||
---|---|---|---|---|
Parameter | Type | Description | ||
hostname | String | The hostname of the webhook server | ||
port | Number | The port the webhook server is running on | ||
path | String | The path for the webhook |
Example
dbl.webhook.on('ready', hook => { console.log(`Webhook running at http://${hook.hostname}:${hook.port}${hook.path}`); });
vote
Emitted when the webhook has received a vote.
Parameters | ||||
---|---|---|---|---|
Parameter | Type | Description | ||
bot | Snowflake | Id of the bot that was voted for. | ||
user | Snowflake | Id of the user that voted. | ||
type | String | Type of the vote. Is always "upvote" except when using the test button it's "test". | ||
isWeekend | Boolean | Whether the weekend multiplier is in effect, meaning users votes count as two. | ||
query | Object | The possible querystring parameters from the vote page. |
Example
dbl.webhook.on('vote', vote => { console.log(`User with ID ${vote.user} just voted!`); });
Example of linking webhooks with an existing http server (like express)
const DBL = require('dblapi.js'); const express = require('express'); const http = require('http'); const app = express(); const server = http.createServer(app); const dbl = new DBL(yourDBLTokenHere, { webhookAuth: 'password', webhookServer: server }); dbl.webhook.on('ready', hook => { console.log(`Webhook running with path ${hook.path}`); }); dbl.webhook.on('vote', vote => { console.log(`User with ID ${vote.user} just voted!`); }); app.get('/', (req, res) => { // ... }); server.listen(5000, () => { console.log('Listening'); });
We currently don't endorse any unofficial libraries for the API, but if you think you could contribute to our current libraries check out our github repos and maybe submit a PR. If you think we should endorse your unofficial library for a language we don't already support hit us up at [email protected]
or DM a Website Administrator
We currently don't endorse any unofficial libraries for the API, but if you think you could contribute to our current libraries check out our github repos and maybe submit a PR. If you think we should endorse your unofficial library for a language we don't already support hit us up at [email protected]
or DM a Website Administrator
This is our official Python Library for top.gg, if you have any issues please submit an issue on our github.
Install via pip (recommended)
pip install dblpy
Install from source
git clone https://github.com/DiscordBotList/DBL-Python-Library cd DBL-Python-Library pip install -R requirements.txt
Example with automatic server count
import dbl import discord from discord.ext import commands class TopGG(commands.Cog): """Handles interactions with the top.gg API""" def __init__(self, bot): self.bot = bot self.token = 'dbl_token' # set this to your DBL token self.dblpy = dbl.DBLClient(self.bot, self.token, autopost=True) # Autopost will post your guild count every 30 minutes async def on_guild_post(): print("Server count posted successfully") def setup(bot): bot.add_cog(TopGG(bot))
Example with manual server count
import dbl import discord from discord.ext import commands, tasks import asyncio import logging class TopGG(commands.Cog): """Handles interactions with the top.gg API""" def __init__(self, bot): self.bot = bot self.token = 'dbl_token' # set this to your DBL token self.dblpy = dbl.DBLClient(self.bot, self.token) # The decorator below will work only on discord.py 1.1.0+ # In case your discord.py version is below that, you can use self.bot.loop.create_task(self.update_stats()) @tasks.loop(minutes=30.0) async def update_stats(self): """This function runs every 30 minutes to automatically update your server count""" logger.info('Attempting to post server count') try: await self.dblpy.post_guild_count() logger.info('Posted server count ({})'.format(self.dblpy.guild_count())) except Exception as e: logger.exception('Failed to post server count\n{}: {}'.format(type(e).__name__, e)) # if you are not using the tasks extension, put the line below await asyncio.sleep(1800) def setup(bot): global logger logger = logging.getLogger('bot') bot.add_cog(TopGG(bot))
Example with manual server count and webhook
import dbl import discord from discord.ext import commands, tasks import asyncio import logging class TopGG(commands.Cog): """Handles interactions with the top.gg API""" def __init__(self, bot): self.bot = bot self.token = 'dbl_token' # set this to your DBL token self.dblpy = dbl.DBLClient(self.bot, self.token, webhook_path='/dblwebhook', webhook_auth='password', webhook_port=5000) # The decorator below will work only on discord.py 1.1.0+ # In case your discord.py version is below that, you can use self.bot.loop.create_task(self.update_stats()) @tasks.loop(minutes=30.0) async def update_stats(self): """This function runs every 30 minutes to automatically update your server count""" logger.info('Attempting to post server count') try: await self.dblpy.post_guild_count() logger.info('Posted server count ({})'.format(self.dblpy.guild_count())) except Exception as e: logger.exception('Failed to post server count\n{}: {}'.format(type(e).__name__, e)) # if you are not using the tasks extension, put the line below await asyncio.sleep(1800) @commands.Cog.listener() async def on_dbl_vote(self, data): logger.info('Received an upvote') print(data) def setup(bot): global logger logger = logging.getLogger('bot') bot.add_cog(TopGG(bot))
We currently don't endorse any unofficial libraries for the API, but if you think you could contribute to our current libraries check out our github repos and maybe submit a PR. If you think we should endorse your unofficial library for a language we don't already support hit us up at [email protected]
or DM a Website Administrator
User Structure | |||
---|---|---|---|
Field | Type | Description | |
id | Snowflake | The id of the user | |
username | String | The username of the user | |
discriminator | String | The discriminator of the user | |
avatar? | String | The avatar hash of the user's avatar | |
defAvatar | String | The cdn hash of the user's avatar if the user has none | |
bio? | String | The bio of the user | |
banner? | String | The banner image url of the user | |
social | Object | The social usernames of the user | |
social.youtube? | String | The youtube channel id of the user | |
social.reddit? | String | The reddit username of the user | |
social.twitter? | String | The twitter username of the user | |
social.instagram? | String | The instagram username of the user | |
social.github? | String | The github username of the user | |
color? | String | The custom hex color of the user | |
supporter | Boolean | The supporter status of the user | |
certifiedDev | Boolean | The certified status of the user | |
mod | Boolean | The mod status of the user | |
webMod | Boolean | The website moderator status of the user | |
admin | Boolean | The admin status of the user |
Use this endpoint to gain information about a particular user
GET/users/{user.id}
Bot Structure | |||
---|---|---|---|
Field | Type | Description | |
id | Snowflake | The id of the bot | |
username | String | The username of the bot | |
discriminator | String | The discriminator of the bot | |
avatar? | String | The avatar hash of the bot's avatar | |
defAvatar | String | The cdn hash of the bot's avatar if the bot has none | |
lib | String | The library of the bot | |
prefix | String | The prefix of the bot | |
shortdesc | String | The short description of the bot | |
longdesc? | String | The long description of the bot. Can contain HTML and/or Markdown | |
tags | Array of Strings | The tags of the bot | |
website? | String | The website url of the bot | |
support? | String | The support server invite code of the bot | |
github? | String | The link to the github repo of the bot | |
owners | Array of Snowflakes | The owners of the bot. First one in the array is the main owner | |
guilds | Array of Snowflakes | The guilds featured on the bot page | |
invite? | String | The custom bot invite url of the bot | |
date | Date | The date when the bot was approved | |
certifiedBot | Boolean | The certified status of the bot | |
vanity? | String | The vanity url of the bot | |
points | Number | The amount of upvotes the bot has | |
monthlyPoints | Number | The amount of upvotes the bot has this month | |
donatebotguildid | Snowflake | The guild id for the donatebot setup |
Use this endpoint to gain information about different bots
GET/bots
Query String Params | |||
---|---|---|---|
Field | Type | Description | Default |
limit | Number | The amount of bots to return. Max. 500 | 50 |
offset | Number | Amount of bots to skip | 0 |
search | String | A search string in the format of field: value field2: value2 |
|
sort | String | The field to sort by. Prefix with - to reverse the order |
|
fields | String | A comma separated list of fields to show. | All fields |
Response fields | |||
---|---|---|---|
Field | Type | Description | |
results | Array of bot objects | The matching bots | |
limit | Number | The limit used | |
offset | Number | The offset used | |
count | Number | The length of the results array | |
total | Number | The total number of bots matching your search |
Use this endpoint to gain information about a specific bot
GET/bots/{bot.id}
IF YOU HAVE OVER 1000 VOTES PER MONTH YOU HAVE TO USE THE WEBHOOKS AND CAN NOT USE THIS
Use this endpoint to see who have upvoted your bot
GET/bots/{bot.id?}/votes
returnsAn Array of simple user objects
Use this endpoint to see who have upvoted your bot in the past 12 hours. It is safe to use this even if you have over 1k votes.
GET/bots/{bot.id?}/check
Query String Params | |||
---|---|---|---|
Field | Type | Description | |
userId | Number | User id of the discord user |
{voted: 1}
or {voted: 0}
Use this endpoint to gain information about a specific bot's stats
GET/bots/{bot.id}/stats
Response fields | |||
---|---|---|---|
Field | Type | Description | |
server_count? | Number | The amount of servers the bot is in | |
shards | Array | The amount of servers the bot is in per shard. Always present but can be empty | |
shard_count? | Number | The amount of shards a bot has |
Use this endpoint to post your bot's stats
POST/bots/{bot.id?}/stats
JSON Params | |||
---|---|---|---|
Field | Type | Description | Required |
server_count | Number or Array of Numbers | The amount of servers the bot is in. If an Array it acts like shards |
Yes (or shards ) |
shards | Array of Numbers | The amount of servers the bot is in per shard. | No (unless server_count is not set) |
shard_id | Number | The zero-indexed id of the shard posting. Makes server_count set the shard specific server count | No |
shard_count | Number | The amount of shards the bot has | No |
Widgets are images that can display your bots stats on your own website! On this page we will tell you how to access and customise them.
To use the widget, you can insert the following link as an image into your website / documentation.
https://top.gg/api/widget/:ID.svg
Preview
In this example we use .svg
but it can also be a .png
. We recommend SVG for the best quality. That is an example of the large widget. There are also 5 small widgets which can be generated by editing the URL an example of a small widget is this
https://top.gg/api/widget/owner/:ID.svg
Preview
The /owner/
can be replaced with the following to get the 4 other smaller widgets: status
,upvotes
,servers
and lib
. You can also append a querystring to hide the avatar on the smaller widgets: ?noavatar=true
Preview
The current sections of the widget available for customization are as follows
Widget Querystring Parameters | |||
---|---|---|---|
Parameter | Large Widget | Small Widget | Value |
topcolor | ✓ | Hexadecimal | |
middlecolor | ✓ | Hexadecimal | |
usernamecolor | ✓ | Hexadecimal | |
certifiedcolor | ✓ | Hexadecimal | |
datacolor | ✓ | Hexadecimal | |
labelcolor | ✓ | Hexadecimal | |
highlightcolor | ✓ | Hexadecimal | |
avatarbg | ✓ | Hexadecimal | |
leftcolor | ✓ | Hexadecimal | |
rightcolor | ✓ | Hexadecimal | |
lefttextcolor | ✓ | Hexadecimal | |
righttextcolor | ✓ | Hexadecimal |
Example of Customization
This is an example of changing the colors of the large widget
https://top.gg/api/widget/270904126974590976.svg?usernamecolor=FFFFFF&topcolor=000000
This is a preview of the examples output.
The HTTP API implements a process for limiting and preventing spam requests. API users that regularly hit and ignore the limit will be blocked from our platform. These rate limits are in place to help prevent the abuse and overload of our services.
Rate limits are applied globally on all routes
Rate Limits | |||
---|---|---|---|
Route | Request Type | Requests Allowed Per Minute | Punishment if Exceeded |
/bots/* | ANY | 60 | 1 Hour Block |
If you exceed the set rate limit for the API you will receive a HTTP 429 and be blocked from posting to the API for one hour.
Rate Limit Response Structure | ||
---|---|---|
Field | Type | Description |
retry-after | integer | Indicates how long the timeout period is/when you will be able to send requests again |
IF YOU HAVE OVER 1000 VOTES PER MONTH YOU HAVE TO USE THE WEBHOOKS
Users can currently vote every 12 hours for each bot. The /votes endpoint for your bot (the one you use via getVotes) only indexes the last 1000 votes. Please implement the webhook instead if you plan to process over 1000 votes.
Our current Rules on using our voting API.
Unacceptable use of our API (breaking these rules will result in appropriate punishments):
Acceptable use of our API:
Consequences of breaking these rules:
We reserve the right to not follow these consequences in the exact order they are laid out here and take action how we see fit dependant on the scenario
To help give all bots a better chance to fight for the top spots we are now introducing vote multipliers. Votes count double on the weekend! On Fridays, Saturdays and Sundays, users votes count as two votes each.
Checking if the multiplier is live
Use this endpoint to find out if the multiplier is live so you can increase your bot's voting rewards for the weekend
GET/weekend
Example Response
{is_weekend: true}
Returns in JSON form a bool for the key is_weekend
Here are your bots. You can view your API key here and other neat things!
Log in to view your bots
API Key |
---|
|
Regen token |
Test webhook |
This is our official .NET Library for top.gg, if you have any issues please submit an issue on our github.
Nuget
If you're using Nuget you can use find it with the ID DiscordBotsList.Api
or use
Install-Package DiscordBotsList.Api
Unauthorized API Usage
Setting Up
DiscordBotListApi DblApi = new DiscordBotListApi();
Getting Bots
// discord id IBot bot = DblApi.GetBotAsync(160105994217586689);
Getting Users
// discord id IUser bot = DblApi.GetUserAsync(121919449996460033);
Authorized API Usage
Setting Up
AuthDiscordBotListApi DblApi = new AuthDiscordBotListApi(BOT_DISCORD_ID, YOUR_TOKEN);
Updating Stats
ISelfBot me = await DblApi.GetMeAsync(); // Update stats sharded indexShard shardCount shards await me.UpdateStatsAsync(24, 50, new[] { 12, 421, 62, 241, 524, 534 }); // Update stats guildCount await me.UpdateStatsAsync(2133);
Widgets
string widgetUrl = new SmallWidgetOptions() .SetType(WidgetType.OWNER) .SetLeftColor(255, 255, 255); .Build(160105994217586689);
Generates the following:
We currently don't endorse any unofficial libraries for the API, but if you think you could contribute to our current libraries check out our github repos and maybe submit a PR. If you think we should endorse your unofficial library for a language we don't already support hit us up at [email protected]
or DM a Website Administrator
Instead of requesting our API to see the users who have voted for your bot, we now have webhooks! Webhooks will send a post request to a URL of your choice when your bot has been voted for.
Start by setting up your webhook URL in the edit form of your bot on this site, it can be found at https://top.gg/bot/:ID/edit
once you have entered the URL you want the webhook to be sent to, you're all set! If you need help setting up webhooks inside of your bot don't be afraid to ask in our discord server in our #api channel.
On the edit page you can see another input for "Authorization". Here you shall provide a "password" that you can check for.
To verify requests are coming from us, look for the value in the Authorization
header and make sure it is the same as the value you provided in the form.
The format of the data your webhook URL will receive in a POST request
JSON Params | |||
---|---|---|---|
Field | Type | Description | |
bot | Snowflake | ID of the bot that received a vote | |
user | Snowflake | ID of the user who voted | |
type | String | The type of the vote (should always be "upvote" except when using the test button it's "test") | |
isWeekend | Boolean | Whether the weekend multiplier is in effect, meaning users votes count as two | |
query? | String | Query string params found on the /bot/:ID/vote page. Example: ?a=1&b=2 |