Welcome to topggpy’s documentation!
API Reference
The following section outlines the API of topggpy.
Client
- class topgg.DBLClient(bot: discord.client.Client, token: str, autopost: bool = False, post_shard_count: bool = False, autopost_interval: Optional[float] = None, **kwargs: Any)[source]
Represents a client connection that connects to Top.gg. This class is used to interact with the Top.gg API.
- Parameters
bot (discord.Client) – An instance of a discord.py Client object.
token (str) – Your bot’s Top.gg API Token.
autopost (bool) – Whether to automatically post bot’s guild count every 30 minutes. This will dispatch
on_autopost_success()
(oron_autopost_error()
in case of an error).post_shard_count (bool) – Whether to post the shard count on autopost. Defaults to False.
autopost_interval (Optional[int]) – Interval used by autopost to post server count automatically, measured in seconds. Defaults to 1800 (30 minutes) if autopost is True, otherwise None.
**session (
aiohttp.ClientSession
) – An aiohttp session to use for requests to the API.
- async get_weekend_status() bool [source]
This function is a coroutine.
Gets weekend status from Top.gg.
- Returns
weekend status – The boolean value of weekend status.
- Return type
- async post_guild_count(guild_count: Optional[Union[int, List[int]]] = None, shard_count: Optional[int] = None, shard_id: Optional[int] = None) None [source]
This function is a coroutine.
Posts your bot’s guild count and shards info to Top.gg.
- Parameters
guild_count (Optional[Union[int, List[int]]]) – Number of guilds the bot is in. Applies the number to a shard instead if shards are specified. If not specified, length of provided client’s property .guilds will be posted.
shard_count (Optional[int]) – The total number of shards.
shard_id (Optional[int]) – The index of the current shard. Top.gg uses 0 based indexing for shards.
- async get_guild_count(bot_id: Optional[int] = None) topgg.types.BotStatsData [source]
This function is a coroutine.
Gets a bot’s guild count and shard info from Top.gg.
- Parameters
bot_id (int) – ID of the bot you want to look up. Defaults to the provided Client object.
- Returns
stats – The guild count and shards of a bot on Top.gg.
- Return type
- async get_bot_votes() List[topgg.types.BriefUserData] [source]
This function is a coroutine.
Gets information about last 1000 votes for your bot on Top.gg.
Note
This API endpoint is only available to the bot’s owner.
- Returns
users – Users who voted for your bot.
- Return type
List[BriefUserData]
- async get_bot_info(bot_id: Optional[int] = None) topgg.types.BotData [source]
This function is a coroutine.
Gets information about a bot from Top.gg.
- async get_bots(limit: int = 50, offset: int = 0, sort: Optional[str] = None, search: Optional[Dict[str, Any]] = None, fields: Optional[List[str]] = None) topgg.types.DataDict[str, Any] [source]
This function is a coroutine.
Gets information about listed bots on Top.gg.
- Parameters
- Returns
bots – Info on bots that match the search query on Top.gg.
- Return type
- async get_user_info(user_id: int) topgg.types.UserData [source]
This function is a coroutine.
Gets information about a user on Top.gg.
- async get_user_vote(user_id: int) bool [source]
This function is a coroutine.
Gets information about a user’s vote for your bot on Top.gg.
- async generate_widget(options: topgg.types.WidgetOptions) str [source]
This function is a coroutine.
Generates a Top.gg widget from the provided WidgetOptions object.
- Parameters
options (WidgetOptions) – A WidgetOptions object containing widget parameters.
- Returns
widget – Generated widget URL.
- Return type
Event reference
- topgg.on_autopost_success()
Called when autopost posts server count successfully on Top.gg.
- topgg.on_autopost_error(exception)
Called when autopost raises an exception during server count posting.
- Parameters
exception (Exception) – The raised exception object.
- topgg.on_dbl_vote(data)
Called when someone votes for your bot on Top.gg.
- Parameters
data (BotVoteData) – The data model containing bot vote information.
Example:
@bot.event async def on_dbl_vote(data): print(data)
- topgg.on_dsl_vote(data)
Called when someone votes for your server on Top.gg.
- Parameters
data (ServerVoteData) – The data model containing server vote information.
Example:
@bot.event async def on_dsl_vote(data): print(data)
Data models
This section explains data models used in topggpy to represent data received from Top.gg.
Note
All listed models subclass dict
and allow retrieving data via attributes and keys (i.e., both response['id']
and response.id
are valid).
DataDict
- class topgg.types.DataDict(**kwargs: topgg.types.VT)[source]
Bases:
dict
,MutableMapping
[topgg.types.KT
,topgg.types.VT
]Base class used to represent received data from the API.
Every data model subclasses this class.
BotData
UserData
BriefUserData
BotStatsData
- class topgg.types.BotStatsData(**kwargs: Any)[source]
Bases:
topgg.types.DataDict
[str
,Any
]Model that contains information about a listed bot’s guild and shard count.
VoteDataDict
- class topgg.types.VoteDataDict(**kwargs: Any)[source]
Bases:
topgg.types.DataDict
[str
,Any
]Base model that represents received information from Top.gg via webhooks.
- query: topgg.types.DataDict
Query parameters in DataDict.
BotVoteData
ServerVoteData
- class topgg.types.ServerVoteData(**kwargs: Any)[source]
Bases:
topgg.types.VoteDataDict
Model that contains information about a server vote.
WidgetOptions
- class topgg.types.WidgetOptions(id: Optional[int] = None, format: Optional[str] = None, type: Optional[str] = None, noavatar: bool = False, colors: Optional[Dict[str, int]] = None, colours: Optional[Dict[str, int]] = None)[source]
Bases:
topgg.types.DataDict
[str
,Any
]Model that represents widget options that are passed to Top.gg widget URL generated via
DBLClient.generate_widget()
.- id: Optional[int]
ID of a bot to generate the widget for. Must resolve to an ID of a listed bot when converted to a string.
- colors: Dict[str, int]
A dictionary consisting of a parameter as a key and HEX color (type int) as value.
color
will be appended to the key in case it doesn’t end withcolor
.
Webhooks
Attention
In order for webhooks to work, the port you provide to WebhookManager.run()
must be accessible, meaning your firewall must allow incoming requests to it.
Note
WebhookManager
exposes the internal webserver instance via the WebhookManager.webserver
property.
WebhookManager
- class topgg.WebhookManager(bot: discord.client.Client)[source]
This class is used as a manager for the Top.gg webhook.
Methods
WebhookManager.dbl_webhook()
andWebhookManager.dsl_webhook()
return a modified version of the object, allowing for method chaining.- Parameters
bot (discord.Client) – The Client object that will be utilized by this manager’s webhook(s) to emit events.
- dbl_webhook(route: str = '/dbl', auth_key: str = '') topgg.webhook.WebhookManager [source]
Helper method that configures a route that listens to bot votes.
- Parameters
- Returns
Modified version of the object
- Return type
- dsl_webhook(route: str = '/dsl', auth_key: str = '') topgg.webhook.WebhookManager [source]
Helper method that configures a route that listens to server votes.
- Parameters
- Returns
Modified version of the object
- Return type
- run(port: int) asyncio.Task[None] [source]
Runs the webhook.
- Parameters
port (int) – The port to run the webhook on.
- property webserver: aiohttp.web_app.Application
Returns the internal web application that handles webhook requests.
- Returns
The internal web application.
- Return type
Examples
Helper methods:
import discord
import topgg
bot = discord.Client(...) # Initialize a discord.py client
# WebhookManager helper methods allow method chaining, therefore the lines below are valid
bot.topgg_webhook = topgg.WebhookManager(bot)\
.dbl_webhook("/dbl", "dbl_auth")\
.dsl_webhook("/dsl", "dsl_auth")
Via the webserver
property:
You can utilize the internal aiohttp.web.Application
via the WebhookManager.webserver
property to add custom routes manually.
import discord
import topgg
from aiohttp import web
dbl_auth = "Your DBL Authorization key" # Leave empty to allow all requests
bot = discord.Client(...) # Initialize a discord.py client
async def bot_vote_handler(request):
auth = request.headers.get("Authorization", "") # Default value will be empty string to allow all requests
if auth == dbl_auth:
# Process the vote and return response code 2xx
return web.Response(status=200, text="OK")
# Return code 401 if authorization fails
# 4xx response codes tell Top.gg services not to retry the request
return web.Response(status=401, text="Authorization failed")
bot.topgg_webhook = topgg.WebhookManager(bot)
bot.topgg_webhook.webserver.router.add_post(path="/dbl", handler=bot_vote_handler)
Exceptions
The following exceptions are thrown by the library.
TopGGException
ClientException
- exception topgg.ClientException[source]
Bases:
topgg.errors.TopGGException
Exception that’s thrown when an operation in the
DBLClient
fails.These are usually for exceptions that happened due to user input.
HTTPException
Forbidden
- exception topgg.Forbidden(response: ClientResponse, message: Union[dict, str])[source]
Bases:
topgg.errors.HTTPException
Exception that’s thrown when status code 403 occurs.
NotFound
- exception topgg.NotFound(response: ClientResponse, message: Union[dict, str])[source]
Bases:
topgg.errors.HTTPException
Exception that’s thrown when status code 404 occurs.
ServerError
- exception topgg.ServerError(response: ClientResponse, message: Union[dict, str])[source]
Bases:
topgg.errors.HTTPException
Exception that’s thrown when Top.gg returns “Server Error” responses (status codes such as 500 and 503).
What’s New
This page keeps a detailed human friendly rendering of what’s new and changed in specific versions.
v1.4.0
v1.3.0
Introduced global ratelimiter to follow Top.gg global ratelimits
Fixed an
AttributeError
raised byHTTPClient.request()
Resource-specific ratelimit is now actually resource-specific
v1.2.0
v1.1.0
Introduced data models
DBLClient.get_bot_votes()
now returns a list ofBriefUserData
objectsDBLClient.get_bot_info()
now returns aBotData
objectDBLClient.get_guild_count()
now returns aBotStatsData
objectDBLClient.get_user_info()
now returns aUserData
object
WebhookManager.run()
now returns anasyncio.Task
, meaning it can now be optionally awaited
v1.0.1
WebhookManager.webserver
now instead returnsaiohttp.web.Application
for ease of use
v1.0.0
Renamed the module folder from
dbl
totopgg
Added
post_shard_count
argument toDBLClient.post_guild_count()
Autopost now supports automatic shard posting (GH-42)
Large webhook system rework, read the Webhooks section for more
Added support for server webhooks
Renamed
DBLException
toTopGGException
Renamed
DBLClient.get_bot_upvotes()
toDBLClient.get_bot_votes()
Added
DBLClient.generate_widget()
along with thewidgets
section in the documentationImplemented a properly working ratelimiter
Added
on_autopost_error()
All autopost events now follow
on_autopost_x
naming format, e.g.on_autopost_error()
,on_autopost_success()
Added handlers for autopost args set when autopost is disabled
v0.4.0
DBLClient.post_guild_count()
now supports a customguild_count
argument, which accepts either an integer or list of integersReworked how shard info is posted
Removed
InvalidArgument
andConnectionClosed
exceptionsAdded
ServerError
exception
v0.3.3
Internal changes regarding support of Top.gg migration
Fixed errors raised when using
DBLClient.close()
without built-in webhook
v0.3.2
Client
class has been renamed toDBLClient
v0.3.1
Added
on_guild_post
, an event that is called when autoposter successfully posts guild countRenamed
get_upvote_info
toget_bot_upvotes
Added
get_user_vote
v0.3.0
DBLClient
now hasautopost
kwarg that will post server count automatically every 30 minutesFixed code 403 errors
Added
on_dbl_vote
, an event that is called when you test your webhookAdded
on_dbl_test
, an event that is called when someone tests your webhook
v0.2.1
Added webhook
Removed support for discord.py versions lower than 1.0.0
Made
DBLClient.get_weekend_status()
return a boolean valueAdded webhook example in README
Removed
post_server_count
andget_server_count
v0.2.0
Added
post_guild_count
Made
post_server_count
an alias forpost_guild_count
Added
get_guild_count
Made
get_server_count
an alias forget_guild_count
Removed all parameters from
DBLClient.get_upvote_info()
Added limit to
DBLClient.get_bots()
Fixed example in README
v0.1.6
Bug fixes & improvements
v0.1.4
Initial ratelimit handling
v0.1.3
Added documentation
Fixed some minor bugs
v0.1.2
Initial release
Working
POSTing server count
GET bot info, server count, upvote count, upvote info
GET all bots
GET specific user info
GET widgets (large and small) including custom ones. See Top.gg docs for more info.
Not Working / Implemented
Searching for bots via the api
SocialData
Bases:
topgg.types.DataDict
[str
,str
]Model that contains social information about a top.gg user.
The YouTube channel ID of the user.
The Reddit username of the user.
The Twitter username of the user.
The Instagram username of the user.
The GitHub username of the user.