#topgg-api

1 messages ยท Page 14 of 1

sand pendant
#

yes

#

your bot can post to discord

#

if you setup a port for express to work on

#

and top.gg sends the data to your bot which your bot sends to discord

regal minnow
#

I don't think my host allows me to open extra ports

sand pendant
#

why not use the port your bot is running on

regal minnow
#

oh

#

do you dm support I just wanted to know a few more details

sand pendant
#

sure if you want you could dm me

muted verge
#

Is the API down? I keep getting a 502 bad gateway

scarlet cobalt
icy aurora
#

@radiant pasture @silk idol i got question for both of you

silk idol
#

||Insert a joke I just Forgot ||

icy aurora
#

Why i said it here

#

i literally thought this was general

icy aurora
weak karma
#

Server link is down?

icy aurora
weak karma
#

Okey

radiant pasture
#

also this is the wrong channel

icy aurora
#

I thought it was general for sec

scarlet cobalt
#

One message removed from a suspended account.

#

One message removed from a suspended account.

wary ivy
#

When will the website be fixed? There are commands in my bot that require voting, and my bot is not working because it cannot connect to the site.

scarlet cobalt
wary ivy
#

:c

restive otter
#

To integrate the top.gg api, should I use topgg autoposter or sdk?

#

I'm thinking about thanks

runic creek
restive otter
restive otter
#

The site has b.o again, but I wanted to add the topgg bot link to the website, confirm that this is correct please
top.gg/bot/<ID>

tidal idol
#

yes

abstract crown
#

if you regenerate your topgg api token, the old one is invalidated right?

tidal idol
#

yes

abstract crown
#

thanks

tidal aurora
#

TopGGAPIError: 401 Unauthorized (You need a token for this endpoint)
Why this?

scarlet cobalt
#

One message removed from a suspended account.

tidal aurora
#

Ok

tidal aurora
scarlet cobalt
#

One message removed from a suspended account.

#

One message removed from a suspended account.

tidal aurora
#

Ys

scarlet cobalt
#

One message removed from a suspended account.

tidal aurora
#

Check vote it has problem

#

But it is not working

#

Fixed

light basin
#

nor fixed

tight raft
#

yo

#

when i try to put my yt channel

#

it has this channel/ thing

#

that i dont need

solar mist
#

Where do I paste my token to create a new .env file on vsc?

jaunty plank
#

Inside the .env file ๐Ÿ‘€

#

You create the file first, not paste the token to create the file.

solar mist
jaunty plank
#

or right click and click create file

solar mist
#

Thank you @jaunty plank PenguinLove

lapis forge
#

having trouble installing the python-sdk atm

#

installing with pip install -U topggpy seems to work but trying to install from source gets ```
Running command git clone --filter=blob:none --quiet https://github.com/top-gg/python-sdk /tmp/pip-req-build-x31mgezk
Resolved https://github.com/top-gg/python-sdk to commit 06844706605b2d368d6892933f7f1aae45be5dee
Preparing metadata (setup.py) ... error
error: subprocess-exited-with-error

ร— python setup.py egg_info did not run successfully.
โ”‚ exit code: 1
โ•ฐโ”€> [3 lines of output]
error in topggpy setup command: 'install_requires' must be a string or list of strings containing valid project/version requirement specifiers; Expected end or semicolon (after name and no valid version specifier)
https://files.pythonhosted.org/packages/18/93/1f005bbe044471a0444a82cdd7356f5120b9cf94fe2c50c0cdbf28f1258b/aiohttp-3.9.3.tar.gz
^
[end of output]

note: This error originates from a subprocess, and is likely not a problem with pip.
error: metadata-generation-failed

ร— Encountered error while generating package metadata.
โ•ฐโ”€> See above for output.

restive otter
#

does anyone have an example webhook request for bot votes?

jaunty plank
#

The docs do. One sec

restive otter
jaunty plank
#

๐Ÿ‘€
that describes the json object

restive otter
jaunty plank
#
{
"bot": "136583532972605440",
"user": "1213694236319416351",
"type": "upvote",
"isWeekend": true,
"query": "?hi=howareyou&someotherquery=weeee"
}

restive otter
#

ty

vernal isle
lapis forge
#

cool...good to know

vernal isle
reef crow
vestal wasp
reef crow
reef crow
#

How to make an logger that logged vote in a specific channel on discord

vestal wasp
#

make an api endpoint in your bot and add its url in topgg

#

it will then send a post request on every vote

reef crow
#

I am beginner in these things

vestal wasp
#

look at tutorials for your languages of choice on how to setup a http server to handle requests

#

note that you also need to host your bot on a server where you have some IP address

thorny thicket
#

Hi, I'm using this curl to post bot's stats but getting 401, I tried to reset token and use new token as well

curl --location 'https://top.gg/api/bots/<bot_id_here>/stats' \
--header 'Authorization: <token_here>' \
--header 'Content-Type: application/json' \
--header 'Authentication: <token_here>' \
--data '{
    "server_count": 1,
    "shard_count": 1
}'```
solid imp
#

not sure if thats the cause but wont hurt to check

#

also, try making a request using a programming language, if that works, then its prolly your cURL syntax

#

not an expert on that, so you gotta check the docs

subtle widget
#

So I used this API

from discord.ext import tasks

import topgg

# This example uses tasks provided by discord.ext to create a task that posts guild count to Top.gg every 30 minutes.

dbl_token = "Top.gg token"  # set this to your bot's Top.gg token
bot.topggpy = topgg.DBLClient(bot, dbl_token)


@tasks.loop(minutes=30)
async def update_stats():
    """This function runs every 30 minutes to automatically update your server count."""
    try:
        await bot.topggpy.post_guild_count()
        print(f"Posted server count ({bot.topggpy.guild_count})")
    except Exception as e:
        print(f"Failed to post server count\n{e.__class__.__name__}: {e}")


update_stats.start()

It said on my end that it posted the server count, I go to the top.gg page and it hasnt updated?

thorny thicket
solid imp
#

Looks like its working just fine for me now, it couldโ€™ve been a small hiccup in services

thorny thicket
#

Still getting 401 ๐Ÿ˜ฆ

livid jasper
#

hi
I am looking for the blockchain and web dev
plz send me DM, if anyone know well

gaunt steeple
#

not the right place to recruit devs

unkempt hill
#

does topgg have a event listener for new votes?

jaunty plank
#

We have webhooks

restive owl
#

how can i add server count

round sundial
# restive owl how can i add server count
const nodefetch = require('node-fetch');

    
const body = { "server_count": client.guilds.cache.size };

