#topgg-api
1 messages · Page 171 of 1
This is the URL you're supposed to put, SpaceDoggo
For the auth, it's fully up to you
Are you hosting the webhook locally?
thats what im supposed to do, right?
If you use some sort of service that uses a website domain instead, that'll suffice too
Not really. It's just another option
Err, where do you host the bot though?
its a service called EpikHost
So you want to separate the webhook server and the bot?
no no, i just want a way use webhook locally, when i dont know the ip
wait there must be something in python which does that
get the ip adress of machine
of hosting
Do you have a URL that points to the machine?
no
Err, you might wanna ask for that I guess
Huh yeah
ill ask them
yo wait could that be the ip?
no way lol
umm wait a minute
i do have a website
could i handle webhooks through that?
congrats you exposed your ip address
💀
If you have access to the backend, sure
how ...
i have access to the backend
bot.topgg_webhook = topgg.WebhookManager(bot).dbl_webhook("/dblwebhook", "password")
bot.topgg_webhook.run(5000) # this method can be awaited as well```
bot is needed here, right?
Is it Python as well?
Well, tbh you don't need topggpy if that's the case
Just create a route that accepts a POST request
Check the Authorization header so that you're sure it's coming from topgg. If so, parse the body in JSON and do whatever you want with the data
That's basically it
Take a look at this for the scheme https://docs.top.gg/resources/webhooks/#bot-webhooks
but wait, then topgg will post the data on my website right?
Yes
Hello,
I don't understand very well how the webhook system works
Is a webhook is needed for each server ?
And what have to use for get the user who's voted and do something in Python ?
try upgrade node
K
// Top.gg API
setInterval(() => {
fetch(`https://top.gg/api/bots/${client.user.id}/stats`, {
method: 'post',
data: {
"server_count": `${client.guilds.cache.size}`
},
headers: {
"Content-Type": "application/json",
"Authorization": bconfig.topggtoken
},
body: JSON.stringify({ "server_count": client.guilds.cache.size }),
}).then(() => {
let webembed = new Discord.MessageEmbed()
webembed.setTitle("Top.gg")
webembed.setURL("https://top.gg/bot/802868654957789204")
webembed.setDescription("Bot Stats - Updated")
webembed.setColor('GREEN')
webembed.setTimestamp()
client.channels.cache.get(bconfig.botpostchannel).send(webembed)
}).catch((err) => {
console.error(err);
})
}, bconfig.apiupdatetime)
won't updating server count on website
error?
maybe cache update, i'd say give it 20 minutes max
m giving 2 hrs same resutl
giving 5 sec same result
(Use `node --trace-warnings ...` to show where the warning was created)
this comes everytime
did you do that?
(node:25) ExperimentalWarning: stream/web is an experimental feature. This feature could change at any time
(Use `node --trace-warnings ...` to show where the warning was created)
/home/container/node_modules/discord.js/src/rest/RequestHandler.js:154
throw new DiscordAPIError(request.path, data, request.method, res.status);
^
DiscordAPIError: Missing Permissions
at RequestHandler.execute (/home/container/node_modules/discord.js/src/rest/RequestHandler.js:154:13)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async RequestHandler.push (/home/container/node_modules/discord.js/src/rest/RequestHandler.js:39:14) {
method: 'delete',
path: '/channels/132632676225122304/messages/900766672091234314/reactions',
code: 50013,
httpStatus: 403
}
now this
ok, so forbidden access, looks like a delete and reaction error
just tell me one thing
// Top.gg API
setInterval(() => {
fetch(`https://top.gg/api/bots/${client.user.id}/stats`, {
method: 'post',
data: {
"server_count": `${client.guilds.cache.size}`
},
headers: {
"Content-Type": "application/json",
"Authorization": bconfig.topggtoken
},
body: JSON.stringify({ "server_count": client.guilds.cache.size }),
}).then(() => {
let webembed = new Discord.MessageEmbed()
webembed.setTitle("Top.gg")
webembed.setURL("https://top.gg/bot/802868654957789204")
webembed.setDescription("Bot Stats - Updated")
webembed.setColor('GREEN')
webembed.setTimestamp()
client.channels.cache.get(bconfig.botpostchannel).send(webembed)
}).catch((err) => {
console.error(err);
})
}, bconfig.apiupdatetime)
this code have any error
that it didnt update stats
ok, so it looks like from reading a stack overflow forum, your bot has lower permissions than the user possibly, also check your intents in the dev portal for discord
i dont think that i have to enable any intent for this
the channel you are trying to post the embed to isn't allowing your bot to do so
check your permissions then, because it's saying it's a permission issue and your bot's requesting access for a channel it doesn't have access too, i think it envolves deleting something too
fetch is a package node-fetch
yes it is
wait
ya
r u sure this snippet throws error?
m sending ss
does your bot autodeletes any message?
or something like that
??
is that the full code?
@restive otter you put topggtoken in Authorization?
ya
// Bot Required Modules
const Discord = require('discord.js');
const client = new Discord.Client();
const bconfig = require("./config.json");
const fetch = (...args) => import('node-fetch').then(({ default: fetch }) => fetch(...args));
// Bot Website Post Stats API's
client.on('ready', () => {
console.log("HI")
// Top.gg API
setInterval(() => {
fetch(`https://top.gg/api/bots/${client.user.id}/stats`, {
method: 'post',
data: {
"server_count": `${client.guilds.cache.size}`
},
headers: {
"Content-Type": "application/json",
"Authorization": bconfig.topggtoken
},
body: JSON.stringify({ "server_count": client.guilds.cache.size }),
}).then(() => {
let webembed = new Discord.MessageEmbed()
webembed.setTitle("Top.gg")
webembed.setURL("https://top.gg/bot/802868654957789204")
webembed.setDescription("Bot Stats - Updated")
webembed.setColor('GREEN')
webembed.setTimestamp()
client.channels.cache.get(bconfig.botpostchannel).send(webembed)
}).catch((err) => {
console.error(err);
})
}, 5000)
})
client.login(bconfig.bottoken);
thats my code
m testing the stats update only
use autoposter
thats why only this one
^^
k
autoposter will be easy to handle
(:
yes
k
code -
const { AutoPoster } = require('topgg-autoposter')
// Bot Website Post Stats API's
const poster = AutoPoster('eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjgwMjg2ODY1NDk1Nzc4OTIwNCIsImJvdCI6dHJ1ZSwiaWF0IjoxNjMyMDQyMDU4fQ.2rLETL-7DY3Gi8eXMZDxHoMz6t18EqWjJS4fTlJEL_g', client)
poster.on('posted', () => {
console.log('Posted stats to Top.gg!')
})
error
TopGGAPIError: 401 Unauthorized (You need a token for this endpoint)
at Api._request (C:\Users\manje\Desktop\New folder\node_modules\@top-gg\sdk\dist\structs\Api.js:76:19)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async Api.postStats (C:\Users\manje\Desktop\New folder\node_modules\@top-gg\sdk\dist\structs\Api.js:99:9) {
response: Response {
size: 0,
timeout: 0,
[Symbol(Body internals)]: { body: [PassThrough], disturbed: true, error: null },
[Symbol(Response internals)]: {
PS C:\Users\manje\Desktop\New folder> npm run start
> new-folder@1.0.0 start
> node index.js
TopGGAPIError: 401 Unauthorized (You need a token for this endpoint)
at Api._request (C:\Users\manje\Desktop\New folder\node_modules\@top-gg\sdk\dist\structs\Api.js:76:19)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async Api.postStats (C:\Users\manje\Desktop\New folder\node_modules\@top-gg\sdk\dist\structs\Api.js:99:9) {
response: Response {
size: 0,
timeout: 0,
[Symbol(Body internals)]: { body: [PassThrough], disturbed: true, error: null },
[Symbol(Response internals)]: {
url: 'https://top.gg/api//bots/stats',
status: 401,
statusText: 'Unauthorized',
headers: [Headers],
counter: 0
}
}
}
@raw bough
wait
token is correct?
yes u can
yes
any suggestions
are you using client.login() ?
i mean I deleted the message because it had your token in it
ya
sorry for that
const Discord = require('discord.js');
const client = new Discord.Client();
const { AutoPoster } = require('topgg-autoposter')
const poster = AutoPoster('mytoken', client)
poster.on('posted', () => {
console.log('Posted stats to Top.gg!')
})
client.login(bconfig.bottoken);
here is my code
@raw bough
any error messages?
this is syntactically correct
TopGGAPIError: 401 Unauthorized (You need a token for this endpoint)
at Api._request (C:\Users\manje\Desktop\New folder\node_modules\@top-gg\sdk\dist\structs\Api.js:76:19)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async Api.postStats (C:\Users\manje\Desktop\New folder\node_modules\@top-gg\sdk\dist\structs\Api.js:99:9) {
response: Response {
size: 0,
timeout: 0,
[Symbol(Body internals)]: { body: [PassThrough], disturbed: true, error: null },
[Symbol(Response internals)]: {
PS C:\Users\manje\Desktop\New folder> npm run start
> new-folder@1.0.0 start
> node index.js
TopGGAPIError: 401 Unauthorized (You need a token for this endpoint)
at Api._request (C:\Users\manje\Desktop\New folder\node_modules\@top-gg\sdk\dist\structs\Api.js:76:19)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async Api.postStats (C:\Users\manje\Desktop\New folder\node_modules\@top-gg\sdk\dist\structs\Api.js:99:9) {
response: Response {
size: 0,
timeout: 0,
[Symbol(Body internals)]: { body: [PassThrough], disturbed: true, error: null },
[Symbol(Response internals)]: {
url: 'https://top.gg/api//bots/stats',
status: 401,
statusText: 'Unauthorized',
headers: [Headers],
counter: 0
}
}
}
nvm
fixed it
thanks for your time
say the fix
ok
have a nice day
thanks
suprabhat
site bug
subhratri
The data property does not belong into your code.
(:
// Bot Required Modules
const Discord = require('discord.js');
const client = new Discord.Client();
const bconfig = require("./config.json");
const fetch = (...args) => import('node-fetch').then(({ default: fetch }) => fetch(...args));
// Bot Website Post Stats API's
client.on('ready', () => {
console.log("HI")
// Top.gg API
setInterval(() => {
fetch(`https://top.gg/api/bots/${client.user.id}/stats`, {
method: 'post',
headers: {
"Content-Type": "application/json",
"Authorization": bconfig.topggtoken
},
body: JSON.stringify({ "server_count": client.guilds.cache.size })
}).then(() => {
let webembed = new Discord.MessageEmbed()
webembed.setTitle("Top.gg")
webembed.setURL("https://top.gg/bot/802868654957789204")
webembed.setDescription("Bot Stats - Updated")
webembed.setColor('GREEN')
webembed.setTimestamp()
client.channels.cache.get(bconfig.botpostchannel).send(webembed)
}).catch((err) => {
console.error(err);
})
}, 5000)
})
client.login(bconfig.bottoken);
then this is the code @plucky lance
You don't have to post any fields as the body is your JSON string.
am i right
then m correct
this is correct
Remove the comma fron the last property
body: JSON.stringify({ "server_count": client.guilds.cache.size }), <--
Also check if the status code for the response is accurate
.then((response) => { if(response.ok) ...
catch() only handles errors not if topgg forbidds your request
Also keep in mind to increase your interval frequency
Sending it every 5s is absolutelly too much
I would recommend 30 min
hi there
why I have another owner and at Creators section I see only me?
he has full perms as well
i need api key for my discord bot plz
what's the value that returns true when it's a weekend with the Top.gg Node SDK node module i forgot
vote.weekend or something
idk
what it is and is it a Boolean or something else
or just show the docs of where it is i've been looking for a bit can't find it
?
Whats my webhook url if my bot is hosted using AWS?
U mean token?
If you don’t know the hostname just use it’s public IP address and the path you specified in your webhook config as URL
i thought there was something that showed if it was the weekend on the top.gg api but i couldn't find it so i'll just use my local time on my machine
The API should return a boolean for is_weekend
sidenote: the test button doesn't include the is weekend parameter. only real votes.
should probably add that in for test webhooks too
Known issue
how can I get the id of person who voted for the bot I use python
A simple API wrapper for top.gg written in Python. Contribute to top-gg/python-sdk development by creating an account on GitHub.
Read that
ok 👍 ty again
can we get post request if bot is self hosted?
you will need to portforward etc if you selfhost
any guide that I can follow?
your router manual
another way to get vote info without webhooks? 😅 (ping while answering)
?
Hi there. How would I go by adding a webhook for my server to remind users to upvote? Do I need to create my own bot? Does the reminder only work for bots or can it also be used to remind users to upvote my server?
You can send requests to the API as well to receive the list of voters for the last 12 hours.
so I cant know at the same moment when the bot being voted without using webhooks is that right?
The disadvantage is there’s no timestamp available when an user has voted but the result is the same.
Correct
The webhook is more or less live.
I see
How can i search for bots with prefix ! and only show invite, username, discriminator, id, prefix fields? https://top.gg/api/bots?search=prefix: !&fields=invite, username, discriminator, id, prefix this dosen't work, i may understood it wrong tho
as a side-note: you will need an approved bot to use the api
i do have an approved bot, prefix dosent math with my query tho
example data i get
prefixed are like '.', '$' but not '!'
There's no search filtering on what you're doing, you will have to fetch actual data, parse that data into json, then loop through the results matching prefixes
sucks, thx tho
1|zap-v13 | TypeError: Cannot read properties of undefined (reading '_request')
1|zap-v13 | at postStats (/root/zap-v13/node_modules/@top-gg/sdk/dist/structs/Api.js:99:20)
1|zap-v13 | at Timeout._onTimeout (/root/zap-v13/src/structures/zap.js:185:33)
1|zap-v13 | at listOnTimeout (node:internal/timers:557:17)
1|zap-v13 | at processTimers (node:internal/timers:500:7)
Is there a fix yet? Been getting this error and not finding a fix for days.
FetchError: request to https://top.gg/api//bots/stats failed, reason: socket hang up
how to fix this please
already made
Check the url
i see im just using the auto poster so im not the one providing the url probably just not up to date
make sure you're using the newest version, aswell as passing a correct id
your url does not include the bot id
yep the version is probably outdated as i said
that what i did
my issue fixed it was just not up to date lol
ohhh
@celest pier
it should, is the bot instance logged in?
ghost ping
I have some questions about the ratelimits on here: https://docs.top.gg/resources/ratelimits/
i think i am being ratelimited, but i am using autoposter
how do i know how often its hitting the api? and how do i limit it so that i don't exceed it
The autoposter shouldnt be rate limitable, unless you create it a ton of times.
by default it runs once every 30 minutes.
https://github.com/jpbberry/topgg-autoposter/blob/master/src/structs/BasePoster.ts#L33
ok thanks, thats good
then it is probably discordjs ratelimiting me
Hey, i try to let my bot send a embed if a users votes for my bot, but i tried everything and nothing worked. It would be nice if someone could help me(my bot is in py)
i tried to set the url to https://my-server.ip:port/dblwebhook and the auth key to "test", than i made the cog but nothing happend, nothing is printed :/
where are you hosting your bot?
home/vps/replit/heroku/other
i host on a pterodactyl panel
do they allow the use of webservices like this?
do they allow the port you are using?
pterodactyl gives port number per account so I'm not sure if it will work
I have a pterodactyl account so I'll give it a try now
i can send my code if you want
@jaunty plank Can confirm it will work on Pterodactyl
@client.event
async def on_ready():
discordtownlist.start()
topgg.start()
DiscordComponents(client)
client.topgg_webhook = topgg.WebhookManager(client.dbl_webhook("/dblwebhook", "test"))
await client.topgg_webhook.run(7001)
@client.event
async def on_dbl_vote(data):
"""An event that is called whenever someone votes for the bot on Top.gg."""
if data["type"] == "test":
# this is roughly equivalent to
# return await on_dbl_test(data) in this case
return client.dispatch('dbl_test', data)
print(f"Received a vote:\n{data}")
@client.event
async def on_dbl_test(data):
"""An event that is called whenever someone tests the webhook system for your bot on Top.gg."""
print(f"Received a test vote:\n{data}")
but i got this error too:
File "/home/container/.local/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "/home/container/bot.py", line 153, in on_ready
client.topgg_webhook = topgg.WebhookManager(client.dbl_webhook("/dblwebhook", "test"))
AttributeError: 'Loop' object has no attribute 'WebhookManager'```
odd
Lemme try something and I'll get back to you
I'll also write down the code on how to do it
for others
ok
yes they allow these webservers and using of the port
alr
You're shadowing the topgg module there
what did i do?
what means that
You have a function decorated with a loop decorator named topgg it seems
Can't tell much without the full code ¯\_(ツ)_/¯
yeah but thats for posting guild count
Name it something else
ok
Also, you shouldn't do it in an on_ready, because it may fire multiple times
I'm making a simplified tutorial for python and pterodactyl
Well you can, but just don't try to override, do a hasattr check
File "/home/container/bot.py", line 153, in on_ready
client.topgg_webhook = topgg.WebhookManager(client.dbl_webhook("/dblwebhook", "test"))
AttributeError: 'Bot' object has no attribute 'dbl_webhook'
now i get this lol
Because you're accessing something non-existent
That's not how you setup the WebhookManager either
I'd suggest you read the examples in the readme
ok
I don't know what the issue you're talking about, feel free to make an issue on GitHub
ok i fixed i try it
Anyw, gtg
Will check it later
yesss it worked!!
epic
user = client.get_user(int(data["user"]))```
then user.name
or user
user returns name#0000 etc and user.name returns just the name
You got it!
Well we cannot help much without you showing your code
autoposter posts stats every 30 minutes iirc, so that could be posting it initially, then 30 minutes later
Hey, is it possible to get the current vote count in py in a client.command()
Look the docs
I dont find anything
then you're not properly looking
check the bot object on the docs
the data it contains
@restive otter ok then
dblapi
This channel is ONLY for the Top.gg API!
This channel is only for: suggestions/help/bugs to do with official API libraries and API docs found at: https://docs.top.gg
Any Off-Topic conversation may get deleted and muted.
If you need help with development about your bot or development in general, feel free to use #development.
I just find how to post the guild count and print when a user votes for the bot
Trying to webhook when someone votes. Do i need to auth? Newbie to Python, thanks.
client.topgg_webhook = topgg.WebhookManager(client).dbl_webhook("/dblwebhook", "my bot token")
client.topgg_webhook.run(5000)
@client.event
async def on_dbl_vote(data):
# doesn't run```
mmkay so i realised what the password was supposed to be and it's still not working.
i'm assuming i need to authorise somewhere but idk how
yea that's already fixed
the password and server is all entered on the site now

where do i use the top.gg token though
there
but that's the password
ah nvm
ye ye, mb

i tried turning off my firewall incase it was that and that didn't work
check whether the port is open
i manually opened a port to try that too
I mean, check if nothing else is using it
i've tried two ports now 
this is running off my home pc so im wondering if im being dumb with the webhook url
i've tried both, which should i use
no it's running on my windows 10
is your ip discoverable?
Your IP Address plus Port Scanners, Traceroute, HTTP Compression Test, Ping, Whois, DNS, IP Geo Location, Password Generator and many more tools and how-to's
yea
okay
thanks
Did you not specify the port in the URL?
no?
i've been using telnet to check if my port is open and it seems that even if i add rules in windows firewall it doesn't connect. If i turn off windows firewall it still doesn't connect
wtf is this
Iirc HTTP defaults to 80, so try http://YOUR_IP:5000/dblwebhook
okay ill see if that works but its saying that port is closed
Personally haven't done any port forwarding, so can't help with that
didn't work 
you'll have to port forward for it to work
if you set http://your_ip/something on topgg, you'll need to forward port 80 to that computer you are using to listen those requests
You can use the GUI of your Windows advanced firewall settings or just the command prompt
Keep in mind to adjust the local port
Also hosting at home means you will have to open and forward the port in your router, too
Since be default they will drop inbound connection for unknown ports
You need to forward this TCP port to your device, your current code is running on listening for the webhooks
Even if you did all the required steps it may still be impossible to receive webhooks.
The reason for that could be a nowadays common DS-Lite connection to your provider.
That means you will not have an actual public IPv4 address and most providers don’t support port forwarding for IPv6
OSError: [Errno 10048] error while attempting to bind on address ('0.0.0.0', 80): only one usage of each socket address
(protocol/network address/port) is normally permitted

gawd darn it
i just spent all that time forwarding
alright so after all of that
it doesn't work
no error message or anything. back to square one.
waaait
ofc my public ip has changed 
i'm pretty sure it's working now, i'm getting normal dumb errors that says it's actually triggering the function
Keep in mind that will and can happen frequently.
aaand the code works
with port forwarding, i had to reserve an ip, so i'm hoping that means it doesn't change 
I can has zip
I thought i should pop back in here and say thank you and you're all very lovely for helping me 
Duck DNS free dynamic DNS hosted on Amazon VPC
or if you're on cloudflare https://github.com/timothymiller/cloudflare-ddns
Hey, i tried to get the vote count in discord.py
i tried:
import dbl
dbl_token = 'topgg-token'
@client.command()
async def votes(ctx):
upvotes = await dbl.DBLClient(client, dbl_token).get_bot_upvotes()
print(upvotes)
But it just printed a giant list with users, ids etc
but i want only the count of all votes from a month
this is what was printed
but i just want the current vote count
probably looking for the bot data.
https://topggpy.readthedocs.io/en/latest/models.html#botdata
Is the api down?
nope
But the push of the bots server count isnt working
Also for other users
getting any errors?
mine is posting ok
posted 10 mins ago ok
also, your server count seems to be updated correctly for me.
-bots 280695297456472065
im posting every 30mins
and it hasn't updated
my bot wasn't on 430 servers 30mins ago
cache then
wdym?
it might be a caching issue then
Basically the site knows the count but the site isn't displaying it due to cache
you'll report that?
so i guess just wait
yep
does anyone know a solution for this? my bot has shards so I can't connect, when I turn on the first shard on port 5000, the others try and can't because it's the same port.
Error: listen EADDRINUSE: address already in use :::5000
I’m not really into sharding but that looks like you create a webhook listener for each shard
Why doesn't my token appear when I press "reveal token"
Try clearing cache or refreshing the token
In order to clear your cache for the site, press CTRL+F5.
If this does not work, try one of these resources below:
Instructions on Microsoft Edge
Instructions on Google Chrome
Instructions on Mozilla Firefox
Instructions on Safari
Instructions on Opera
Instructions on Brave
yes, I add the code in the shard.js file so that I don't create one for each shard, when someone votes for the bot, it restarts and gives an error. but the vote is received, because he announces in the chat and hands out coins before he falls.
Theoretically a little bit less than the rate limit is.
But that wouldn’t make much sense.
Posting the stats every 30 min is recommended.
thanks
30 min is also the frequency the official autoposter uses if I remember right
Just to say…
Not able to post my server count. https://top.gg/api/bots/896209803385372682 returns not found.
When providing my token, it also returns forbidden.
Ah. Nevermind fixed it. Was an issue on my end.
Alright so follow these steps:
1. Go to top.gg and login
2. Head to https://top.gg/bot/new and fill out the whole form
3. Wait until you get the result.```
also, go to [#support](/guild/264445053596991498/channel/714045415707770900/) next time :)
How do I get the votes received message in my server
Here some of the steps to follow!
NodeJs:
npm install top.gg
const DBL = require('top.gg');
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!`);
});```
Python:
`pip3 install topggpy`
```py
import topgg
# This example uses topggpy's webhook system.
# The port must be a number between 1024 and 49151.
bot.topgg_webhook = topgg.WebhookManager(bot).dbl_webhook("/dblwebhook", "password")
bot.topgg_webhook.run(5000) # this method can be awaited as well
@bot.event
async def on_dbl_vote(data):
"""An event that is called whenever someone votes for the bot on Top.gg."""
if data["type"] == "test":
# this is roughly equivalent to
# return await on_dbl_test(data) in this case
return bot.dispatch('dbl_test', data)
print(f"Received a vote:\n{data}")
@bot.event
async def on_dbl_test(data):
"""An event that is called whenever someone tests the webhook system for your bot on Top.gg."""
print(f"Received a test vote:\n{data}")
Sources:
npm: https://www.npmjs.com/package/top.gg
python: https://github.com/top-gg/python-sdk
A simple API wrapper for top.gg written in Python. Contribute to top-gg/python-sdk development by creating an account on GitHub.
Here, follow these steps:
NodeJs:
npm install top.gg
const Discord = require("discord.js");
const client = new Discord.Client();
const DBL = require("top.gg");
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}`);
})```
Python:
`pip3 install topggpy`
```py
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('Failed to post server count\n{}: {}'.format(type(e).__name__, e))
update_stats.start()
Sources:
npm: https://github.com/top-gg/python-sdk
pip: https://github.com/top-gg/python-sdk
A simple API wrapper for top.gg written in Python. Contribute to top-gg/python-sdk development by creating an account on GitHub.
thanks
np :)
yea
and after installing the package
one sec
should I add it in the message event?
If you're using our Node.js runtime, don't install the top.gg npm package as it's deprecated, install @top-gg/sdk instead
ok
my bad
apologies
The Top.gg API also has a documentation and a few examples for each official Top.gg lib/SDK you can read and follow:
https://docs.top.gg
Hello
Can someone explain me easily what actually this piece of code mean?
# this is roughly equivalent to
# return await on_dbl_test(data) in this case
return bot.dispatch('dbl_test', data)```
Espacially the dispatch part
A nice, ezzy explaination pls

How to get DBL TOKEN?
not your webhook url
more help: https://docs.top.gg/api/@reference/#:~:text=Your token can be obtained,the ID of your bot
Halp pls
halp
it triggers the event
@restive otter is it like that await process_commands() from discord.py?
await bot.process_commands(message)
bot is your bot variable
Im trying to get the vote stats of my bot but why is the Monthly value greater than the total? That makes no sense. ```js
const x = await axios.get('https://top.gg/api/bots/BOTID', {
headers: {
'Authorization': this.client.config.voteToken
}
}).then(result => result.data).catch(() => null);
console.log(x.points, x.monthlyPoints);```
Result: 40 42
If I just console.log() x the point part shows
monthlyPoints: 42, points: 40,
Is it possible to import topggpy without discord.py
yeah
oh wait
not sure
try it
but its a dependency
then its required
k, so i cant use it wiith pycord
It should work
youll need to write code to do that, or use a third party tool such as https://webhook-topgg.com/
i dont think it will, since pycord mantains the import discord
Do you have a code for that?
as long as it passes a bot object (client or bot) it should work
hmm i use discord.Bot not commands.Bot
Oh fun
Ignoring type annotations, as long as it's similar to d.py, you're good to go
How can see a list of ppl who voted my bot using the topggpy api?
Traceback (most recent call last):
File "/home/container/.local/lib/python3.9/site-packages/topgg/client.py", line 151, in _auto_post
await self.post_guild_count(
File "/home/container/.local/lib/python3.9/site-packages/topgg/client.py", line 212, in post_guild_count
await self.http.post_guild_count(guild_count, shard_count, shard_id)
File "/home/container/.local/lib/python3.9/site-packages/topgg/http.py", line 192, in post_guild_count
await self.request("POST", "/bots/stats", json=payload)
File "/home/container/.local/lib/python3.9/site-packages/topgg/http.py", line 165, in request
raise errors.Unauthorized(resp, data)
topgg.errors.Unauthorized: Unauthorized (status code: 401)``` What is this error?
are you providing a topgg token in the initialization of the library?
yes
try regenerating the token and using that.
ty, it worked
np
realized that the token was more than 16 characters long lol
Votes webhook not working .. help
postman?
online http post/get
bro @restive otter welp
do what Aurel said
i did as you told
im getting reference error and then my token..
Someone help me with webhooks
bruh
@wild lantern
depends, what is your host?
vps/home/replit/herkou/etc
@jaunty plank replit
What language?
It doesn't work like that
Nope. Top.gg webhooks don't work with discord webhooks.
You need to add a webhook receiver in code
either use https://webhook-topgg.com/ or i can send some code which works on Replit d.py
https://docs.top.gg/libraries/python/
Middle example
Searched github but couldnt find anything
bot.topgg_webhook = topgg.WebhookManager(bot).dbl_webhook("/dblwebhook", "password")
The "/dblwebhook"
It needs to be replaced by the webhook right?
That's just the path for the url
from quart import Quart, request
import json
app = Quart(__name__)
@app.route("/dblwebhook", methods=["POST"])
async def votewebhook():
data = await request.data
data = json.loads(data)
userid = data["user"]
botid = data["bot"]
return "Webhook recieved"
app.run("0.0.0.0")```
here is some simple code which works on Replit
No auth check though
Can be added easily though
from quart import Quart, request, abort
import json
app = Quart(__name__)
@app.route("/dblwebhook", methods=["POST"])
async def votewebhook():
if request.headers["Authorization"] == "PUT AUTH PASSWORD HERE!":
data = await request.data
data = json.loads(data)
userid = data["user"]
botid = data["bot"]
return "Webhook recieved"
else:
abort(403)
app.run("0.0.0.0")```
Then you can use the userid and botid data to use in your bot
gemme API link
Thankyou
anyone here tried to use topgg webhook with heroku?
I have not, but have gotten it working for others.
whats the issue?
you need to enable a web dyno, you also are not allowed to use port 80 on heroku
enable a webdyno then see if they both fix then.
Probably need to use the env variable they provide.
https://help.heroku.com/P1AVPANS/why-is-my-node-js-app-crashing-with-an-r10-error
lol
problem was
i used process.env.port not process.env.PORT

as always
@jaunty plank Thank u btw
for helping me bypass my stupidity

Hi guys!
Please tell me where can I get API Token?
And what to add here?
ur webhook url, place where info will go
if you're not going to use webhooks, ignore that field
Is that token a bot token or api token?
and one more thing how can I use top.gg api with blapi package to display server count
oki
Why?
than which weebhooks can I use?
https://github.com/top-gg/java-sdk is too outdated
An API wrapper for https://discordbots.org/api/docs that works in Java - GitHub - top-gg/java-sdk: An API wrapper for https://discordbots.org/api/docs that works in Java
like alot
There's no-one maintaining it, nor are prs reviewed
you cannot post your server count when your bot is not approved
bot has been approved
its for my friends its a bot with him and it isnt working
@restive otter's
thats with your bot id
ok
epic
@tidal idol do u know how to make upvote counter in a discord channel with top.gg webhooks
like that?
Yea
alr lemme see
ok
You just fetch the user by the user ID you got from topgg and post a message in a channel you want.
That doesn’t require to rely on third party services.
like a bot does that
Yes, you’re using your bot to fetch the user and also to send a massage to a channel
could someone help me use the top.gg events in discord.py in cogs
cause im using cogs and sending tests but it dont work
dblservercount
To have your bot's server count displayed on Top.gg, please read the documentation on server/shard posting.
login?
i will
ngl @hearty lintel update gif when
i've just made one
its saving
@rain heart
so
i know i have the right token because the autopost server count is working
but the on_dbl_vote event is not being called
(python)
anyone?
ping me if you reply
If you receive webhooks the current timestamp is the way to go.
Just add 12 hours to it and you got the timestamp somebody can vote again.
Any other way? Cuz I mean it's not just for 1 person
Have you set your webhook on your webhook settings on topgg
No, topgg doesn't provide the timestamp when the user has voted.
You have to take the timestamp when receiving the webhook.
???
what does that mean
(i have a token)
@rain heart?
Hello
I am using webhook-topgg.com
But...
I want a webhook msg like this when someone votes...
Shayokh voted for Spark Bump! Thank You!
Voter id : id_here
So how to write this exact content here?
I'm using the Python library
He's not asking about what library ur using, he's asking did you set up ur webhook and add it to ur bots top.gg page?
Not the correct channel and server
You gonna receive webhooks sent by topgg, take the user ID provided as data in the webhook, fetch the user using your bot, send a message to whatever channel (DM) you want.
i had an issue with webhook-topgg.com, i set it all up, it worked when it sent a test, but as soon as i closed the tab, it stopped working, even when actually voting. am i doing something wrong?
@jaunty plank
did you test it with top.gg?
hmm, can you dm me the url you used on topgg?
yeah, one sec
@jaunty plank The voter id?
You want the voters id?
On the third page the bottom menu lists all the variables. Can't remember which is the voter id on the top of my head
E.
I still don't understand
Bruh
hello, how can shard display, number of servers, etc. can i show
dblservercount
To have your bot's server count displayed on Top.gg, please read the documentation on server/shard posting.
like a vote list?
servers cant use the api, so if you need a list you need to store them yourself.
Running from home?
yes
Did you port forward?
http://portforward.com/
Has guides for most routers
A port forward is a way of making a computer on your home or business network accessible to computers on the internet even though they are behind a router. It is commonly used in gaming security camera setup voice over ip and downloading files.
how do i make my bot log my server votes
You'll need to setup a webhook listener
https://docs.top.gg/resources/webhooks/
ok
so i need to add my bot in top.gg first ?
i just want my bot to count server votes
Nope, if you are setting it up for server votes your bot doesn't need to be added.
Only time your bot needs to be added is for bot vote webhooks
so wht to do first ?
Add the code for the webhook listener to the bot/wherever you want the event to exist.
what seems to be the issue?
ok
from my phone i can't
i'd recommend https://webhook-topgg.com
only from pc
ok
Initial server error
from my phone
strange, not sure why that would happen.
you're here anyways
I dont have mobile offically supported, but shouldnt have errored
idk why
(reason being discord doesnt let you create webhooks/view webhooks from mobile)
so it wasnt a priority
are you planning to use the api?
webhooks dont need the topgg token
I want to do vote system
i need the token
but there is no token
oh ok i don't need the token, just webhook
is there a way i can get the amount left of the cooldown after i vote?
that will need to be tracked by you.
ah, alright, what im doing now is whenever they use the command the cooldown starts, but theres many flaws in it.
Would be best to use webhooks, and when they vote add 12 hours to the time and thats when they can vote again
yea ,but how would i do that for each user, thats what im stuck on
what do you mean?
same exact thing you are doing now, but only when they actually vote.
state your problem
The voting system is not working
when someone vote for my bot, the bot is not sending the message
Have you setup your webhook listener correctly?
Do you have an active connection listening to requests?
Is the webhook somewhat hindered by a firewall?
You could test webhooks with one of the following tools to make sure they work:
- reqbin
- postman
if you're not sure about any of these, nor about what any of the tools mentioned above are useful for, I'd suggest reading over https://sendgrid.com/blog/whats-webhook/
const Topgg = require("@top-gg/sdk");
const webhook = new Topgg.Webhook("123")
app.post("/voted", webhook.listener(vote => {
let channel = client.channels.cache.get("903363101422923797")
let user = client.users.cache.get(vote.user)
if(!channel)return console.log("channel was not found")
if(!user)return console.log("user was not found")
channel.send(`${user} voted for us, thank you`)
}))
This is my code
What hosting are you using?
replit
Have you also set your webhook url on top.gg after making sure it is functional using the tools above?
yeah
And it does receive requests?
Could you test your webhook using an actual vote than using the test vote button? If I remember correctly some users may have had issues testing their webhooks using it
And entered authorization aswell? In your case seems to be 123
yes
Remember the authorization on your webhook code and top.gg need to be equal, otherwise it will fail
yes im sure
Screenshot your current configuration on your webhook settings on top.gg, change the current authorization to something else for showing
and you have tried that exact url aswell? Could you add a debug line to your webhook code without processing anything?
So for example before your let channel and let user, a simple debug line that says "I received a request"
it did work now
thank you
What was the issue?
i think because i don't have
app.get("/voted")
it did work after that
Oh yeah forgot the endpoint then 👍
dblissues
Top.gg is currently facing multiple site issues that may cause your experience to not be great. The Development Team is actively working on these issues to try to fix them. There is NO ETA (estimated time) for when these issues are fixed.
Please refer to the message in #support labeled [Current Site Issues](#support message) to stay up to date on which of these issues are fixed and/or if the issue you're encountering is already known.
Please note: The linked message above may not be updated accurately, the team is already working on ways to reliably notify you about ongoing site issues. If you're unaware of a certain issue being already known by us, feel free to inform us and we'll inform you accordingly.
ok
no by cooldown i mean, when they use the !vote command, it starts the cooldown for it.
yep, can do the exact same thing, but inside the webhook event.
Has the API changed since the website update in anyway? My server count isn't increasing on top.gg but I know my bot is joining more server...
You need to actively post your server count to top.gg
We do not fetch it ourselves as we technically can't
Hello
I am getting this webhook msg on test
There is lots of stuffs messed here
How can I do the \n?
I am expecting an output like this...
Shayokh just voted for Spark Bump! Thank You!
Id : voterid
It's Discord's caching on mobile, you can't do anything about it
webhookAuth How can I get?
You create the auth password yourself
Personally I just did something like “This Is My Very Secure Password”
You can just not put anything there
required for notifications
const dbl = new DBL('dbl token', { webhookPort: 5000, webhookAuth: 'dbl password' });
I'm saying okay
Ok
So, should your webhook discord be your own webhook?
ok
vote notification
ok
What do you want to use it for?
vote logs
i want to add reminder and much more https://test.repl.co/dblwebhook i use my code first in repl and paste that repl link into top.gg webhook section when i clicked test then getting embed but i am my bot on azure rdp so what i add ip ip/dblwebhook like this ?
Yep
i also try that
they're using repl I assumed
no my bot is hosted on azure rdp
have you checked if the actual webhook is working?
Have you setup your webhook listener correctly?
Do you have an active connection listening to requests?
Is the webhook somewhat hindered by a firewall?
You could test webhooks with one of the following tools to make sure they work:
- reqbin
- postman
if you're not sure about any of these, nor about what any of the tools mentioned above are useful for, I'd suggest reading over https://sendgrid.com/blog/whats-webhook/
yes first i try on repl that is working
copy paste time
i use repl.it bot only for test but i want to put that in my main bot code because i want to make vote reminder and much more soo
I thought they did
They do, but with a warning for invalid certificate
So long as the listener accepts SSL certificates
You can’t get SSL for IPs
You can have one for a domain but it will flag up on browsers
Fun
how get vote streak of a user?
( i use get requests)
you need to track that yourself.
streaks are not tracked by topgg
How to send a message to the very next channel the user interact with after voting?
You could theoretically do it this way:
-
get the webhook event requests from the user voting
-
store that state
-
every time a user interacts with that channel, check if that vote state is true, if yes, send that message
how can i get the current vote count of my discord.py bot with your api?
@jaunty plank
wooo
webhook not sending on vote atm
several people voted on my server and no webhook was sent
I'm out of town till Monday. I can't really do much if somethings wrong.
I'll see if I can look into it
hey I need help setting up server count for my bot
Just checked the number of votes using the site per hour, its not really dropped at all.
I'll check it in the morning. If I need to ill call cloudflare(only reason it might not work)
Does the test button on topgg work?
how do I start with :/
yeah like where do I add this?
bot is js
That goes in the header of the request.
If you dont know how that works probably best to use the js library.
hi guys, i need help, when i want to start the server to get the webhooks, the server start in http://0.0.0.0 etc.., someone can help me ?
0.0.0.0 basically means "from any end"
so it could be localhost, your internal ip, your external ip
yes
you need to use your external ip
but where can i put my external ip
const dbl = new DBL('my token :D', { webhookPort: 3000, webhookAuth: 'my pass :D' })
dbl.webhook.on('ready', hook => {
console.log(`Webhook running at http://${hook.hostname}:${hook.port}${hook.path}`);
});```
where can i put
(tag me if u have the solution pls)
can u help me please?
im trying to make a search bot function
therefore i want to return the id
but when i search
and i set the limit, offset, search to anything
i get this result: 247056469894103041 252442396879486976 281041859692855296 227435708183216128 293879161062424578 292953664492929025 218423174621167617 303904389968560129 226393343385403403 85614143951892480
who to get top api
what do you mean
for bot or server
that ^^
thats not something top.gg provide support for
as its a third party module/api
hey , anyone know how to show bot statistics in top.gg page?
im using python
number of servers that my bot is in and stuff
so i am trying to check if used has voted or not
index.js
const Topgg = require("@top-gg/sdk");
this.topgg = new Topgg.Api(process.env.TOPGGKEY);
and to check i am trying
client.topgg.hasVoted(`user id here`)
but i am getting this error
TopGGAPIError: 401 Unauthorized (You need a token for this endpoint)
create a env file with your topgg key






