Skip to main content

Top.gg Python SDK

The community-maintained Python SDK for Top.gg.

Chapters

Installation

$ pip install topggpy

Usage

General API calls

import topgg

from datetime import datetime, timedelta, UTC
import asyncio
import os


async def main():
  async with topgg.ProjectClient(os.getenv('TOPGG_TOKEN')) as client:
    project = await client.get_project()
    print(project)

    votes = await client.get_votes(since=datetime.now(UTC) - timedelta(hours=1))
    for vote in votes:
      print(vote)

    vote = await client.get_vote(661200758510977084, topgg.UserSource.DISCORD)
    print(vote)

    await client.post_announcement(
      'My project announcement',
      'Lorem ipsum' * 25,
      topgg.AnnouncementCategory.ANNOUNCEMENT,
    )

    # Array of application commands that
    # can be serialized to Discord API's raw JSON format.
    await client.post_commands(
      [
        {
          'id': '1',
          'type': 1,
          'application_id': '1',
          'name': 'test',
          'description': 'command description',
          'default_member_permissions': '',
          'version': '1',
        }
      ]
    )

    await client.post_metrics(topgg.DiscordBotMetrics(server_count=5))

    headline = topgg.LocaleMap(
      {
        topgg.Locale.ENGLISH: 'hello this is a headline',
        topgg.Locale.GERMAN: 'hallo das ist eine Überschrift',
      }
    )

    page_content = topgg.LocaleMap(
      {
        topgg.Locale.ENGLISH: 'hello this is a page content' * 20,
        topgg.Locale.GERMAN: 'hallo dies ist ein seiteninhalt' * 20,
      }
    )

    await client.edit_project(headline, page_content)

    metrics = topgg.TimestampedMetrics[topgg.DiscordBotMetrics]()
    now = datetime.now(UTC)

    metrics.add(now - timedelta(hours=3), topgg.DiscordBotMetrics(server_count=5))
    metrics.add(now - timedelta(hours=2), topgg.DiscordBotMetrics(server_count=6))
    metrics.add(now - timedelta(hours=1), topgg.DiscordBotMetrics(server_count=7))

    await client.post_timestamped_metrics(metrics)


if __name__ == '__main__':
  asyncio.run(main())

aiohttp Webhooks

import topgg

from aiohttp import web
import asyncio
import signal
import json
import os


async def handle_webhooks(request: web.Request) -> web.Response:
  if 'x-topgg-signature' in request.headers and request.can_read_body:
    body = (await request.read()).decode('utf-8')

    if topgg.webhooks.verify(
      os.getenv('TOPGG_WEBHOOKS_SECRET'), request.headers['x-topgg-signature'], body
    ):
      payload = topgg.webhooks.parse(json.loads(body))
      print(payload)

      return web.Response(status=200, text='OK')

  return web.Response(status=401, text='Unauthorized')


async def main() -> None:
  app = web.Application()

  app.add_routes([web.post('/webhooks', handle_webhooks)])

  runner = web.AppRunner(app)

  await runner.setup()

  site = web.TCPSite(runner, 'localhost', 3000)

  await site.start()

  stop_event = asyncio.Event()
  loop = asyncio.get_running_loop()

  signal.signal(signal.SIGINT, lambda _, __: loop.call_soon_threadsafe(stop_event.set))

  try:
    await stop_event.wait()
  finally:
    await runner.cleanup()


if __name__ == '__main__':
  asyncio.run(main())

aiohttp Oauth2

import topgg

from aiohttp import web
import asyncio
import signal
import os


async def handle_oauth2(request: web.Request) -> web.Response:
  if (
    'code' in request.query
    and 'state' in request.query
    and f'oauth2_url:{request.query["state"]}' in request.app
  ):
    oauth2: topgg.Oauth2 = request.app['oauth2']
    oauth2_url: topgg.Oauth2URL = request.app[f'oauth2_url:{request.query["state"]}']

    try:
      session = await oauth2_url.exchange(request.query['code'])
      client = oauth2.new_client(session)

      projects = await client.get_projects()
      integrations = await client.get_integrations(364806029876555776)
      webhooks = await client.get_webhooks(364806029876555776)

      user = await client.get_authorized_user()
      user_projects = await client.get_authorized_user_projects()

      return web.Response(
        status=200,
        text=f'Projects: {projects!r}\n'
        + f'Integrations: {integrations!r}\n'
        + f'Webhooks: {webhooks!r}\n\n'
        + f'User: {user!r}\n'
        + f'User projects: {user_projects!r}',
      )
    except Exception as err:
      print(err)
      pass

  return web.Response(status=401, text='Unauthorized')


async def main() -> None:
  app = web.Application()

  oauth2 = topgg.Oauth2(
    os.getenv('TOPGG_CLIENT_ID'),
    os.getenv('TOPGG_CLIENT_SECRET'),
    'http://localhost:3000/topgg/oauth2',
    [
      'user.identify',
      'user.projects.read',
      'user.projects.write',
      'project.information.read',
      'project.information.write',
      'project.votes.read',
      'project.metrics.write',
      'project.announcements.write',
      'project.webhooks.read',
      'project.webhooks.write',
      'project.integrations.read',
      'project.integrations.write',
    ],
  )

  url = oauth2.new_url()
  print('Please open this URL:', url)

  app['oauth2'] = oauth2
  app[f'oauth2_url:{url.state}'] = url

  app.add_routes([web.get('/topgg/oauth2', handle_oauth2)])

  runner = web.AppRunner(app)

  await runner.setup()

  site = web.TCPSite(runner, 'localhost', 3000)

  await site.start()

  stop_event = asyncio.Event()
  loop = asyncio.get_running_loop()

  signal.signal(signal.SIGINT, lambda _, __: loop.call_soon_threadsafe(stop_event.set))

  try:
    await stop_event.wait()
  finally:
    await runner.cleanup()
    await oauth2.close()


if __name__ == '__main__':
  asyncio.run(main())

Metadata

Release files for topggpy 2.0.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for topggpy 2.0.0
File Size Uploaded Provenance Actions
topggpy-2.0.0.tar.gz 20.8 kB With provenance Details for topggpy-2.0.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for topggpy 2.0.0
File Interpreter ABI Platform Actions
topggpy-2.0.0-py3-none-any.whl Python 3 none any Details for topggpy-2.0.0-py3-none-any.whl

Total release size: 42.2 kB

Release files / topggpy-2.0.0.tar.gz

Download URL topggpy-2.0.0.tar.gz
Size 20.8 kB
Tags Source
SHA-256 checksum
How to use checksums
6c957b4b853a5d750a8003ddfe1f3c8837a51d9e4208b369bc69287b25fd0078
BLAKE2b-256 checksum
How to use checksums
e4cafed07cca5976dc47a2b2b99a84e17136aae2a1554ad64dab4268064c2f76
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 23, 2026.

Transparency log

Release files / topggpy-2.0.0-py3-none-any.whl

Download URL topggpy-2.0.0-py3-none-any.whl
Size 21.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
1dded19d9fc7fe54a18056337e35e43f1399a0b7e9bae8d0809242d541dce039
BLAKE2b-256 checksum
How to use checksums
51c35ff063b5cda7b2dae65fda3df4321db70058d9dfaeb889269e5aacde5b41
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 23, 2026.

Transparency log

Security for topggpy 2.0.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for topggpy-2.0.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 23, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page