nodefetch(`https://top.gg/api/bots/id/stats`, {
          method: 'POST',
          headers: {
                 "Content-Type": "application/json",
                "Authorization": "token",
            },
          body: JSON.stringify(body),
          }).catch((err) => console.error(`#${cache.index + 1} ${this.name}: ${err.stack}`));```
#

change token with your token and the id in the https with your bot id

icy aurora
reef crow
#

Something here to learn everything about topggpy

restive owl
#

i do understand nodejs

#

and i know how to do it now

#

thanks

round sundial
#

bad*

round sundial
wooden kite
#

Does anyone know how to, got a manual, video tutorial on how to make voting restricted commands

vestal wasp
wooden kite
vestal wasp
#

well, only the top.gg webhook is documented, the other stuff are things you have to find out yourself with your programing language and database

mint cedar
#

could I get support regarding the topggpy library here? and to get the webhook manager working? I'm not able to.

glacial blade
#

hmm how to fix toppggpy webhook error:

#
Error handling request
Traceback (most recent call last):
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python312\Lib\site-packages\aiohttp\web_protocol.py", line 350, in data_received
    messages, upgraded, tail = self._request_parser.feed_data(data)
                               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "aiohttp\\_http_parser.pyx", line 557, in aiohttp._http_parser.HttpParser.feed_data
aiohttp.http_exceptions.BadStatusLine: 400, message:
  Invalid method encountered:

    b'\x03'
      ^
strong rock
#

cgpm

gaunt steeple
jaunty plank
gaunt steeple
#

this isn't windows xp days any more

jaunty plank
#

Your user account doesn't have admin access?

gaunt steeple
#

nobody runs as admin in windows please tell me I'm hallucinating

#

no lol

jaunty plank
#

I actually didn't know that people did that ๐Ÿ‘€

gaunt steeple
#

I put an admin password in to do admin stuff

#

windows can work like sudo if you have separate admin accounts and keep UAC on

#

this is how ms want you to work

#

they just default to moron mode

jaunty plank
#

I'm pretty sure admin is the default

#

Yeah

gaunt steeple
#

lol

#

especially in windows 11

#

however that default is not administrator

#

an admin account and administrator are different

#

administrator is a guessable name, makes you easier to hack

#

they've had the default administrator account disabled since what, vista unless you're on a domain controller

#

administrator always has the same UID

jaunty plank
#

So administrator is effectively root? Above admin perms?

gaunt steeple
#

kinda yeah

jaunty plank
#

I gotta learn windows still and I've been using it forever

gaunt steeple
#

it's root instead of making your own user account in the root or wheel group

#

the normal setup of windows is a user who isn't technically an admin all the time but elevates to admin via uac

#

which is why you can't just delete windows files

#

since after windows xp

#

basically like sudo

#

that's when it pops up "do you want to perform changes to your pc"

#

elevation

#

as actual administrator it may not prompt

jaunty plank
vernal isle
vernal isle
mint cedar
bitter merlin
#

@mint cedar @vernal isle @jaunty plank can u give me top.gg api

jaunty plank
#

Please don't mass ping

jaunty plank
#

You're looking for the docs? Or?

bitter merlin
bitter merlin
jaunty plank
#

We can't "give" a website.

bitter merlin
vernal isle
bitter merlin
vernal isle
vernal isle
#

If it gets rejected, fix the cause. If you got no response, keep waiting

gaunt steeple
#

I still wouldn't run a bot as admin

#

same way I wouldn't run one as root

#

use the permissions systems your os gives you

cerulean valley
#
TopGGAPIError: 504 Gateway Timeout
    at Api._request (/home/container/node_modules/@top-gg/sdk/dist/structs/Api.js:61:19)
    at processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async Api.postStats (/home/container/node_modules/@top-gg/sdk/dist/structs/Api.js:86:9) {
  response: {
    statusCode: 504,
    headers: {
      date: 'Tue, 12 Mar 2024 14:56:42 GMT',
      'content-type': 'text/plain; charset=UTF-8',
      'content-length': '15',
      connection: 'keep-alive',
      'strict-transport-security': 'max-age=15552000; includeSubDomains; preload',
      'x-content-type-options': 'nosniff',
      'x-frame-options': 'SAMEORIGIN',
      'referrer-policy': 'same-origin',
      'cache-control': 'private, max-age=0, no-store, no-cache, must-revalidate, post-check=0, pre-check=0',
      expires: 'Thu, 01 Jan 1970 00:00:01 GMT',
      server: 'cloudflare',
      'cf-ray': '8634a071beaea832-SYD',
      'alt-svc': 'h3=":443"; ma=86400'
    },
    trailers: {},
    opaque: null,
    body: BodyReadable {
      _events: [Object],
      _readableState: [ReadableState],
      _read: [Function: bound resume],
      _maxListeners: undefined,
      _eventsCount: 3,
      [Symbol(shapeMode)]: true,
      [Symbol(kCapture)]: false,
      [Symbol(abort)]: [Function (anonymous)],
      [Symbol(kConsume)]: [Object],
      [Symbol(kBody)]: null,
      [Symbol(kContentType)]: 'text/plain; charset=UTF-8',
      [Symbol(kReading)]: false
    },
    context: undefined
  }
}``` anyone having the same error every now and again?
runic creek
#

This is an error on the top.gg side, which is probably caused by a temporary API downtime

latent nova
#

Hi

civic thicket
#

Hello @latent nova, for general chatting head over to #general topggHappy

dim hatch
#

I can't post my bot's stats. I am using the Api builder from @topgg/sdk

#

It says I'm unauthorized

#

But I am using the correct token

spiral roost
#
const Topgg = require("@top-gg/sdk")
const express = require("express")

const app = express()

const webhook = new Topgg.Webhook("your webhook auth")

app.post("/dblwebhook", webhook.listener(vote => {
  // vote will be your vote object, e.g
  console.log(vote.user) // 395526710101278721 < user who voted\
}))

app.listen(80)

Is there any way, I can achieve this same thing without having to use webhook?

reef crow
#

Someone tell me as beginner guider
How to make a logging system that log on specific channel when someone vote my bot

#

With variables of who voted, a timer when they vote again

#

Total vote counts

jaunty plank
gusty locust
gusty locust
spiral roost
jaunty plank
#

You just make an API endpoint for whatever lib and language you use.

spiral roost
#

And can a moderator see your webhook link or auth?

jaunty plank
#

We can't no

#

I'm out of town, I can't help with this today sorry.

spiral roost
spiral roost
#

Though I use js

jaunty plank
#

We have some libs on the docs site that can do this.

As for doing it from scratch you can just Google webhooks for your programming language

spiral roost
timid stratus
#

Hey hey, as a question, can someone briefly explain to me the API and what you can do with it, for example?

I'm new to this API area, I always code everything myself, etc
hence the stupid question

jaunty plank
timid stratus
#

Thanks

dim hatch
#

And that module requiere the client of Eris or Djs

runic creek
#

Both should work

shell siren
#

Not sure where to post this but, is it correct to assume bot icons aren't being shown when the bot avatar is a gif format? thinkMan

tidal idol
#

correct

dim hatch
#

Nor Eris

#

It is a new library that is not very well known.

shadow leaf
runic creek
dim hatch
topaz mural
#

hey, I am getting started with tpogg API , how do I get the topgg API token?

#

got the token

#

instead of sending the code, I am sending the parameter values because my library might not be familiar:

header:

  "Authorization": "topggapitoken"
}```
type: POST

body:

{
"server_count": 57
}

url:
```https://top.gg/api/bots/815583533308313641/stats```
property: empty 

is this good?
topaz mural
runic creek
#

Remove this colon in the link

topaz mural
runic creek
#

It shouldn't be there

topaz mural
#

ok I'll try

runic creek
#

You were supposed to replace :bot_id with your bot's id, not just bot_id

#

That's why it's even bolded

topaz mural
#

o i get it I'll try

#

now it says invalid input

#

{"message":"Invalid input"}

#

@runic creek help :>

old forge
#

yo @ripe trellis

#

-b @ripe trellis support scam smirk

abstract mothBOT
#

upvote stevenclinton.#0 was successfully banned.

topaz mural
#

lmao wut

#

pink

old forge
#

hi

old forge
#

what lib are you using

topaz mural
#

aoi.js

#

๐Ÿ˜ฎ

topaz mural
# old forge what lib are you using
c!eval $httpRequest[https://top.gg/api/bots/815583533308313641/stats;POST;
{
  "server_count": 57
}
;;err;
{
  "Authorization": "$getVar[topggapikey]"
}
]
#

does there need to be anything in the object/property parameter?

i have just put

  "server_count": 57
}

in the "body"

old forge
#

looks fine

topaz mural
humble summit
#

Yeah looks good to me too. I'm more familiar with using .NET though but I would recommend using something like postman first to test making a call to ensure it sends through all fine. Then you can craft the call in your code from there.

#

Maybe try a get call as well? It could help narrow down the problem area.

topaz mural
#

all requests (POST/GET) are to be https or json?

old forge
#

I mean if you go off the docs, it looks fine

#

And are you unable to use the js lib for posting stats?

topaz mural
#

when using GET, there's just no response, no error or anything

topaz mural
old forge
topaz mural
#

wut is autoposter lib :

old forge
#

o:

topaz mural
#

i need to install it?

old forge
#

Npm lib

topaz mural
#

npm i topgg-autoposter, i need to install this?

#
const client = new Discord.Client() // Your discord.js or eris client (or djs ShardingManager)
const { AutoPoster } = require('topgg-autoposter')

const ap = AutoPoster('Your Top.gg Token', client)

ap.on('posted', () => {
  console.log('Posted stats to Top.gg!')
})
``` and also add this?
old forge
#

yes

topaz mural
#

ok ig i have done this stuff

#

now it will do it automatically or I have to something?

#

yo it worked thanks ๐Ÿ˜ฎ

wind olive
#

curl -X POST -H "Authorization: " -d "{\"server_count\":50}" https://top.gg/api/bots/1209874430981963846/stats
{"message":"Invalid input"}

#

why doesnt work?

lethal prism
#

Why did the bot stats stopped updating at 31,200 servers? Was there some change in API? It worked 4-5 days ago

brave rapids
#

O vote

snow parrot
#

is there a way to get bot review?

#

beyond the topgg api or in it

runic creek
#

If you look carefully in the "Network" tab, you will find the appropriate API request and the endpoint in it

manic pecan
#

Hello, someone has a JavaScript Code for webhook message when a user vote ?

muted verge
#

API not working for anyone?

icy aurora
muted verge
#

Was there a change? I'm getting 400 codes now and didn't change anything

sand spire
#

Can someone tell to me how too add bot too server

radiant pasture
sand spire
#

Gaming

#

Bot

#

I already added it

#

But the problem is

#

Idk how to use it

radiant pasture
#

you can join their support server and they will help you out

#

you can also look for the bot's documents online they usually tell you how to use it

sand spire
#

Can U come dm

#

For a little bit

#

??

abstract mothBOT
#

@sand spire

topggDotRed Hey! We think you have our server mistaken. We do not provide support, help, or advice for any bot. You need to click on the "Discord Support Server" button on the bot's page of the bot you need support for. If there isn't a button that says "Discord Support Server" or nothing else mentioned about a support server, the server invite is invalid or you were banned from the bot's support server, then we can't help you. Sorry :(

radiant pasture
#

read that, should help worryThumbsUp

velvet compass
#

where is that damaged top gege python sdk

scarlet cobalt
muted verge
#

Anyone know why this stopped working? I've been getting 400 Bad Request error codes for the past week or so and didn't change anything. I verified it's passing the correct token and payload via debugging:

async def update_server_count():
    guild_count = len(bot.guilds)
    payload = {
        'server_count': guild_count
    }

    headers = {
        'Authorization': bot.topgg_token
    }

    async with aiohttp.ClientSession() as session:
        async with session.post(f'https://top.gg/api/bots/{bot.user.id}/stats', data=payload, headers=headers) as resp:
            if resp.status == 200:
                print(f'Server count of {guild_count} posted successfully to top.gg.')
            else:
                print(f'Failed to post server count. Status code: {resp.status}')
#

Should I refresh my token?

vestal wasp
#

seemingly many people get that error

#

a wrong token should be 403 though

muted verge
#

Do you know how they resolve it or does top.gg need to fix it?

vernal isle
#

tldr possibly just random stupid requests coming through.

jaunty plank
simple lion
#

Your Top.gg Token

where to get the token

pallid jay
#

reddit bots when?

muted verge
jaunty plank
#

Yep

muted verge
#

I'm still getting 400 Bad Request

vital anvil
woven coral
jaunty plank
#

We dont require that do we? ๐Ÿ‘€

#

I've not used the API directly in so long

woven coral
#

i dont know either lmao

woven coral
#

wait yeah i think we don't

woven coral
#

@muted verge try data=json.dumps(payload)

olive heart
#

#credits

vernal isle
#

or json=payload

muted verge
woven coral
#

โค๏ธ

sage mural
#

credits plizz

lethal prism
#

the stats stopped updating randomly

#

this is my code

await fetch(`https://top.gg/api/bots/718493970652594217/stats`, {
            method: "POST",
            headers: {
                "Authorization": config.topggToken,
            },
            body: params
        });
#

also getting 400

#

trying stuff said above

#

Ok now getting 200

icy aurora
merry bloom
#

Hi, I was wondering a question, is it possible to make a /vote command which votes directly on the site without having to click on the link etc. that it is automatic and that its vote is carried out by the person who executes the command?

vital anvil
merry bloom
#

ok, thanks for your answers ๐Ÿ™‚

lethal prism
#

its just a single post request

#

and autoposter doesn't work too well for clustering in some cases

lilac oracle
#

hi๏ผŒwhen i apply the bot token to track the server count, top.gg kept showing: http 400

jaunty plank
visual oxide
#

Hello everyone,
Is there an API endpoint, where I could post a description of Bot?

I am aware, that I can change the Description manually on the Top.GG site.

visual oxide
vestal wasp
#

long answer, yes with a user account, but I doubt you are supposed to do that, so no again

visual oxide
#

Well that's sad

#

Thanks for answering; have a nice day!

vestal wasp
#

yw

jaunty plank
#

Dynamic/changing descriptions can be done with an iframe

#

iframe to a website you have, then you can update that iframe any time you want.

lusty tundra
#

How do I make an event in the topgg javascript (node.js) library, that when a user has voted, it returns the userId and everything

#

I tried toppgg-votes but that didn't work

#

The closest I saw to official topgg stuff was: https://www.npmjs.com/package/topgg-autoposter

But this didn't have posting events. just to post stats to the website

jaunty plank
lusty tundra
jaunty plank
#

Hmm, thats not official. I'm not sure who made that.

lusty tundra
jaunty plank
#

Looks like you're trying to use a discord URL. Top.gg webhooks are not discord webhooks.

jaunty plank
#

The top.gg token is only for the API. Not voting webhooks/events

restive otter
#

Is the only way to receive voting events with a webhook and an ePoint?

wooden kite
#

I got a error when using topgg-autoposter

#

Fixed it

wooden kite
#

If anyone needs help with top.gg's api then this video got you covered. Helped me a lot

untold sparrow
untold sparrow
wooden kite
#

maybe like how to make your bot page better with like markdown or html

untold sparrow
wooden kite
#

feel you

icy aurora
quick knoll
#

error

restive otter
#

where can I host a mini webhook server for free to listen to votes?

icy aurora
quick knoll
#

Where do I enter the token?
@icy aurora

icy aurora
molten dove
#

hello I'd like to know why I'm getting this "Error: 401 Unauthorized (You need a token for this endpoint)" error, because I'm using this tokenI'd like to know why I'm getting this "Error: 401 Unauthorized (You need a token for this endpoint)" error, because I'm using this token

rare yew
#

hey one question how can i get the webhook token?

#

or is there any docs?

jaunty plank
#

For example I could just start hitting keys on my keyboard.
dnjsaiodjnsadnkoas
^ valid auth

rare yew
#

wait what how is that possible

jaunty plank
#

The auth is for you, or the library you use to validate the incoming request is actually coming from Top.gg

#

If only you know it no one can submit fake requests.

elder stratus
#

How to i get my API Key?

elder stratus
#

Thanks

lusty tundra
#

The request isn't working. Url is valid

jaunty plank
#

Top.gg webhooks are not discord webhooks

lusty tundra
radiant pasture
#

Pretty sure you find that on your bot's edit page

radiant pasture
jaunty plank
#

Thats just to fill in your own webhook url.

robust yacht
#

isn't it possible to test vote for topggpy lib?

#

Like it doesn't it load in the on_dbl_vote event?

robust yacht
#

I'm trying to send message whenever someone votes, using my main bot but the event on_dbl_vote is not getting called when i send test vote

inner bloom
#

it used to work but since like 2 weeks it just doesn't anymore

wooden kite
# inner bloom it used to work but since like 2 weeks it just doesn't anymore

Use top.gg autoposter. Can't remember the exact name but something like that. Here is a video tutorial: https://www.youtube.com/watch?v=wqlU2KOxQws&t=65s

Quick showcase on how the top.gg API can be easily used with the help of the top.gg javascript SDK to give users a reward for voting for your bot as well as how you can easily implement the autoposter library to keep your bot stats up to date on the website.

Credits

Produced...

โ–ถ Play video
kindred shard
#

...

earnest swan
#

Hey, does anybody knows why my response returns into false?

in my topGG code:




function topGG(serverCount) {
    fetch("https://top.gg/api/bots/1193672589428654120/stats", {
        method: "POST",
        headers: {
            Authorization: "token",
            
        },
        body: {
            server_count: serverCount
        }
    }).then(response => {
        response.json()
        console.log(response.ok)
    })
}

module.exports = {topGG}```

In bot.js

```js

setInterval(() => {
    topGG(client.guilds.cache.size)
}, 30000)```
restive otter
#

Are votes from app owners no longer sent to the webhook? I voted with my own account and nothing happened, but when I told someone to vote they received it

icy aurora
earnest swan
icy aurora
#

that package is written in ts but works ts and js

foggy relic
#

~~Hello, I'm trying to reward a user when they vote, but my bot isn't receiving the vote POST requests. Whether a user votes or I use the "send test" function, my bot isn't receiving them. Here is my code and config:

const { Webhook } = require("@top-gg/sdk");
const express = require("express");

const app = express();
const webhook = new Webhook("my-auth");
const PORT = 3000;

app.post("/dblwebhook", webhook.listener(vote => {
    console.log("vote received:", vote);
    rewardVote(vote.user);
}));

app.listen(PORT);

console.info(`Connected to TopGG (port ${PORT})`);

Then in the webhook config, I have:

  • Webhook URL: http://[host ip]:3000/dblwebhook
  • Authorization: my-auth~~

Edit: got it fixed, my code was correct, but I needed to unblock the port on my VPS's firewall

native raft
hearty echo
#

Why does server 1 appear?

timid stratus
icy aurora
timid stratus
icy aurora
vernal isle
# robust yacht Like it doesn't it load in the on_dbl_vote event?
GitHub

A simple API wrapper for top.gg written in Python. Contribute to Top-gg-Community/python-sdk development by creating an account on GitHub.

robust yacht
#

ok

#

this isn't the webhook of discord?

vernal isle
#

Make sure the webhook manager is running properly and top.gg's access to it is not hindered.

No, the webhook manager in this case is an alias for a webserver. In other words, a server running on your machine that accepts HTTP requests.

#

Top.gg does not support Discord webhooks.

robust yacht
#

alright, thanks

lusty tundra
#

Does Top.gg have an API where it sends votes to a Discord webhook?

icy aurora
lusty tundra
# icy aurora no

any other way instead of webhook? bc if i'm running multiple bots on different ips is there an event any other than webhook that i can get?

icy aurora
long canopy
#

hi can someone send the code for server stats in top.gg for python

long canopy
# icy aurora https://pypi.org/project/topggpy/

Traceback (most recent call last):
File "/home/container/bot.py", line 2973, in <module>
bot.topggpy = topgg.DBLClient(bot, dbl_token)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/container/.local/lib/python3.12/site-packages/topgg/client.py", line 98, in init
self.http = HTTPClient(token, loop=self.loop, session=kwargs.get("session"))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/container/.local/lib/python3.12/site-packages/topgg/http.py", line 84, in init
self.session = kwargs.get("session") or aiohttp.ClientSession(loop=self.loop)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/container/.local/lib/python3.12/site-packages/aiohttp/client.py", line 279, in init
loop = get_running_loop(loop)
^^^^^^^^^^^^^^^^^^^^^^
File "/home/container/.local/lib/python3.12/site-packages/aiohttp/helpers.py", line 301, in get_running_loop
if not loop.is_running():
^^^^^^^^^^^^^^^
File "/home/container/.local/lib/python3.12/site-packages/discord/client.py", line 140, in getattr
raise AttributeError(msg)
AttributeError: loop attribute cannot be accessed in non-async contexts. Consider using either an asynchronous main function and passing it to asyncio.run or using asynchronous initialisation hooks such as Client.setup_hook

icy aurora
long canopy
#

so what now

icy aurora
restive otter
#

When do vows reset?

icy aurora
long canopy
#

they gave me example

long canopy
#

did not understand

#

one word

#

u can send a yt video dm me

icy aurora
long canopy
#

u know what i dont care

#

i get errrors

icy aurora
ionic fox
#

Hey is there a way in python where I can give rewards based on if a person has voted or not?
API/ Documentation in Python
or something

jaunty plank
jagged coral
#

What does this mean?

icy aurora
#

You need a token

jagged coral
#

Is the token from the bot or somewhere on the website?

jagged coral
jagged coral
restive otter
#

Have the votes been reset? If yes, when?

untold sparrow
restive otter
olive lion
#

Where do you get your bot topgg token? in the webhooks?

golden adder
still roost
#

I have a bug when i want to add Background Image in my bot page...

abstract mothBOT
#

@still roost

topgg The bot page background link is currently broken. We suggest you use CSS for the time being!

topggDotRed Add the following code to your bot description:

body {
 background: url(INSERT_LINK_HERE);
}
</style>
still roost
#

oki thanks

olive lion
#

language is python

teal mesa
#

i was using this

#

everything works

#

even post shard and server count func

#

the hting is on_dbl_vote isn't being called

#

not in cog or in main file

#

am setting dblclient in OnReady event

#

but thats not the issue i blieve

#

hope somone can help thanks

jaunty plank
#

Was vote webhooks ever working?

#

or it just suddenly stopped working

teal mesa
#

i tried with send Test button and also tried real voting too

#

but none

#

no error or print

jaunty plank
#

and you filled in the webhook url and authorization?

#

Not with a discord webhook

teal mesa
#

dblclient = topgg.DBLClient(bot, topgg_token)

#

this how i am setting it

#

we need webhook?

jaunty plank
#

Yeah, you need a webhook not a discord webhook.

teal mesa
#

ah

#

any tutorial about webhooks?

#

nvm found it

#

let me see

#

thanks m8

robust yacht
#

Hi, How do I send message whenever someone votes? I am using Python discord.py. I have made my own webhook using FastAPI which returns status code 200.

jaunty plank
olive lion
#

How to get the user cooldown on voting?

jaunty plank
#

Thats something you should track on your side. store the timestamp when they vote in your database, then 12 hours from then is the cooldown

long canopy
#

Hi Can Any One Help Get My Bot Server Amount In Discord.py Also Did Not Understand Docs And Example If Possible Pls Send Code Or Yt Video

robust yacht
#

but the event doesn't get triggered

jaunty plank
robust yacht
#

I return a response with status code 200

#

I think the webhook works fine but I didn't do the code of topggpy correctly

jaunty plank
#

Isn't the code the webhook? ๐Ÿ‘€

#

That's what a webhook is, just code on a server

robust yacht
#

I am hosting server and bot differnetly

jaunty plank
#

I'm really confused on what your issue actually is.

Is the webhook not working?
Or is the dm not working?

#

We can't fix the DM issue until the webhook works, but it sounds like your webhook doesn't work.
I'm not really certain which issue it is

robust yacht
#

like do you have any page that shows the response from my server?

jaunty plank
#

You'd just want to print a response when you get a vote.

robust yacht
#

Yeah it does print

jaunty plank
#

So, you're receiving webhooks?

robust yacht
#

Yes

jaunty plank
#

Then you just need to add your bot to your webhook code, and just send a DM in the event. Or send a message in the channel you want. Or both

robust yacht
jaunty plank
#

yeah, you can always use ipc to forward the request to your "main" bot progran, but thats a pain. It should just be easier to add a very basic bot to the endpoint you want.
And just send a DM via that.
It shouldnt need any commands or anything, just log in to the bot and send DMs.
You'll likely want to disable all intents too.

robust yacht
jaunty plank
#

Topggpy has a webhook server, its not a discord library, its just for receiving webhooks. The only feature other than receiving webhooks is for accessing the Topgg API.

robust yacht
#

oh, so the only way to send message is doing it in the webhook server?

jaunty plank
#

So, the webhook server can be put inside your main bot code, or in the sharding manager(or first shard).
That way your bot and webhook server are the same process.

That's the most common way people handle it.

Or it can be on its own process with a small instance the bot to send DMs.
Or it can be on its own process and you can use IPC to send it to the bot(but that's kinda silly imo).

There's no real right way to handle it, it's however you feel the most comfortable.

robust yacht
#

Alright, thanks.

normal cedar
#

Hi

jaunty plank
winged shard
#

whenever installing topggpy, it messes with pycord to cause AttributeError: module 'discord' has no attribute 'AutoShardedBot' error. This issue only occured after installing topggpy. Does it not support pycord?

#

is there a way to poststats just by an api endpoint? do we need to use a package?

#

Please ping me if you respond

runic creek
#

Everything is in the documentation

honest kraken
#

Hii

winged shard
elfin lichen
#

how do i get a user from top.gg's internal user id's?
for example, my user id is 318453143476371456 but in the topgg url bar its 7901547614833410048 on my profile
sending a request to /api/users/:userid only accepts discord id's

ocean salmon
#

Hello gys

#

My service is not working

jaunty plank
#

I don't think any of our public api endpoints uses or provides a Top.gg ID.

elfin lichen
#

Like a "who is" but based on topgg profile URL

jaunty plank
#

Wouldn't it be easier to just have them mention the user in the command or provide the Discord ID?
then just use the API endpoint?

elfin lichen
#

(and other way around where my whois shows the topgg profile)

jaunty plank
#

I dont think we have any public API endpoints for what you're looking for.

elfin lichen
#

Sad, thank you tho

olive lion
#

I got a question regarding the api. Is it possible to get the upvote cooldown time of a voter?

jaunty plank
tranquil field
#

whats an api

icy aurora
tranquil field
olive lion
#

It helps to communicate between two applications

river veldt
#

if i send test webhook on my vps, i get

7|Robloxbot  |   File "/usr/local/lib/python3.10/dist-packages/aiohttp/web_protocol.py", line 332, in data_received
7|Robloxbot  |     messages, upgraded, tail = self._request_parser.feed_data(data)
7|Robloxbot  |   File "aiohttp/_http_parser.pyx", line 551, in aiohttp._http_parser.HttpParser.feed_data
7|Robloxbot  | aiohttp.http_exceptions.BadStatusLine: 400, message="Bad status line 'Invalid method encountered'"```
river veldt
tame gate
#

..

long canopy
#

it kinda hard too understand

jaunty plank
#

What's hard to understand from the docs?

river veldt
jaunty plank
# river veldt mh, even with different wrapper I get this

I'm not a py dev, but that reads like an error is happening with a request you're sending.
Ie after the webhook is already handled, something in your event is throwing the error. Are you possibly sending a request to an API or something that could be causing this?

river veldt
river veldt
#

does not work, I cant even get the request to print

#

even tho port should be open

river veldt
#

might found out why

mint cloak
#

How can I test voting hehooks locally?

icy aurora
smoky marten
#
{
  "bot": "6916266261969696969",
  "user": "584309117380853770",
  "type": "upvote",
  "isWeekend": false
}

Use something like this

long canopy
#

hi can any send me the code for servers in python

#

i kinda did not understand the docs or example

smoky marten
dry maple
river veldt
long canopy
#

Which file should I look into

rough quiver
#

probably should not be used anymore lol

river veldt
#

I only had to patch one minor thing

rough quiver
river veldt
#

well, the thing is, the main author used [] and not .get and isWeekend would error on test hook

#

other then that, it works fine

rough quiver
wary ivy
#

Hello, can someone who understands this issue help? The user votes once, but receives more than one message.

wary ivy
#

But it didn't work before, how can I do that?

jaunty plank
jaunty plank
#

It's going to sit like that for awhile if I don't have someone else handle it.

Going to make a new GitHub repo rq

spark bronze
#

Am i doing something wrong?

const TopggAPIWebhook = new Topgg.Webhook(config.TopggToken)


api.post('/dblwebhook', TopggAPIWebhook.listener(vote => {
  const Embed = new EmbedBuilder()
  .setTitle(`<@${vote.user}> Just voted for RoSearcher!`)

  const Channel = client.channels.fetch("1207774395268079657")

  if (Channel) {
    Channel.send({ embeds: [Embed] })
  }

}))
jaunty plank
spark bronze
jaunty plank
#

It should be cached, you can use get if you're caching channels.

spark bronze
spark bronze
# jaunty plank It should be cached, you can use get if you're caching channels.

Ok i've done that but the message aint sending


const TopggAPIWebhook = new Topgg.Webhook(config.TopggToken)


api.post('/dblwebhook', TopggAPIWebhook.listener(async vote => {
  const Embed = new EmbedBuilder()
  .setTitle(`<@${vote.user}> Just voted for RoSearcher!`)

  const Channel = await client.channels.cache.get("1207774395268079657")

  if (Channel) {
    Channel.send({ embeds: [Embed] })
  }

}))
jaunty plank
#

Have you used Top.gg webhooks before?

spark bronze
#

just not fully

jaunty plank
#

not fully?

spark bronze
jaunty plank
#

Ah, I mean use them use them

spark bronze
#

no

jaunty plank
#

Did you setup your webhook url? not a discord url, not a url from a webhook site.

spark bronze
#

on the site?

#

yes

jaunty plank
#

Do you mind if i send a request to that url?

spark bronze
#

yah np

jaunty plank
#

Alright, gotta swap to my other OS, brb

jaunty plank
spark bronze
#

yes

jaunty plank
#

Did you fill it in here?

spark bronze
#

yes

#

I see the Request coming

jaunty plank
#

So, you've been receiving the requests

#

?

spark bronze
#

sometimes it will

jaunty plank
#

I'd double check your auth is set correctly.

console.log(config.TopggToken)
Make sure its the exact same thing filled in the authorization.

spark bronze
#

Ok for some reason its now showing this

spark bronze
#

I think ik what i did wrong

#

i accidently set it to the token

spark bronze
#

mb

jaunty plank
#

np ^-^

spark bronze
#

just need to return a 200 to make it not spam

spark bronze
jaunty plank
#

Log vote, see what it is

spark bronze
jaunty plank
#

is your auth using something thats an accented or weird character?

IIRC it only accepts some characters

spark bronze
#

I would say it but yk

#

thats not a good idea

jaunty plank
#

tbh, I'm unsure

spark bronze
jaunty plank
#

do you want me to try a real vote?

spark bronze
#

plz

jaunty plank
#

Voted

spark bronze
#

my only guess is its not sending data from the server to my bot

formal atlas
#

Hi, how can I make my own vote tracker? Using pycord (python).

When a user vote for my bot i want it to print in console, "{userid} has voted for example bot!", maybe using bot.event to check?

If this is possible. What do I need to import/install?

gritty bobcat
#

One message removed from a suspended account.

mossy hill
#

anyone got like a full example for autopost? (discord.py)

cunning mountain
#

anyone know why i get this error often :

TopGGAPIError: 429 Too Many Requests
    at Api._request (/home/container/node_modules/@top-gg/sdk/dist/structs/Api.js:61:19)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async Api.postStats (/home/container/node_modules/@top-gg/sdk/dist/structs/Api.js:86:9) {
  response: {
    statusCode: 429,
    headers: {},
    trailers: {},
    opaque: null,
    body: BodyReadable {
      _readableState: [ReadableState],
      _read: [Function: bound resume],
      _events: [Object: null prototype],
      _eventsCount: 3,
      _maxListeners: undefined,
      [Symbol(kCapture)]: false,
      [Symbol(abort)]: [Function (anonymous)],
      [Symbol(kConsume)]: [Object],
      [Symbol(kBody)]: null,
      [Symbol(kContentType)]: 'application/json',
      [Symbol(kReading)]: false
    },
    context: undefined
  }
}```
ocean linden
#

it obviously sais you exceeded a rate limit

heavy comet
#

is there a way to get a webhook when someone writes a review for your bot? No, right?

runic creek
#

No, there is no such webhook

#

There is also no documented endpoint in the API when it comes to reviews

atomic burrow
#

Hey, whenever someone votes on my bot on Top.gg, it does not send a POST request to the webhook i provided. Am i doing something wrong?
I've tried clicking the "Send Test" button in the settings, which successfully sends a request and i process it correctly on my end. It's just when someone votes that nothing happens. Help please!

#

My code:

const express = require('express');
const app = express();
const port = 8000;
app.use(express.json());

app.post('/topgg-vote', async(req, res) => {
    console.log('Received a vote from top.gg:', req.body);
    const userID = req.body.user
    // Here you can add your logic to respond to the vote, e.g., sending a message to a Discord channel
    const channelId = 'CHANNEL_ID';
    const channel = client.channels.cache.get(channelId);
    if (channel) {
        channel.send('Thank you for voting, <@' + userID + '>! ``+10,000 โ˜Š``');
    }
    await mongoose.connect(PSWRD, {
        keepAlive: true,
    });
    let user = require("./schemas/user-schema.js");
    let user1 = await user.findOne({_id : userID});
    user1.bal += 10000
    user1.timesVoted += 1
    await user1.save().catch(e => console.log(e));
    res.sendStatus(200); // Respond to Top.gg to acknowledge receipt of the vote
});
app.listen(port, () => {
    console.log(`Server listening at URL:${port}`);
    console.log('Server online!');
});
fiery hornet
#

Hey!

neat rover
#

Does the Webhook URL require SSL when we are doing post request?

#

Cause for the moment it looks like we are not getting any information

#

Even if the express server it's set

fiery crown
#

yes

#

http:// if you don't have ssl

neat rover
#

But when i'm doing with http:// i get This page isnโ€™t working

fiery crown
#

that should work if im not wrong

neat rover
#

I think it also work with url, right?

river veldt
tardy flicker
#

topgg api not working rn??

#

im getting TopGGAPIError: 500 Internal Server Error

tardy flicker
#

works now

river veldt
#

5xx is usually your fault if you run a webserver

tardy flicker
old forge
#

use this

unique cedar
#

i already do

#

thats the npm package i wanted to use

dry maple
#

๐Ÿ‘

tender wagon
#
import topgg
import sys

# Top.gg Stats Poster
TOPGG_TOKEN = os.getenv("TOPGG_TOKEN")
if not TOPGG_TOKEN:
    print("Error: TOPGG_TOKEN not found in .env file.")
    sys.exit(1)

def on_autopost_success():
    print("TopGG Stats succesfully posted.")

def on_autopost_error(exception: Exception):
    print("Failed to post:", exception, file=sys.stderr)

async def post_stats():
    try:
        wrapper = topgg.StatsWrapper(bot, TOPGG_TOKEN)
        await wrapper.post_stats()
    except Exception as e:
        on_autopost_error(e)
    else:
        on_autopost_success()

def stats(client: discord.Client = topgg.data(discord.Client)):
    return topgg.StatsWrapper(guild_count=len(client.guilds))

@bot.event
async def on_ready():
    await post_stats()
  File "c:\Users\Max\Documents\Programmieren\Discord-Bots\Aktive Bots\Vysion\main.py", line 67, in <module>
    def stats(client: discord.Client = topgg.data(discord.Client)):
                                       ^^^^^^^^^^
AttributeError: module 'topgg' has no attribute 'data'

hi, but https://github.com/Top-gg-Community/python-sdk/blob/master/examples/discordpy_example/callbacks/autopost.py

GitHub

A simple API wrapper for top.gg written in Python. Contribute to Top-gg-Community/python-sdk development by creating an account on GitHub.

tidal burrow
#

Hey, I have a question. Does the Send Test button in webhooks actually send any data? Maybe dummy data?

wide wind
#

whatever

unique cedar
river veldt
tidal burrow
#

Ok, thanks!

spark bronze
wide wind
spark bronze
wide wind
spark bronze
restive otter
#

guys..whats the best verification bot out der??

wide wind
#

In post, what type of content i need to send?

#

form type or params or json?

#

or something else

#

?

velvet compass
#

JSON Body

tidal burrow
#

Hey, is it normal that votes take a very long time to process? I've voted for my bot about 15 minutes ago, and the vote count still hasn't gone up, nor have I received a webhook about it.

jaunty plank
tidal burrow
#

Honestly, I'm unsure. I think I've been receiving both but it's very inconsistent, so right now I'm trying to figure out if Cloudflare is the cause.

tidal burrow
#

Well, I've found out that it was indeed counting all votes, even test ones. Turns out printing the incoming webhooks was inconsistent than writing to a file.

#

Though, at least without the Cloudflare proxy, which I'd really like to use but unsure whether it's a good idea to rely that it will be immediately forwarding all data.

#

Can anybody provide any input on that? It's really necessary to hide myself from the public internet, but there's also no guarantee that Cloudflare will deliver every data immediately.

tidal burrow
#

Well, I think I've found out that Cloudflare only caches GET, but POST is always immediately forwarded to origin. I didn't find a mention of it in the official Cloudflare docs, so can anyone comment on this and hopefully give me some reassurance?

unique cedar
glad void
#

@leaden kestrel

jaunty plank
tidal burrow
#

Alright, thank you!

runic creek
river veldt
#

Why do i keep getting ratelimited?

toppy.errors.Ratelimited: Ratelimited by the internal ratelimiter - Retry after 1438.078099s

#

second time i saw it happend

#

is fetching bot info really that ratelimited or something else wrong?

#

on vote I fetch /bots/MYBOT, to get the stats. I dont really have many votes yet, so idk. Seems pretty weird to me

jaunty plank
#

Why do you need to fetch bot info every vote? ๐Ÿ‘€

#

Thats not really how its intended to be used, its more of a "once a day" type of endpoint

river veldt
#

or is there another endpoint?

#

thats how jt currently looks

jaunty plank
#

Assuming you just want to send a message with the number of votes I would fetch the endpoint when the bot starts, and every hour or day.
Then just increment the count in a variable.

river veldt
#

i guess storing myself is the way than

jaunty plank
#

It should just be 5-6 extra lines of code, super simple.

river veldt
#

ye ik but i was being lazy about it

#

and I assume if i get ratelimited on that endpoint, the check endpoint is also affected?

jaunty plank
#

Thats probably the main reason you're being ratelimited tbh

river veldt
#

but that would be kinda silly how the check endpoint is heavily ratelimited

jaunty plank
#

Imo, the check endpoint is rarely useful for anything but just checking if a webhook didn't get received.

#

If you need it for checking if people can use a command you'll get ratelimited pretty much instantly unless you have a ton of caching, even then I've seen bots still get ratelimited.

river veldt
#

Thats a very odd design choice then. It sounds for me that the endpoint is made for that in mind but it seems not when the ratelimit is so heavy lmao.
I guess, i will also check it via db then

river veldt
#

how come i get ratelimited when i wont send 60 req in a min

runic creek
#

One bot has one webhook, this is true because there is only a webhook responsible for votes. By hosting several bots on one VPS, you can create several such webhooks (on different ports) or use the same webhook and check in the webhook code which bot this vote applies to

runic creek
#

A webhook is nothing more than a web server that accepts requests. I don't completely understand what you mean by "multiple webhooks" since there is only one webhook on top.gg responsible for receiving requests when someone votes for your bot

unique cedar
#

People are voting for my bot but my webhook doesnt send any message

jaunty plank
#

You can forward webhooks.
So you can have one receive and forward it to as many webhooks as you want.

jaunty plank
unique cedar
jaunty plank
#

That's unrelated to this channel. Webhook-topgg is my site, and it's unofficial, if you want to DM me I can look into it when I have time.
I'm out of town for the next 12 hours or so, so it'll probably be tomorrow before I can help.

unique cedar
jaunty plank
#

We will likely never support it.

Webhook forwarding is pretty normal, you can manage things like handling retries yourself for each webhook server.

tight oyster
#

I'm new to topgg, is it possible to make automatic rewards for voting?

tight oyster
#

Can you give me the link to the api docs?

tight oyster
#

thanks

random saddle
#

How can I make a topgg voter in python can someone help me

radiant pasture
#

you can't vote bot mate

unique cedar
tight oyster
untold sparrow
unique cedar
#

nah automatic vote for a bot every 12 hours

untold sparrow
tight oyster
random saddle
#

That if someone votes my bot should send a vote message in a channel but I don't know how to do it

tight oyster
random saddle
#

Thanks

tight oyster
random saddle
# tight oyster Use webhook for this https://topggpy.readthedocs.io/en/stable/webhooks.html

So

import discord
from discord.ext import commands
import topgg
from aiohttp import web
import os

class VoteListener(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.dbl_auth = os.getenv("TOPGG_TOKEN", "") 
        self.webserver = web.Application()
        self.webserver.router.add_post("/dbl", self.handle_vote)
        
        self.bot.loop.create_task(self.start_webserver())

    async def start_webserver(self):
        runner = web.AppRunner(self.webserver)
        await runner.setup()
        site = web.TCPSite(runner, "0.0.0.0", 5000)
        await site.start()
        print("Webhook server started on port 5000")

    async def handle_vote(self, request):
        auth = request.headers.get("Authorization", "") 
        if auth == self.dbl_auth:
            data = await request.json()
            user_id = data.get("user")
            if user_id:
                embed = discord.Embed(title=f"<@{user_id}> Just voted for RoSearcher!")
                channel = self.bot.get_channel(1207774395268079657)
                if channel:
                    await channel.send(embed=embed)
                return web.Response(status=200, text="OK")
        return web.Response(status=401, text="Authorization failed")

async def setup(bot):
    await bot.add_cog(VoteListener(bot))
untold sparrow
tight oyster
tight oyster
neat rover
#

When you have 1 mil votes each month

#

Do you think they are legit?

tight oyster
tight oyster
#

what is the name of the bot?

gaunt steeple
#

botted votes are not allowed. they impact the site and are unfair to everyone else.

#

theres no such thing as a "legit" discord bot net

scarlet cobalt
#

One message removed from a suspended account.

runic creek
#

I doubt it would be a good idea to joke about this. Someone might take this seriously

restive otter
restive otter
#

Hi

#

How can I install the topgg api? I want to see who votes for my bot.

scarlet cobalt
restive otter
#

๐Ÿ‡น๐Ÿ‡ท

scarlet cobalt
#

One message removed from a suspended account.

#

One message removed from a suspended account.

#

One message removed from a suspended account.

#

One message removed from a suspended account.

#

One message removed from a suspended account.

#

One message removed from a suspended account.

restive otter
#

@scarlet cobalt

scarlet cobalt
#

One message removed from a suspended account.

#

One message removed from a suspended account.

#

One message removed from a suspended account.

restive otter
silk idol
restive otter
#

There is no clone or copy of my bot, it is one and the same.

#

I hope you don't do anything to my bot, I worked hard to get it approved. @silk idol

silk idol
unique cedar
#

wth is bdfd

silk idol
unique cedar
silk idol
unique cedar
shy salmon
unique cedar
#

real

shy salmon
#

OH WAIt administrator is at the top

#

LMAO

unique cedar
#

yep

fallen thistle
#

real quick question

#

is snowflake a string or int type

scarlet cobalt
#

One message removed from a suspended account.

merry path
weak bobcat
#

fetch snowflake by passing ID

fallen thistle
#

huh

weak bobcat
#

for example

fallen thistle
#

Using rust's rocket and it needs the API body to be statically typed

weak bobcat
#

know nothin bout rust

fallen thistle
#

Otherwise it rejects the request

weak bobcat
fallen thistle
#

I implemented it in dpy already

#

but dpy doesn't care about types

weak bobcat
#
guild = ctx.guild
channel_id = int(input("Enter Channel ID: "))

channel = guild.fetch_channel(channel_id))
#

like dis

fallen thistle
worldly palm
#

can you help me out, the bot doesn't post stats to the api

    async def update_top_gg(self):
        top_gg_token = os.getenv('TOP_GG_TOKEN')
        if top_gg_token:
            url = 'https://top.gg/api/bots/{bot_id}/stats'.format(bot_id=self.bot.user.id)
            headers = {'Authorization': top_gg_token, 'Content-Type': 'application/json'}
            payload = {
                'server_count': len(self.bot.guilds),
            }
            await self.post_update(url, headers, payload)```
eager spear
#

why is this not working

jaunty plank
eager spear
#

Anyway I just had to send message so itโ€™s figured out

last lodge
#

User key not found in vote data
Did the user key been removed? if yes then whats the latest ?

supple depot
#

how tto make it sao whyen soimeone votes iit sends thru embed in that channel

vital pulsar
# supple depot how tto make it sao whyen soimeone votes iit sends thru embed in that channel

this might still be viable

import express, { Request, Response } from 'express';

const app = express();
const voteAuth = process.env.VOTE_AUTH_TOKEN || '';

app.post('/vote/topgg', (req: Request, res: Response) => {
  const authHeader = req.header('Authorization');

  if (authHeader !== voteAuth) {
    console.log('Unauthorized vote request');
    return res.status(401).end();
  }

  const { user } = req.body;

  if (!user) {
    console.log('Invalid vote request: User ID is required');
    return res.status(400).json({ error: 'User ID is required' });
  }

  console.log(`Received vote from user: ${user} on top.gg`);

  res.status(200).end();
});
#

then just configure the url for votes

neat rover
#

Does someone face the same issue, topgg api send me the same information 2 times, but not always

#

Like someone voted now and the top.gg send me the same information 2 times

#

like the person voted 2 times

mystic surge
#

Is it possible to view analytics like count of invite button press ..etc from my bot?

jaunty plank
#

Just a heads up, that only shows someone clicking invite on Top.gg, it doesnt confirm they actually invited the bot

mystic surge
#

oh i didn't know that, thanks

minor glacier
#

Its any way to post on api the real number of all shards from my bot

dry maple
#

Note, tell them what language you are using

minor glacier
#

Js

dry maple
#

discord.js?

minor glacier
#

Yes

dry maple
#

You will have to broadcast to all shards for their guild size then post the result of that to top.gg api as of my latest knowledge

minor glacier
#

Ok

dry maple
gaunt steeple
#

im receiving webhooks with user set to null or missing, anyone else?

jaunty plank
#

is the entire thing empty or just user?

gaunt steeple
jaunty plank
#

wtf avatar? ๐Ÿ‘€

gaunt steeple
#

yeah ikr

jaunty plank
#

did veld change things? ๐Ÿ‘€

gaunt steeple
#

idk

#

let me just check im not routing the wrong lists webhook to the wrong route

#

hmmm

#

i know what the problem is, i think, brb

#

yeah, another list is delivering its webhook to my top.gg endpoint, my page edit didnt save there when told to :/

kind raptor
#

// Auto poster for top.gg
AutoPoster(topggApiKey, client)
.on("posted", () => {
console.log("Posted stats to top.gg!");
})
.on("vote", (vote) => {
console.log(${vote.user} just voted!);
handleVoteReward(vote, client); // Call the function from votereward.js
});
could you help me fixing the issue when someone vote it seem the code does nothing

jaunty plank
#

I'm guessing AI

#

The autoposter has nothing to do with voting events.
https://www.npmjs.com/package/topgg-autoposter

kind raptor
kind raptor
jaunty plank
kind raptor
jaunty plank
bleak mural
#

Hi, can someone please help me with the py-sdk?

#

I have the webhook manager in a cog and I start the webhook in the cog_load function with .run(port_number).

#

Then I run await webhookmanager.stop() in the cog_unload function. But, the problem seems to be that the session does not get closed properly because I get an error saying that the address and port is in use.

#

I even tried to access the webserver property and call shutdown() but that still does not solve the problem. It means I have to restart my whole bot in order to unbind from the port but it seems reasonable to expect the .close() function to do it which does not work. It runs but it does not unbind to the port. Any help would be greatly appreciated.

bleak mural
jaunty plank
#

๐Ÿ‘€ dumb question, but what is a cog?
Not a py dev, so I dont know, but why would you be stopping it?

bleak mural
jaunty plank
bleak mural
#

I am using it.

#

But, when reload my cog, the webhook manager gets restarted.

#

That throws an error because when I ran webhook.close() it did not properly unbind the session from the port.

bleak mural
# jaunty plank It looks like the method you want to use is close https://topggpy.readthedocs.io...
class Voting(commands.Cog):
    def __init__(self, bot):
        self.topgg_webhook = WebhookManager(bot).dbl_webhook(auth_key=TOPGG_AUTH_KEY)
        self.topgg_dbl_client = DBLClient(bot, TOPGG_CLIENT_TOKEN)

        # bot.topgg_webhook.webserver.router.add_post(path="/dbl", handler=self.on_dbl_vote)
        # bot.topgg_webhook.
        self.bot = bot
    
    def cog_load(self):
        self.topgg_webhook.run(5000)
        
    async def cog_unload(self):
        await self.topgg_webhook.close()
        await self.topgg_webhook.webserver.shutdown()
        print("webserver shutdown")```
#

So, the webhook has been closed, then when the cog loads again, it throws an error saying the ip:port is in use. Does that make more sense?

#

It just seems like the close method is not properly shutting down the session. even if I access the webserver and call shutdown(seems overkill) it still does not work. So, instead of just reloading this individual cog, I have to restart my whole bot in order to unbind the ip:port.

jaunty plank
bleak mural
#

That makes the webserver bind to that port.

#

I want stop() to unbind from the port. That is what I'd expect it to do but that does not happen.

#

Because, when I do run() again, after calling close(), it says the port is still bound to.

bleak mural
jaunty plank
#

I dont know how aiohttp works, but it sounds like it doesn't work the way you want it to for whatever reason.
I would expect it to release the port when its stop method is called.

bleak mural
#

Okay, thanks for your help. I'll just leave it bound for now and I'll just restart my whole bot if it becomes thaty necessary.

jaunty plank
#

If you track down why aiohttp isnt releasing the port you should make a pull request. Thats definatly something we would want fixed

bleak mural
#

There is an __app property in the webhook manager and it does not get stopped in the close() method. Only the _webserver gets stopped. I am not sure if the __app prop is supposed to get stopped but it does seem like a possibility.

#

That might be the issue, I'll dig a little deeper.

bleak mural
#

Sorry to ask this but is there someone I can speak to about this? Perhaps someone that maintains the py sdk?

jaunty plank
#

You can just make a PR request on our github or @untold sparrow can redirect you to whoever is our py dev(i forget :D)

bleak mural
jaunty plank
#

Should be enough to get it working until close() is properly working

untold sparrow
#

Cc @woven coral above poggythumbsup

bleak mural
gleaming verge
#

How do I know what my api key is?

#

@jaunty plank

jaunty plank
#

On your bots edit page click "webhooks"

gleaming verge
gleaming verge
#

How can I get votes and servers for my application on a website?

#

using the api

gleaming verge
#
// app.js

document.addEventListener("DOMContentLoaded", () => {
    const BOT_ID = "BOT_ID"; // Reemplaza con el ID de tu bot
    const API_KEY = "TU_API_KEY_AQUI"; // Reemplaza con tu API Key de top.gg

    // Verificaciรณn inicial
    console.log("Iniciando la solicitud de estadรญsticas del bot...");

    // Fetch bot stats (server count)
    fetch(`https://top.gg/api/bots/${BOT_ID}/stats`, {
        headers: {
            Authorization: API_KEY
        }
    })
    .then(response => {
        console.log("Bot stats response status:", response.status);
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        return response.json();
    })
    .then(data => {
        console.log("Bot stats data:", data);
        document.getElementById("server-count").textContent = data.server_count || "Not Found";
    })
    .catch(error => console.error("Error fetching bot stats:", error));

    // Fetch bot votes
    fetch(`https://top.gg/api/bots/${BOT_ID}`, {
        headers: {
            Authorization: API_KEY
        }
    })
    .then(response => {
        console.log("Bot votes response status:", response.status);
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        return response.json();
    })
    .then(data => {
        console.log("Bot votes data:", data);
        document.getElementById("vote-count").textContent = data.points || "Not Found";
    })
    .catch(error => console.error("Error fetching bot votes:", error));
});```
#

Are you looking for the servers correctly?

#

Because only the votes appear but the servers tell me the variable that I have configured Not Found

#

@rough crater

woven coral
gleaming verge
#

One question, for the votes can I get the name of the last person who voted for the bot? and can I get the last server anyway?

#

And how are reviews handled in the API?

#

@signal hawk

tidal idol
#

Iโ€™m not sure if this is in order though - Iโ€™d recommend using a vote webhook and storing the votes in your own database and fetching when needed

untold sparrow
tidal idol
#

@signal hawk

scarlet cobalt
#

One message removed from a suspended account.

#

One message removed from a suspended account.

gleaming verge
#

The rest if it gives me data

#

Or are the servers it shows inviting the bot from top.gg?

#

@jaunty plank

jaunty plank
#

Bot owners have to post their server/shard count

#

they dont have to, so it can be 0

#

or just not exist

gleaming verge
jaunty plank
#

you're trying to show your server/shard counts?

jaunty plank
gleaming verge
#

But he doesn't find anything.

gleaming verge
elfin lichen
#

topgg gives me cloudflare "you have been blocked" response when posting stats.
Should I appeal this or am i doing something wrong
URL: https://top.gg/api/bots/BOT_ID/stats
Method: POST
Payload:

{
    "server_count": 3730,
    "shard_list": [0, 1, 2, 3]
}```
#

Yes im providing a token and yes its valid

unique cedar
#

You are rate limited by cloudflare

elfin lichen
#

how, when i make no requests

#

this is the first request i made since idk how many months

unique cedar
tidal idol
#

Do you fetch votes from the api by any chance

elfin lichen
#

not from this IP

#

im using postman at my home ip to do this

unique cedar
honest kraken
#

Hey

pale dock
#

Hllo

silent dove
#

its me

fast pewter
#

Hey! i have a question where do i get my top.gg auth

jaunty plank
fast pewter
#

whichever auth it asks for

jaunty plank
#

The api requires a token, its on your bots edit page in the webhook section

thorny agate
#

async with aiohttp.ClientSession() as session:
headers = {
"Authorization": token}
data = {
'server_count': server_count,
'shard_count': shard_count
}
async with session.post(f'https://top.gg/api/bots/:botid:/stats',
headers=headers,data=data) as resp:
content = await resp.json()
print(content)

This is our request, but it returns: {'message': 'Invalid input'}

dry maple
#

note :botid: is a placeholder

#

you have to put your actual bot's id there

thorny agate
#

It was on purpose,details are hidden.

thorny agate
dry maple
#

you would be surprised the number of people who make that mistake

#

Also, assuming server_count and shard_count are both numbers then yes it looks correct

thorny agate
thorny agate
thorny agate
jaunty plank
vernal isle
#

Do json=data instead of data=data if you want to send dict/JSON data.

Alternatively, what Woo said. Add 'Content-Type': 'application/json' to your headers.

north cave
#

can someone give me an example of the vote data that is sent to the url?

#

this webhook i mean

#
{
    "bot": "",
    "user": "",
    "type": "vote",
    "isWeekend": "false",
    "query": "test=true"
}```
is this the correct data that is sent to the webhook url?
north cave
#

and im assuming, remove query if it's not a test?

jaunty plank
#

query is the query string on the url when they vote.

north cave
#

ohh