#topgg-api

1 messages · Page 15 of 1

north cave
#

so the endpoint?

#

if im not mistaken

jaunty plank
#

If I was voting for luca for example, and I linked to users from my command /vote

https://top.gg/bot/264811613708746752/vote?frombot=true

The query would be frombot=true

#

you can use it to track things

north cave
#

ahh

#

copy that

#

thank you

night abyss
#

Can anyone help me with the top.gg API to check how often a user voted for the bot in discord.py v2.3.2?

jaunty plank
night abyss
night abyss
jaunty plank
#

You should just be able to do whatever you want with your bot inside the event

@bot.event
async def on_dbl_vote(data):
    # whatever you need to do with the vote event
    print(data)

night abyss
#

Do I have to enter my bot token somewhere after the import or does it take it automatically?

jaunty plank
#

Python knows what variable is which, as long as you use that variable it "knows"

night abyss
#

So I must import topggpy and then I can use the Event?

jaunty plank
#

yeah

#

its just an event, nothing fancy or crazy

night abyss
#

Oooh thank you. ^^

night abyss
jaunty plank
#

Someone the other day got it to work with Cogs

night abyss
#

Does it work something like this?

real yew
#

Is there any problem in this? because I only get received request and not "received vote":
const express = require('express');
const Topgg = require('@top-gg/sdk');
const app = express();
const port =
const auth =

const dbl = new Topgg.Webhook({ port, auth });

app.use((req, res, next) => {
console.log(Received request: ${req.method} ${req.url});
next();
});

app.post(
"/dblwebhook",
dbl.listener(async (vote) => {
console.log('Received vote:', vote);
})

jaunty plank
real yew
#

Nvm fixed it

#

thanks

honest kraken
#

Hey!

unique cedar
honest kraken
serene dagger
#

i use pycord

zealous vine
#

because they used discord.py when they made the sdk?

serene dagger
#

cant they remove force install of it =/

lilac grotto
#

Hello please I need discord member scraping

#

Hello

#

I’m a newbie

urban coral
#
[ ERROR ] UNHANDLED REJECTION: DiscordAPIError[50027]: Invalid Webhook Token
    at handleErrors (/home/container/node_modules/@discordjs/rest/dist/index.js:722:13)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async SequentialHandler.runRequest (/home/container/node_modules/@discordjs/rest/dist/index.js:1120:23)
    at async SequentialHandler.queueRequest (/home/container/node_modules/@discordjs/rest/dist/index.js:953:14)
    at async _REST.request (/home/container/node_modules/@discordjs/rest/dist/index.js:1266:22)
    at async InteractionWebhook.editMessage (/home/container/node_modules/discord.js/src/structures/Webhook.js:339:15)
    at async ChatInputCommandInteraction.editReply (/home/container/node_modules/discord.js/src/structures/interfaces/InteractionResponses.js:158:17)```
plush ember
#

Hi

urban coral
#

im receiving votes but it is giving invalid token error after sometime

urban coral
# lilac grotto Hello please I need discord member scraping
const { EmbedBuilder } = require("discord.js");

module.exports = {
    name: 'membercount',
    aliases: ['member','mc'],
    description: 'Membercount command of the server',
    async execute(message, client, args) {

        const m = message.guild.memberCount;
        const b = message.guild.members.cache.filter(member => member.user.bot).size;

        const embed = new EmbedBuilder()
        .setColor("Blue")
        .setTitle(`Member/Bot Count`)
        .setDescription(`**Member Count:** ${m-b} \n \n**Bot Count:** ${b} \n \n*Total Members: ${m}*`)
        
        message.channel.send({ embeds: [embed] });
    }
}```
#

it is a prefix command

jaunty plank
urban coral
jaunty plank
#

Do you use slash commands?

#

Those use webhooks

urban coral
urban coral
jaunty plank
#

🤷 re read the error, it says it's from discordjs.

jaunty plank
#

It says it's from an interaction too.

urban coral
#

yes but the bot isn't giving error from a slash command it's hard to find which command is giving that error i have like 60 commands d9_alonerain

jaunty plank
#

It's very likely the response to a command from time to time is taking longer than 3 seconds.

For example you might fetch from an API in a command, and the API you use sometimes takes longer than 3 seconds to respond, and you get that error.

vernal isle
# serene dagger cant they remove force install of it =/

Feel free to implement support for other libraries, test them all locally to make sure everything works, and open a PR. The best way to promote change is to step up and do something yourself.

To answer your question more directly, there's zero point in installing topggpy versions lower than 2.0.0a for non-d.py libraries as those versions rely on discord.py to work in the first place.

#

There has been no active maintainer for 3 years and the current changes are slowed down. Your best course of action, really, would be to wrap up a PR. Very uncertain about when it will be implemented, but at least you have something to blame the inactivity on.

jaunty steppe
#

I actually archived it because the top.gg API just hasn't changed in so long, that the project looked dead anyway. Not making bots anymore was another factor, but not the only one, as that wouldn't have stopped me from responding to PRs and issues.
I've since un-archived it an am working on a new version, since my knowledge of python has vastly increased since I wrote it :^)

#

If there's a bug feel free to open an issue, I'm going purely off of what the docs say because i don't have a popular bot on top.gg anymore

empty crow
#

I'm trying to set up the webhooks can anyone help me?

hazy ginkgo
#

Hi! What does mean isWeekend boolean?

#

Does it means that the votes count 2 in the weekend ?

#

Well in the analytics of my bot there was 1 vote (I voted yesterday) and yes got surprised it gave me 2 votes

hazy ginkgo
#

Alr

tidal idol
#

up to you whether you want to give extra rewards etc on the weekend but the site gives that anyways

hazy ginkgo
#

If this gives 2 votes then the reward should be 2x

#

At the moment my bot is pretty limited because mainly premium features, well I have only $8 to make work those features

#

(it's OpenAI API Requests)

#

But maybe I can give rewards about this to unlock the premium features temporarily

scarlet cobalt
#

One message removed from a suspended account.

safe sandal
safe sandal
#

cc @hearty lintel you look like the only active node-sdk maintainer 🙏

sturdy bough
south rose
#

what am i doing wrong?

knotty garnet
south rose
#

where?

knotty garnet
#

of the request

south rose
knotty garnet
#

right side part of the image, raw_headers

#

actually, no, that's the response

south rose
knotty garnet
#

those are the response headers

#

not aiohttp

#

try setting Content-Type: application/json on the request headers

knotty garnet
#

is your bot id correct?

south rose
#

that error happens in postman too, even though it's code that worked for me in the past on another bot

south rose
knotty garnet
#

is the token correct for that bot?

south rose
#

yes

#

if not another error will be shown

knotty garnet
#

well, try printing both guild_count and shard_count

#

to see their values

#

because there's nothing else to cause an error

south rose
#

i see in debug that they are valid

knotty garnet
#

oh wait

#

nah, nvm

#

try without passing shard_count

south rose
#

current code

knotty garnet
#

well there's nothing else that could error

south rose
#

yeah idk it worked in the past

#

even running in postman on my other bot that it worked in the past now showing the same error, even though i didn't touch it since and the token and bot id is unchanged

#

what happened in that date?

knotty garnet
#

on postman it's probably erroring because you're passing the value as a text

south rose
#

i tried to pass the vale in any form possible

#

and in the past it worked

rich void
#

Does making the bot interact by saying "vote for bot on topgg to be able to use the command" use the topgg API?

runic creek
#

It depends entirely on the logic of your code, but I assume that to send a "vote for bot on topgg to be able to use the command" message requires you to first check whether the user voted or not and only when you find out from the API that he did not vote, do you send this message

#

If you are going to check this for several commands every time someone uses them, you can quickly reach the ratelimit that will be imposed on your top.gg token

sturdy bough
jaunty plank
#

I was 5 seconds too slow

#

😦

sturdy bough
gilded wind
#

@rich void

#

Donde veo eso

hollow iron
#

right so, wtf?I figured initially this was probably caused by vs code just not saving, but then I updated it again and it's still 401ing

#

thing is, this exact code used to work till it just didn't

dry maple
#

Make sure its actually grabbing the token from the env

#

Might have bugged out and now process.env.topggtoken or whatever is empty or null/undefined

hollow iron
#

seems that is what's happening and I have no idea how to fix this

#

especially considering every other variable is working

dry maple
#

How are you loading these variables?

inner bloom
#

Hi little question, am I doing something wrong? when I try to test the webhook there is no message being send I also tried removing "canary." and even created a new one or does it just not work with discord webhooks?

dry maple
#

You make your own web api with a post endpoint that receives the data top.gg gives you

inner bloom
#

Ah okay thanks Miku_Heart

dry maple
#

👍

hazy ginkgo
#

npm i dotenv

then just add at the top of your index.js file:

require("dotenv").config()
#

if you use ESM :

import dotenv from dotenv
dotenv.config()
#

if your index.js is not in the same folder as your .env file, you should set a parameter in the config({...}) method to set the path to it, but I forgot the name of the parameter

#

And also, it should look like that

#

if your variable in .env is like that OPENAI_API_KEY then to get this value, you must spell exactly the same thing: process.env.OPENAI_API_KEY

#

process.env is set everywhere when dotenv.config() is called at the very start of your nodejs process.

#

But if your server is actually not linked to your Discord Client, you should import dotenv in your webapp / REST API main file

#

@hollow iron do you still have this issue?

#

Sorry for the ping, and sorry if I said too much, I'm not that qualified

hollow iron
# hazy ginkgo <@266162824529707008> do you still have this issue?

so my co-dev on this project got it to work, and honestly it really was not my decision to use .env file as I usually use just config.json, rather it was my co-dev's decision, so I don't really understand .env that well as I just never bothered with it, so your explanation was certainly helpful on that

hazy ginkgo
#

Ah I see!!!!

#

So you just populated process.env with a config.json file?

#

Well, I really don't know how it works

#

To make it works on all files in the workspace

#

(Well I don't know how dotenv does that too)

#

Ah wait, no your co-dev uses .env while you, use config.json ?

dry maple
#

their project uses .env

#

its just aspheria is used to using a json file normally by the sounds of it

hazy ginkgo
#

Yeah I just understood, I literally read it too quick

dry maple
#

all dotenv does btw at least in node is parse your .env file and populate process.env with those key's and values

hazy ginkgo
#

ye

#

Like, is process.env global ?

dry maple
#

ofc

hazy ginkgo
#

I mean, if we change process.env in one file, does it change for other files ?

dry maple
#

it's your processes environment

hazy ginkgo
#

I hope

#

It might be useful

#

To store things

#

Like caching

#

idk

dry maple
#

iirc you can access env variables outside of your process like predefined ones from settings

#

but not from another node process no

dry maple
#

never cache anything in process.env

#

thats terrible

hazy ginkgo
#

No no, not process.env

dry maple
hazy ginkgo
#

but like we create a process.cache property

#

Yes I know

#

Let's go

restive otter
#

In the TopGG, my bot shows as 784 server count, but the real server count is 960

#

how can I change and fix it?

#

and my api also well connected

jaunty plank
#

It looks like you stopped posting your stats on April 17th/18th

restive otter
#

and well connected with the topgg api key

jaunty plank
#

Whats the code you're using?

hazy ginkgo
#

Seems like my username is really not updated in the topgg api

idle wedge
#

Where am I supposed to put the userID paramater? I'm confused

```fetch(https://top.gg/api/bots/1249455985156685834/check, { headers: { 'Authorization': "woah" } }).then(res => res.json()).then(data => client.logger.info(JSON.stringify(data)))

#

[2024-06-26 12:17:31] [INFO] {"message":"Missing parameter 'userId'."}

hazy ginkgo
#

after the /check

#

/check?userId=userId

idle wedge
#

ah thanks

hazy ginkgo
#

If it still doesn't work, try adding userId in the data/body of the request

#

i'm not sure

hazy ginkgo
idle wedge
#

Is there any way to grab the date the user voted?

hazy ginkgo
#

Mmmh

idle wedge
#

So I can do smth like this
.addField(`**Last Voted:**`, data.votedAt ? require('moment')(data.votedAt).format('lll') : "Never")

#

votedAt doesnt exist

hazy ginkgo
#

You should create a webhook to receive vote

idle wedge
#

But yeah

hazy ginkgo
#

so an http server

idle wedge
#

Was hoping to avoid that and have an endpoint for it

hazy ginkgo
hazy ginkgo
#

Ah I see

#

wait

#

nop

#

seems like there is no votedAt or votedTimestamp

#

in the response scheme

idle wedge
#

Damn it

hazy ginkgo
#

Yeah

#

so you should create a rest api to receive votes and store them

#

or cache them

#

it's actually i'm doing

idle wedge
#

Whole lot of stuff just to get that

#

Lovely

hazy ginkgo
#

Ye

hazy ginkgo
#

an embed should look like this:

#

It's the latest version of discord

#

with slash commands

idle wedge
#

from an old bot of mine

hazy ginkgo
#

Ah ok

#

Oh ok I see

hazy ginkgo
#

I got everything I need

gaunt steeple
sturdy bough
#

If the user hasn't voted, I get this error: Expected the value to be an object, but received string instead

dry maple
#

and post the full error

unique cedar
#

Can someone explain to me how i can do vote rewards? Like you vote for my bot and when you are on my Discord Server you will get the voter Role for 12hours and then Automatic removed and a notify Message in a Channel

dry maple
#

If you want to force them to bei n your server that is

#

Otherwise keep track of it in some sort of temp cache as they expire every 12h

unique cedar
#

I don't want to force them.

dry maple
#

You can do a pre-command check to see if they are in the voter cache also check top.gg in case your api missed it

unique cedar
#

A vote reminder + vote Message would Work too. Currently i'm Using topgg-webhooks Website

#

And that only sends a message. And no vote reminder

unique cedar
#

Nicee

#

Good luck with that

icy aurora
#

thanks I need stop being lazy first

subtle forge
#

Hlo

thorny agate
#

My response from the request was: {}

#

is that ok?

#

How long does it take on the bot page on top.gg to update stats after sending a successful request above?

runic creek
molten void
#

anyone have idea why top.gg is spamming my post api?

restive otter
steep snow
jaunty plank
steep snow
#

https://top.gg/bot/1089504577734311976?s=08fcf1e863c02

#

this type of link

jaunty plank
#

Have you added the bot to top.gg?

steep snow
jaunty plank
#

Then just copy the URL at the top of the page when you're on your bots page.

dawn light
#

how to make top.gg send the votes to my discord webhook

jaunty plank
#

Top.gg webhooks don't natively support discord webhooks.

You'll want to forward the webhook yourself, or use a third party service.

sleek ledge
#

:craig:,joil:
:craig:,leaniv:

#

graig ┬─┬ノ( º _ ºノ)

#

:craig:,joil:
:craig:,leaniv:

bright quarry
#

Am i doing something wrong? i'm trying to post my bot's server count

dry maple
#

Who knows

bright quarry
#
url = f'https://top.gg/api/bots/{self.bot.user.id}/stats'
headers = {
    'Authorization': self.token
}
payload = {
    'server_count': len(self.bot.guilds)
}

async with aiohttp.ClientSession() as session:
    async with session.post(url, headers = headers, data = payload) as response:
        if response.status != 200:
            logger.error(f'Failed to update server count on top.gg: {response.status} {await response.text()}')
dry maple
#

We need to see some code and any errors first before we can tell you that

bright quarry
#

Failed to update server count on top.gg: 400 {"message":"Invalid input"}

#

don't know why it's invalid

dry maple
#

iirc data sends it as a form url encoded

#

there should be json= on post as well

bright quarry
#

i forgot that was a thing

#

works now ty

dry maple
#

Also

dry maple
#

if you are interested

#

:)

bright quarry
#

cause its severely outdated

dry maple
#

Oh?

bright quarry
#

yeah

dry maple
#

iirc they've updated it

bright quarry
#

last updated in 2021

dry maple
#

Ah right, yea the original owner of the pypi package no longer maintains it, they have yet to get access to the org/account and or upload a new one.

bright quarry
#

I remember when i was using it for the first time i literally had to copy the files of the library and edit it until it barely worked lol

#

and just put the library's code in my own bot

dry maple
#

I see yea, they (as in a new maintainer) are working on updating the python sdk soon™️

#

The prs are in the works

bright quarry
#

alright cool

#

i might make a pr myself sometimes ngl THONK

dry maple
#

Good luck,

cloud sky
#

hi, how to make interval at topgg-autoposter

const { AutoPoster } = require("topgg-autoposter");

module.exports = (client, logger) => {
  const ap = AutoPoster(
    "secret",
    client
  );

  ap.on("posted", () => {});

  ap.post();

  setInterval(() => {
    ap.post();
  }, 21600000);

  return ap;
};```
doesn't work
gusty locust
#
const poster = AutoPoster(config.topggtoken, manager)
    poster.on('posted', () => {
        console.log(`posted stats to Top.gg!`)
    })```
no interval needed afaik but i havent touched my code in awhile
#

it does it every 30 minutes

dry maple
#

^

#

no need for an interval thats the point of the Autoposter

astral niche
#

can someone help me with top.gg apis? i just need to show a message like "Vote the bot to use this command"

#

wich api should i use?

#

like to check if the user has voted

dry maple
astral niche
#

for the bot id should i use the discord bot id?

dry maple
#

whatever is the id of the bot you have on top.gg

astral niche
#

what does it mean?

#

like why is unauthorized

jaunty plank
#

Did you include your authorization header?

astral niche
astral niche
plain pagoda
#

Is there a /get path for top.gg to get the amount of votes a bot has?

dry maple
gaunt steeple
#

was i pinged here?

cloud sky
honest kraken
dry maple
#

What

icy aurora
honest kraken
#

O

frigid warren
#

Hey is it possible to log votes with the Top.gg API With Botghost

#

or not

icy aurora
#

I don’t think so

frigid warren
icy aurora
jaunty plank
icy aurora
#

thanks homie

humble bone
#

cant find the webhook

#

on my bot

jaunty plank
#

My site just forwards it to a discord webhook.

Its in the channel settings > integrations > webhooks

#

If you want your bot to have a top.gg webhook you can't use my site

humble bone
#

i like yours

#

i might have to have bot approved first

humble bone
#

till my bots approved

jaunty plank
#

Yeah

humble bone
#

cant wait for it to be approved lol

restive otter
#

Can I get a bot for a never have I ever server?

meager linden
#

Yo can you use topgg with py-cord?

dry maple
#

Of course

gaunt verge
#

Maw

willow spindle
vast hound
#

If we use bots/:bot_id/check endpoint to check for individual vote will the voted reset to 0 after 12 hours or it will stay at 1

dapper monolith
#

Hey guys, idk if im right here, but how does the "invites" are meaning? i mean currently it shows 11. Last days was over 20 and 30.

How should i understasnd it? my bot would be in over 100 servers already with these stats i see ? 😄

dry maple
#

Views are just how many people looked at your bot, invites are how many people invited your bot

#

This doesn't mean thats how many servers you have, this just means how many people have invited it through top.gg

#

If your bot was later kicked, top.gg does not reflect that

#

As its impossible to do so

dapper monolith
#

Ahh, yea makes sense now. Thanks for info. i mean the views etc its clearly.

jaunty plank
#

discords side

dry maple
#

Right sorry

jaunty plank
#

(maggie hit enter for me mid sentence)

dry maple
#

I meant to clarify that

untold summit
#

How do I register my Discord Server or find it on Top.GG and Implement the voting system for it on the Server itself and Top.GG ?

dry maple
#

Server listing has been discontinued

untold summit
#

Oh, when, or will it get picked up again ? or which other ways like that are there ?

dry maple
#

It is unknown when it will get picked back up again if at all. As for alternatives a simple google search will lead you the right way

restive otter
#

Hi

short oriole
#

hi how i can get my api ?

runic creek
#

Your token should be there, thanks to which you will be authorized when using the top.gg API

weak karma
#

how do webhooks work on top gg?

jaunty plank
weak karma
jaunty plank
#

you didnt use a discord webhook right?

#

Its not a discord webhook

weak karma
#

I didn't understand

#

@jaunty plank

jaunty plank
weak karma
#

😐

jaunty plank
#

Auth is a password, since you're the one hosting the server you're the one that can pick it.

#

as long as its the same between your code and Top.gg

torn vigil
#

Hi there, i don't want to use @top-gg/sdk package, i use my own post like this: ```ts
const topggAuthorization = process.env.TOP_GG_AUTHORIZATION;
app.post('/webhook', (req: Request, res: Response) => {
const authorization = req.headers.authorization
if (authorization !== topggAuthorization) {
return res.status(403).send('Invalid authorization!')
}

const data = req.body;
console.log("Received: ", data)

res.status(200).send("Success")

});

app.listen(port, () => {
console.log(Webhook server listening on port ${port})
});

Can i do this way to receive Topgg data?
dry maple
#

Indeed you can setup your own webhook webserver

#

the sdk is only there to help

#

you dont need to use it at all

unique cedar
#

@signal hawk

short swift
#

/user avatar render

scarlet cobalt
#

One message removed from a suspended account.

unique cedar
#

/user avatar render

burnt parcel
#

how do i get the api key?

burnt parcel
#

-__-

unique citrus
#

we do need json requests

burnt parcel
#

we surely do

unique citrus
#

but then the python libaray doesn't

#

one sec

unique citrus
#

it must just do the heavy lifting in the background

violet sun
#

Hello is there a way to get all votes from a user for my own bot? Whats the variable called?

long vector
#

@tacit elm

spring pebble
#

is there any way of debugging the api? I moved to a different vps, so I just changed the endpoint topgg would send votes to but my vps doesn't seem to be receiving anything

restive otter
#

pretty sure theres a test vote button

spring pebble
#

but i fixed it

#

port wasn't opened on the firewall

#

stupid mistake

distant garnet
#

I'm trying to do a webhook when the user vote in the bot.
Is there anywhere in the strucutre that the top.gg send in the post from the webhook?

summer linden
#

Hey by the way, in the Rust Top.gg library, Client::has_voted() currently uses the wrong endpoint resulting in it returning InternalServerError
I've opened a PR to fix it: https://github.com/Top-gg-Community/rust-sdk/pull/22

GitHub

Previously the endpoint this method used was /bots/votes, which returns the last 1000 votes instead of returning whether or not a single specified user has voted, which is what the /bots/check endp...

dry maple
#

Thanks, nice catch. Im sure someone will be along to review it!

untold sparrow
#

Put on my big boy review shoes

#

Thank god for GitHub mobile

whole wolf
#

on_dbl_test works fine when I'm requesting from insomia but on_dbl_vote doesn't work at all doesn't get any data and I've ran out of alt accoutns to try and fix it and its annoying.

whole wolf
#

Literally can't find a way to fix this

#

this is just painful

#

I've added the webhook url the authorization in Webhooks done the same thing here

        self.topgg_webhook = topgg.WebhookManager(self).dbl_webhook(
            "/webhook",
            auth_key=os.getenv("WEBHOOK_PASSWORD")
        )

then i run it

await self.topgg_webhook.run(80)

then it doesn't even respond

    @commands.Cog.listener()
    async def on_dbl_vote(self, data):
        print(data)
        try:
            user = await self.client.fetch_user(data["user"])
            if user is None:
                return
            channel = await self.client.fetch_channel(1266682025604284447)
            if channel is None:
                return

            await self.reward(user, channel)
        except Exception as e:
            print(f"[⬇️] Failed to reward user: {e}")

But works on dbl test

    @commands.Cog.listener()
    async def on_dbl_test(self, data):

        user = await self.client.fetch_user(data["user"])
        if user is None:
            return
        channel = await self.client.fetch_channel(1266682025604284447)
        if channel is None:
            return

        await self.reward(user, channel)
#

Testing on insomia works fine

#

python 3.11.9

#

please help

vapid cape
knotty garnet
vapid cape
#

you can if you're root

knotty garnet
#

hm? how does that work?

#

like, does it intercept http entirely?

vapid cape
#

you can run python or node on port 80 just like you would run nginx

whole wolf
#

Testing on this works
[IMAGE REMOVED]

#

I can try and change the port dk if that'll do anything

vapid cape
whole wolf
#

on_dbl_test is triggered whenever I do a test on insomnia but whenever I vote on top.gg on_dbl_vote do not trigger

#

Send Test here doesn't work either
[IMAGE REMOVED]

vapid cape
whole wolf
#

The Authorization token is set on both

whole wolf
vapid cape
#

yes

#

port 80 is http

#

unless you have a reverse proxy somewhere

whole wolf
#

Well I tried http earlier and it didn't work either

knotty garnet
#

try attaching topgg listener to 443

vapid cape
#

in your insomnia you did http

whole wolf
#

yea https works too
[IMAGE REMOVED]

#

I change the port to a random number

#

idk if it'll work

vapid cape
#

is your host something that supports automatic port assignment or something?

whole wolf
#

[IMAGE REMOVED]

#

[IMAGE REMOVED]

vapid cape
#

internal port 444

whole wolf
#

yea i just updated it

vapid cape
#

then you should set it to 444 on python too

whole wolf
#

I have

vapid cape
#

well try to use the test button on topgg

whole wolf
#

nothing

vapid cape
#

well, last time this exact issue happened, where it would work in an http client like postman/etc, but not on the website's test button, the user ended up having a typo in his topgg url address

whole wolf
#

[IMAGE REMOVED]

vapid cape
whole wolf
#

It printed

vapid cape
#

im out of ideas then, i would try adding some low level logging on the python webserver under the hood to look if any http request actually comes

#

i g2g out now tho

whole wolf
#

ok

whole wolf
#

Ok instead I just use fastapi

runic gull
#

I notice that in the topgg python sdk docs there's two different webhooks (server and bot votes)

#

but on topgg config dashboard you can only configure one url

#

Is this supposed to be the bot vote one? or how is this supposed to work? I'm very confused lol

jaunty plank
#

Servers are deprecated on top.gg

#

we had a server list, we're now only a bot list.

runic gull
#

I see, so I should just do the full url with the vote webhook route?

#

thank you ☺️

#

btw your cat is very cute

runic gull
#

So when I vote topgg is POST'ing on my webhook 10 times, is that normal? ._.

restive otter
#

which top.gg retries to send the vote because it thinks it failed to send

runic gull
#

oh I see

#

I guess it must be nginx or my firewall

icy aurora
#

I had same problem with that before

#

you have to return 2xx status on your dbl webhook

runic gull
#

This is my code:

@task_error_handler
async def handle_vote(self, request):
    LOG.info("Incoming vote POST.")
    auth = request.headers.get("Authorization")
    if auth == self.dbl_auth:
        data = await request.json()

        # Log the received data
        LOG.info(f"Received vote data: {data}")

        user_id = data.get("user")
        if user_id:
            # Write to db
            weekend = data.get("isWeekend", False)
            LOG.info(f"Received vote from user ID: {user_id} {weekend=}")
            db.quests.write_topgg_vote(int(user_id), weekend)

            # --- SO FAR CODE MADE IT HERE ---
            return web.Response(status=200, text="OK")
        else:
            LOG.warning("Received vote data without user ID")
            return web.Response(status=400, text="Bad Request: Missing user ID")
    else:
        LOG.warning(f"Unauthorized vote attempt. Auth: {auth}")
    return web.Response(status=401, text="Authorization failed")

web is aiohttp.web. I noticed topgg was calling many times bc there were 10 identical entries in my db.

#

It should be returning 200 pepe_scrajj

icy aurora
#

@vapid cape you know python more than me ^

runic gull
#

I'm on a reverse proxy with nginx, so I was thinking maybe that could be related

#

btw thank you

icy aurora
#

idk why it’s not returning to 2xx codes

#

Im ts and js developer but idk anything about python

runic gull
#

ok I figured it out, it was the wrapping function not allowing the response the be returned all the way out

#

I guess I'm glad it was my code lol

#

thank you again!

icy aurora
#

Your welcome

vocal sparrow
#

hi, is possible create a vote command?

#

that works really

rain heart
#

Vote command in the sense of voting for the users behalf

#

No

vocal sparrow
#

damn ok thanks

fallen thistle
#

Is the POST stats API broken?

#

I have no errors in my code but for a few weeks now my guild count has not updated

#

Even though I post it daily

#

Pls ping if you respond

icy aurora
icy aurora
fallen thistle
#

Sure not ideal but Ig I‘ll try that

icy aurora
#

btw it might take few to refresh on the page

golden adder
zenith grove
#

hello, I want to limit my command's usage to 10 per hour, but if a user has voted in the last 12 hours, then allow him additional 10 usage's. What I've been thinking is include the number of usage's left in command's embed's footer(for example "you can use this command 9 more times".

Since I need the footer to change every time the command is run, then I need to know if the user has voted.
From what I've understood, there are two approaches:

  1. Create a webhook and store the users along with an expiration date. When the command is run, check if the user has voted.
  2. Call the API each time the command is run and check if the user has voted.

I've been wandering if the second option will get me rate limited

#

Keep in mind that it's my first time working directly with APIs, so speak hUmAn language please

jaunty plank
#

If you have a discord bot, you have worked with an API.

But, yes calling the API each time the command is run will likely result in a ratelimit.

#

If you go that route, you can store if they have voted for some time, that way you only check if they voted per person once per x time.

dry maple
zenith grove
#

and so which one is the better option as for the bot's resources and etc.

jaunty plank
#

Both in theory are pretty light, webhooks are the correct way to handle it.

zenith grove
#

and store them in a set

#

or a map

#

because I don't really want my db to be involved

#

oh forgot to add: thank you so much @jaunty plank @magic swift

humble oxide
#

how to do vote system in discord.js? ''

jaunty plank
#

Like how to get vote events?

modern nimbus
#

How can I get topggauth

#

@jaunty plank

frigid reef
worldly nacelle
slim apex
#

any plans to add user app install counts?

restive otter
#

is there even a way to detect user app installations and count them properly

wintry cape
#

Is there a way to simulate voting?

jaunty plank
wintry cape
#

I understand, but the problem is that voting can only be done once every 12 hours

restive otter
#

me when i get an answer and do something different

jaunty plank
#

the one in the webhook section when editing your bot

wintry cape
#

I'm outside, my screen is dark, I didn't notice the button

#

Thank you, now I just have to figure out what the actual spinning donut I'm doing

slim apex
worldly nacelle
#

how to get the quantity of votes a user has?

restive otter
#

you have to set up webhooks and a database to do that

#

top.gg only provides the people who voted

worldly nacelle
lethal hound
#

Discord also shows the number in the dev portal

#

but you gotta minus any servers if you have emoji ones ofc

untold trellis
#
import disnake
from disnake.ext import commands
import aiohttp

class VotingCog(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.topgg_token = "token"

    @commands.slash_command(description="Voting")
    async def voting(self, inter):
        embed = disnake.Embed(
            title="Vote",
            description="Click on the buttons below to vote or check your vote.",
            color=disnake.Color.blue()
        )
        
        vote_button = disnake.ui.Button(
            label="Voting",
            url="https://top.gg/bot/1256968181180928080",
            style=disnake.ButtonStyle.link
        )
        
        check_button = disnake.ui.Button(
            label="Reward",
            style=disnake.ButtonStyle.primary,
            custom_id="check_vote"
        )
        
        view = disnake.ui.View()
        view.add_item(vote_button)
        view.add_item(check_button)

        await inter.response.send_message(embed=embed, view=view)

    @commands.Cog.listener()
    async def on_button_click(self, inter):
        if inter.component.custom_id == "check_vote":
            user_id = inter.author.id
            headers = {"Authorization": f"Bearer {self.topgg_token}"}
            url = f"https://top.gg/api/bots/{self.bot.user.id}/check?userId={user_id}"
            
            async with aiohttp.ClientSession() as session:
                async with session.get(url, headers=headers) as response:
                    if response.status == 200:
                        data = await response.json()
                        if data.get("voted") == 1: 
                            time_left = 43200 - (data.get("last_vote") % 43200) 
                            hours, remainder = divmod(time_left, 3600)
                            minutes, seconds = divmod(remainder, 60)
                            time_left_str = f"{hours}ч {minutes}м {seconds}с"
                            await inter.response.send_message(
                                f"You have already voted. You will be able to vote again via: {time_left_str}.",
                                ephemeral=True
                            )
                        else:
                            await inter.response.send_message(
                                "You haven't voted yet. Vote to support the bot!",
                                ephemeral=True
                            )
                    else:
                        await inter.response.send_message(
                            "An error occurred while checking the voice. Try again later.",
                            ephemeral=True
                        )

def setup(bot):
    bot.add_cog(VotingCog(bot))

😭

#

help me how to do this

dry maple
#

Right so what is the issue

untold trellis
dry maple
#

You need to use a valid top.gg token

#

your topgg_token is invalid

untold trellis
#

Maybe

dry maple
#

and or your formatting of the header is wrong

untold trellis
#

where can I get it

dry maple
#

You are doing it wrong

#

remove Bearer

#

it should only be your token

untold trellis
#

sec

#
    @commands.Cog.listener()
    async def on_button_click(self, inter):
        print("[VotingCog] Button clicked with custom_id:", inter.component.custom_id)
        
        if inter.component.custom_id == "check_vote":
            user_id = inter.author.id
            print(f"[VotingCog] Checking vote for user_id: {user_id}")

            headers = {"Authorization": self.topgg_token}  
            url = f"https://top.gg/api/bots/{self.bot.user.id}/check?userId={user_id}"
            print("[VotingCog] URL for checking vote:", url)

            async with aiohttp.ClientSession() as session:
                async with session.get(url, headers=headers) as response:
                    print("[VotingCog] Response status from vote check:", response.status)
#

403 again

dry maple
#

then your token is invalid

#

What token are you using exactly, and or where are you getting this token

dry maple
#

Interesting, then it should work, assuming you copied the entire token properly and not missing any characters

untold trellis
#

Well, I copied everything, if there was a button to copy everything at once without selecting a token it would be a little more convenient xd

#

If anyone knows what the matter is, can you let me know

untold trellis
dry maple
#

no

untold trellis
#

Why doesn't it work then? 😭

dry maple
#

akashrug I've ran out of ideas myself, your code visually looks okay

#

I see no syntax errors or any other problems that could occur

untold trellis
#

what could this mean?

lone spade
#

Hi

#

I have a question, how i can get top.gg api key?

lone spade
runic creek
#

I don't know any other, so yes

lone spade
#

And how i can put a webhook? like, what is

runic creek
#

A webhook is nothing more than a webserver that receives a request when someone votes for your bot. Thanks to this, you are able to track when exactly someone votes without the need to use the API (API has a rate limit)

untold trellis
#

let me know what I'm doing wrong😭

#

I copy the token correctly but for some reason there is an error

#

I copy from the console so as not to miss a letter just in case

#

😭

#

what rights does the bot need and what rights does the token need?

#

[VotingCog] Voting command invoked by user: 1217948886317138064
[VotingCog] Voting message sent with buttons.
[VotingCog] Button clicked with custom_id: check_vote
[VotingCog] Checking vote for user_id: 1217948886317138064
[VotingCog] URL for checking vote: https://top.gg/api/bots/1257007894168338475/check?userId=1217948886317138064
[VotingCog] Response status from vote check: 403
[VotingCog] Forbidden (403) - Possible issues with token or permissions.

#

hewp

copper fiber
#

my bot got approved today, but i cant post stats nor check votes via the api?

#

should i wait?

icy aurora
#

it’s should fix the problem

exotic karma
#

how long does it take for the server count to update after calling the api?

exotic karma
#

dont worry everyone. it's okay. it updated.

restive otter
#

Hiding the bot ID 661408036220436511 isn't really useful, it's public information.. Should hide the API token, which isn't visible either way.

exotic karma
bold jetty
exotic karma
bold jetty
#

nope, id is public

#

So it's not advertising after alll

#

bot id isn't crucial, but token is, that's what should be hidden instead

exotic karma
#

the id is public, but posting it has been considered advertising so i dont do it.

bold jetty
#

it doesn;t mention

#

doesn't*

#

bot id as advertising

#

mostly servers, streams and stuff like that are advertisements

#

not posting a bot id

jaunty plank
#

I do appreciate the effort of hiding it though

exotic karma
#

i've been banned for it before so i'm extra careful. although it was probably an overzealous mod

jaunty plank
#

Looking back at your ban, you probably should have been warned.

I had no idea you were banned at one point 👀

rain heart
#

I mean 4 years ago, previous top.gg moderation that wasn't as relaxed as today

stoic locust
#

is this fr3e clan ?

#

server

#

for join clan in ps99

jaunty plank
#

nope

#

This is the support server for Top.gg

humble bone
#

how do i get my top.gg api token

exotic karma
humble bone
#

thanks

unique cedar
exotic karma
#

you mean this?

dry maple
#

💀

exotic karma
#

i was hoping someone tried to type it all in and see if it worked

dry maple
errant panther
jaunty plank
errant panther
jaunty plank
#

Fill in in your bot id
https://top.gg/bot/:your-bot-id/webhooks

Or go to the edit page of your bot and click on "webhooks" to go to the webhook tab

#

then fill in your information

inner pelican
#
const request = await axios.post(
      `https://top.gg/api/bots/${botId}/stats`,
      { server_count: stats.servers, shards: stats.shards },
      {
        headers: {
          Authorization: process.env.TOP_GG_AUTHENTICATION_TOKEN,
        },
      }
    );

im using this code to post my bots stats and for some reason it is failing with the status 400

jaunty plank
exotic karma
inner pelican
#

ah it's fine, I got it fixed. issue was I should have been using shard_cpint

fading helm
#

How can I access my top.gg token?

upper gorge
#

Can I have some help please I am trying to find my top.gg token where can I get this from

upper gorge
#

Does anyone know what the endpoint for the total votes please

upper gorge
#

Are you sure this Web link works nothing is loading

tribal knot
#

@upper gorge the team are on it now

upper gorge
#

There's no rules are anything just 2 channels

upper gorge
#

Asking for my wallet address really come on

scarlet cobalt
#

One message removed from a suspended account.

#

One message removed from a suspended account.

jaunty plank
#

dominik so fast with the ban

dry maple
#

dominik always watching

scarlet cobalt
jaunty plank
#

hours, really fast ;p

scarlet cobalt
#

One message removed from a suspended account.

jaunty plank
#

++---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

  • maggie sitting on my keyboard
dry maple
scarlet cobalt
dry maple
#

Im sure mods have logs, but I doubt they check them constantly unless there is a need to

scarlet cobalt
#

One message removed from a suspended account.

jaunty plank
scarlet cobalt
#

One message removed from a suspended account.

dry maple
#

Thats a lot of food

upper gorge
#

@scarlet cobalt thank you

#

I've blocked them aswell

#

Also I've looked on the api endpoints and it's still not working

jaunty plank
# dry maple Thats a lot of food

Yeah, they're being fed the most in the morning. That's pretty much all of the food for the day.

I have it setup to feed them as soon as others start waking up, and feed a lot so they don't cry for people to feed them.

#

Since the mornings here there's three separate times everyone wakes up and is downstairs making coffee ^-^

jaunty plank
jaunty plank
#

It should be the thing I linked

upper gorge
#

But for some odd reason when I use points or monthly points it doesn't respond

jaunty plank
#

What do you mean?

upper gorge
jaunty plank
#

What scripting language is that? 👀

upper gorge
#

Bdscript lol

#

I use Bot design for discord

#

App

jaunty plank
#

Can you print things to console?
Or send a message containing just $httpResult

upper gorge
#

I can do both or when you say console do mean like a terminal

jaunty plank
#

Yeah

#

Just to see what its giving you

upper gorge
#

No I can't use a console in that form

#

It should work with $httpResult should anyway

#

The other endpoints work just not them lol

jaunty plank
#

I'm not sure how to debug this, unless you can send a message containing just $httpResult

upper gorge
#

Yeah should be able to

upper gorge
jaunty plank
upper gorge
#

Right ok thank you

ocean fiber
#

Can't I get the time (a unix timestamp or something) from the moment the user voted in my bot?

icy aurora
frosty void
#

im using the topgg/sdk package and I'm having some issues, does the users vote get set to false after 12h? cause when i vote i can just keep running my rewards command

runic creek
still roost
#

Top.gg Api doesn't work ?

await fetch(`https://top.gg/api/bots/stats`, {
                    method: 'POST',
                    headers: {
                        'Authorization': process.env.TOPGG_TOKEN,
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        "server_count": guildCount,
                        "shard_count": process.env.SHARD_COUNT
                    })
                }).then(res => console.log("✅ Top.gg stats update", `> Stats Actual: ${guildCount} Guilds`))

this call doesn't update stats on website

icy aurora
sharp cape
#

when's v1 coming out?

icy aurora
#

api?

sharp cape
#

yes

icy aurora
sharp cape
#

not by the docs

icy aurora
#

oh

#

nveer

#

never

sharp cape
#

yeah thought so

still roost
exotic karma
still roost
scarlet cobalt
#

One message removed from a suspended account.

jaunty plank
#

Honestly, I just consider the api v1 as it is.

#

Its been live for so long, with so few issues. There's no reason to not consider it v1

sharp cape
#

why was v1 actually ever mentioned in the docs tho

scarlet cobalt
#

One message removed from a suspended account.

#

One message removed from a suspended account.

jagged sky
#

In some rare cases i am getting votes inside on_dbl_vote twice?
What could be the reason of this?

austere latch
#

@jaunty salmon @craggy sentinel

dry maple
#

?

atomic burrow
#

Yo, anybody else having issues with top.gg not sending webhook request upon somebody voting for their bot? Webhook tests work, but voting just does nothing!

atomic burrow
# icy aurora no?

Strange, it isn't working for me.. Unless there's some kind of filter in place that prevents the bot owner/manager from voting for it's own bot..?

atomic burrow
#

Maybe adblocker preventing the vote from counting? Cuz after voting I can simply refresh the page and vote again.. With no effect once again

icy aurora
#

probably

atomic burrow
#

Rewards being requests sent from topgg to my local server ^

untold sparrow
icy aurora
#

indeed

atomic burrow
kindred sigil
#

can anyone gimme a code snippet how to track user who have voted

jaunty plank
#

What programming language?

kindred sigil
jaunty plank
lethal prism
#

Api broke? Got 502 bad gateway

#

I use @top-gg/sdk for sending the stats

#

It worked before

glacial whale
#

when will v1 release with more webhook events?

river spear
#

token, correct
auth, correct
then this

#

this has never happenned until today

#

theres also this in the terminal but the error message didnt show fully. it was pushed up

dry maple
#

What endpoint are you calling

#

Afaik any of the bot related endpoints minus finding a bot are restricted to only the bot the token belongs to

#

I may be wrong, but the docs uses terminology like your so it seems to imply that

#

Better yet

This example uses Luca but users are restricted to only receiving their own bots' votes. Replace the id with your own bot.

scarlet cobalt
#

One message removed from a suspended account.

bitter leaf
#

The bot won’t let me vote, it thinks I’m a robot. How do I fix that?

agile patio
#

hi

sand pendant
#

im having a problem with autoposter reporting false server count data to top.gg.. dont know what happened just started happening after i sharded. as soon as it starts posting. it posts the correct number of servers but after that every 30 mins its posting invalid counts... it used to report correct data and still does when i force set shards to 1... dont know why its struggling with 4 shards... :/

relevant code:

const { ShardingManager } = require('discord.js');
const { AutoPoster } = require('topgg-autoposter');
require('dotenv').config();
const token = process.env.DISCORD_TOKEN;
const topgg = process.env.TOPGG;
const manager = new ShardingManager('./bot.js', {
  token: token,
  totalShards: 4,
  timeout: -1,
  respawn: true
});
const ap = AutoPoster(topgg, manager);
let readyShards = 0;
manager.on('shardCreate', shard => {
  console.log(`Shard ${shard.id} launched`);

  shard.on('error', (error) => {
    console.error(`Shard ${shard.id} encountered an error:`, error);
  });

  shard.on('ready', () => {
    console.log(`Shard ${shard.id} is ready`);
    readyShards++;

    if (readyShards === manager.totalShards) {
      console.log('All shards are ready. Starting to send bot statistics.');
      ap.start();
    }
  });
});

manager.spawn({ delay: 25000, timeout: Infinity }).catch(e => console.log(e));
ap.on('posted', (stats) => {
  console.log(`Posted stats to Top.gg! 🟢 SUCCESSFUL | ${stats.serverCount} servers`);
});
ap.on('error', (err) => {
  console.error(`Posted stats to Top.gg! 🔴 FAILED - ${err}`);
});
sand pendant
#

so autoposter wont work for my case?

exotic karma
#

autoposter requires you to use sockets. this method is simpler

sand pendant
#

really liked autoposter though :/ wish it had worked.

icy aurora
sand pendant
#

did u use sharding manager built into discord.js

sand pendant
#

i wonder if its because im still on djs v13

exotic karma
#

this is all you need

// fetch the guild count from discord app store
const guild_count_api_response = await fetch("The URL of the API to fetch the guild count");
const guild_count_api_json = await guild_count_api_response.json();
const guild_count = guild_count_api_json?.directory_entry?.guild_count;

// update the guild count on top.gg
await fetch(URLS.topgg_api, {
    method: "POST",
    headers: {
        "Authorization": "", // todo: put your top.gg API key here
        "Content-Type": "application/json",
    },
    body: JSON.stringify({server_count: guild_count}),
});
icy aurora
#

let me grab my sharding file

sand pendant
exotic karma
exotic karma
#

no auth needed

sand pendant
#

im pretty sure my bot has to be on the app directory for it to work

#

because it wont take my bot id

sand pendant
exotic karma
#

yea

#

get on the app directory

icy aurora
# sand pendant

try my sharding file might want remove require("./server/server.js") part

sand pendant
icy aurora
sand pendant
#

what does it mean for discord to flag bots?

#

the only issues i had was with verification they denied me the first time.

icy aurora
sand pendant
#

idk wouldnt they send an email

sand pendant
icy aurora
icy aurora
exotic karma
#

I would just manually update the server count until it gets on app directory and then setup a simple program to update once every couple of days

#

this is the checklist

icy aurora
exotic karma
#

sounds good

icy aurora
#

since we are on topic of sharding i need edit few things on mine

fluid jetty
#

Hey, asking the stupid question but does the "send test" button send undefined vote data?

fluid jetty
#

🤔 got an actual user to vote and it turns out that all vote data is undefined. using the @top-gg/sdk npm package and webhook.listener()'s vote object is always undefined regardless of if a user is voting or if it's a test send. may be an issue with helmet ? 🤷 if anyone's knowledged, advice is appreciated

#
app.post('/dblwebhook',
      webhook.listener(async (vote) => {
      console.log("TEST VOTE");
      
      console.log(vote.user);
      if (!vote.user) {
          res.status(400);
         return;
      }
      // upsert user data for vote
   }));```

this is the endpoint I'm using
#

it seems like I'm just not receiving any data from voting users in my request body either? req.body evaluates to undefined every run / vote regardless of if it's a test

abstract monolith
restive otter
fluid jetty
# restive otter seems like an issue with your backend code

that's great to know, but I'm not sure if it really is the issue. I've checked the body that is being received (there is no middleware that would modify the request body), and the other endpoint I was using to test it shows no data in the request body at all. it could be, but I'm starting to believe that's less likely the more I'm experimenting with it. appreciate the response though

exotic karma
#

just the http stuff

fluid jetty
#

very confusing answer I'm sorry not at all meaning any ill disrespect

exotic karma
#

webhook stuff

webhook.listener(async (vote) => {
      console.log("TEST VOTE");
      
      console.log(vote.user);
      if (!vote.user) {
          res.status(400);
         return;
      }
      // upsert user data for vote
   })
#

http stuff

app.post('/dblwebhook', (req, res) => {
  console.log("Received webhook");
  res.sendStatus(200);
});```
exotic karma
fluid jetty
#

that's what you're supposed to do, yes. webhook is a part of the @top-gg/sdk package.

exotic karma
#

oh, it's middleware

#

are you doing this and using the right token? no Bot prefix

const webhook = new Topgg.Webhook("topggauth123"); // add your Top.gg webhook authorization (not bot token)
fluid jetty
#

yes

#

yup

#

i've integrated it completely and included error handling too so inparticular I'm really positive it's not an issue with my code. tried everything

exotic karma
#

do you have other middleware that could be interferring?

#

middleware is messy

#

Middleware order: Express executes middleware in the order they are declared. If you have middleware that modifies the request body or interrupts the request flow before it reaches the webhook listener, it could interfere with its functionality.
Body parsing: The Top.gg webhook listener expects to receive the raw request body. If you're using body-parsing middleware (like express.json() or express.urlencoded()), it could consume the request body before the webhook listener can access it.
Error handling middleware: If you have error-handling middleware that catches all errors, it might prevent the webhook listener from sending its own error responses.
Response-sending middleware: Any middleware that sends a response (res.send(), res.json(), etc.) before the webhook listener will prevent it from functioning correctly.

fluid jetty
#

i isolated it seperately from the middleware and was still having that issue, stopped using helmet and it still wasn't working. i'll keep messing around and see if i figure something out, thank you

exotic karma
fluid jetty
#

topggSob tried all those things man, just gonna keep experimenting, we'll see

fluid jetty
#

thank you, I appreciate the help and tips 😄

bronze vault
#

troubleshooting some memory leaks atm, any possibility this comes from topgg?

fluid jetty
#

@exotic karma Thanks for the help man. Just moved some things around in both environments and I found the issue lied in a very well hidden middleware that does infact modify the req body. 😭 amateur hour! I apologize for wasting your time if I did. Thank you again, just wanted to inform you it was fixed by your good advice :)

warped pier
#

hey, I was trying to use a topgg.DBLClient class but it gave me this error

Traceback (most recent call last):
  File "c:\Users\xxxxxx\Desktop\dumpling gambler\main.py", line 26, in <module>
  File "C:\Users\xxxxxx\AppData\Local\Programs\Python\Python310\lib\site-packages\topgg\client.py", line 98, in __init__
    self.http = HTTPClient(token, loop=self.loop, session=kwargs.get("session"))
  File "C:\Users\xxxxxx\AppData\Local\Programs\Python\Python310\lib\site-packages\topgg\http.py", line 84, in __init__
    self.session = kwargs.get("session") or aiohttp.ClientSession(loop=self.loop)
  File "C:\Users\xxxxxx\AppData\Local\Programs\Python\Python310\lib\site-packages\aiohttp\client.py", line 252, in __init__
    loop = get_running_loop(loop)
  File "C:\Users\xxxxxx\AppData\Local\Programs\Python\Python310\lib\site-packages\aiohttp\helpers.py", line 293, in get_running_loop
  File "C:\Users\xxxxxx\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 145, 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

this is the code

bot.top = topgg.DBLClient(bot, TOPGG_TOKEN)

what might be the problem here? do I need to await or call someting? or is python 3.10 not allowed and I need to use 3.9? (on the sdk's repo the badge only shows versions up to 3.9)
i'm really confused. what I did seems to match with what is in the examples

jaunty plank
still cradle
#

can someone help me doing the api to track when someone votes and it sends a message in my server

#

wtf lol

icy aurora
#

@jaunty plank

icy aurora
still cradle
#

well duh

jaunty plank
#

speedy mods

icy aurora
#

Thanks woo

icy aurora
icy aurora
jaunty plank
#

I like being muted

icy aurora
#

whyyy tho

jaunty plank
#

I deserve it

#

bad mod angeryBOYE

icy aurora
#

how

#

nah dylan needs it

leaden root
#

I have no Idea what I do wrong

My code

    @tasks.loop(minutes=30)
    async def update_stats(self):
        # Send a request to top.gg to update the bot's stats
        url = f"https://top.gg/api/bots/{self.bot.user.id}/stats"
        data = {
            "server_count": len(self.bot.guilds)
        }
        
        headers = {
            "Authorization": os.getenv("TOPGG_TOKEN")
        }

        response = requests.post(url, data=data, headers=headers)

The Error
b'{"message":"You are not allowed to update this bot."}'
response.reason = 'Forbidden'

jaunty plank
steel crater
leaden root
icy aurora
abstract monolith
normal creek
#

im programming a my bot in c#. however i cant get my webhook working. i think the code is correct but i have problems with the port being inaccesible (i think). can someone help?

normal creek
#

additional information: when sending a POST via postman i get the error: Error: connect ECONNREFUSED

jaunty plank
normal creek
jaunty plank
#

Their plans are so cheap I doubt they're giving dedicated IP's. So you may need to request a port from plexnodes.

#

I'd copy paste it, but my mouse is double clicking so bad I cant open the faq answer notlikenoot

normal creek
#

i already asked twice, they dont respond....

jaunty plank
#

Yeah, that tends to happen with extremely budget hosts.

#

cheap, but unreliable and no support 😦

normal creek
#

yes sadly, i`ll try harder to contact them. thx for your respons!

jaunty plank
#

One thing you can try, the dashboard may mention a specific port they gave you.

#

you'll have to use that port

normal creek
jaunty plank
#

Your vps might have a firewall by default blocking it.

normal creek
#

yes might be. i formatted my question like this and shared it to them:

I’m having trouble setting up a webhook for my Discord bot to reward users for voting on top.gg. My bot is in C#.

Information i use:

Things i have already done:

  • Using my code (which seems correct). But i see nothing printed in console (made a console.writeline() for debugging.)
  • When I test the webhook via Postman, I get the error: Error: connect ECONNREFUSED myip:20354.
  • I checked the port using a tool like portchecker.co, and it says my port 20354 is closed.

Has anyone encountered a similar issue or can provide help on how to resolve this? Would really appreciate it.

unique cedar
#

Is there a way to fetch all bots from Top.gg via the API??ß i want to create a discord bot that shows a live ranking of the most popular bots on top.gg

#

i think i got ir

jaunty plank
#

@karmic glacier

unique cedar
#

But i will look at the API you gave me

jaunty plank
#

Yeah, you'll have to recreate what DBL statistics does. They use the top.gg api.

You'll hit the top.gg rate limit a ton, but it's doable.

unique cedar
#

Well i can do 60 requests per Minute that should be enough

jaunty plank
#

50,000 bots iirc, so it'll take awhile.

unique cedar
#

Uh right...

#

Idk is there paid api Access? For more requests

jaunty plank
#

I'm not sure how close you'll be able to get to the rate limit constantly before your token access gets revoked too.

unique cedar
#

Maybe this idea from me is dead too lol

jaunty plank
#

We haven't really considered it, but you could ask a cm.

unique cedar
#

Oke

#

Thanks!

jaunty plank
#

If you understand webhooks and websockets I really want someone to make a top.gg webhook to websocket site.
Since so many people struggle with webhooks a websocket conversion would help a lot of developers.

#

Its a great project to work on

#

I have a couple revisions, so assuming you're using JS I can help point you in the right direction

unique cedar
#

@jaunty plank dayum... Your Website looks good

#

For Webhooks

jaunty plank
#

The rewrite of the frontend was fun 😄

#

Though I miss the old frontend, it was impossible to work on

unique cedar
#

Well...

#

I can't beat that lol

#

Anyways back to the work

#

Webhook to websocket

wild pebble
runic creek
#

@signal hawk

tidal idol
#

@subtle pulsar

bronze frigate
#
from discord.ext import commands
from aiohttp import web
import asyncio,json
import topgg
class TopGG(commands.Cog):
    def __init__(self, bot):
      self.bot = bot
      self.bot.topgg_webhook= topgg.WebhookManager(bot).dbl_webhook("/dblwebhook")
      self.bot.topgg_webhook.run(5000)
      self.bot.add_listener(self.on_dbl_vote)
    async def on_dbl_vote(self,data):
      print(data)
async def setup(bot):
    await bot.add_cog(TopGG(bot))

This is not working

restive otter
#

have you set the right url in your bot's settings on top.gg

bronze frigate
scenic escarp
#

Hello! Does someone knows why do I keep getting the TopGGAPIError: 502 Bad Gateway error? I have it around every 10 hours on my Discord bot who's currently on a VPS. I use the libraries @top-gg/sdk and topgg-autoposter

icy aurora
#

502 means it’s down

scenic escarp
scarlet cobalt
#

One message removed from a suspended account.

fluid raft
#

How often shall / can you update the stats?
(interval)

#

Because i keep getting the status code 502

jaunty plank
#

502 is when the API is down

#

Your best bet is to catch and ignore 502 errors

proven tundra
#

How do I see if someone voted for the bot?

jaunty plank
jaunty plank
proven tundra
dapper copper
ripe viper
#

how to make a webhook that tell who voted? where is the link

jaunty plank
ripe viper
#

no

ripe viper
jaunty plank
dapper copper
#

noice

jaunty plank
#

Yeah!

ripe viper
#

where is the link

#

the auto maker

ripe viper
ripe viper
#

yoo

#

mb i didn't see that

lunar timber
#

Hi - I’m looking for discord that will give me notifications to my phone when a specific user posts. Any help?

tidal idol
#

nvm they left

icy aurora
#

@signal hawk

ripe viper
#

@jaunty plank yo

#

why does your web adds a error embed

jaunty plank
#

Hey, it's 3am for me. If you send me a DM I can help you when I wake up

restive otter
#

yeah discord apparently isn't wrong

cc @untold sparrow

blissful flower
tidal idol
scarlet cobalt
#

One message removed from a suspended account.

#

One message removed from a suspended account.

restive otter
untold sparrow
#

-b 1187426294829428759 support scam

abstract mothBOT
#

upvote mitolso#0 was successfully banned.

untold sparrow
calm talon
#

Hi how do you make it so when someone votes on top.gg it says in a channel?

wild pebble
calm talon
wild pebble
tepid star
#

P

faint juniper
restive otter
faint juniper
#
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\

  // You can also throw an error to the listener callback in order to resend the webhook after a few seconds
}))

app.listen(80)
restive otter
#

Send that to them, not me

faint juniper
#

@calm talon

faint juniper
calm talon
jaunty plank
faint juniper
calm talon
jaunty plank
#

I'm not aware of any site having vote reminders right now. That's something you'll want to do from your end.

#

Using your own code and Database

calm talon
jaunty plank
#

That code will highly depend on your host, programming language, and your database.

#

This isnt a one solution fits all problem sadly

#

Reminders are not a fun thing to work on

jaunty plank
#

Never used it

calm talon
calm talon
jaunty plank
#

I've never worked with python and databases or web requests.

faint juniper
wild pebble
#

if you want to do more advanced stuff, i recommend using Python itself

calm talon
#

Yeah

wild pebble
wary oasis
#

Just create a http api server to which TopGG will post user votes. Store it in a database, and distribute the event across your bots to schedule the sent message. Then you can use the database entries for e.g. a top voters leaderboard page, or simply for granting rewards for votes.

south knot
#
import { ShardingManager } from 'discord.js';
import { AutoPoster } from 'topgg-autoposter';
import { env } from './env';
import type Logger from './structures/Logger';

export async function shardStart(logger: Logger) {
    const manager = new ShardingManager('./dist/LavaClient.js', {
        respawn: true,
        token: env.TOKEN,
        totalShards: 'auto',
        shardList: 'auto',
    });

    if (env.TOPGG) {
        AutoPoster(env.TOPGG, manager);
    } else {
        logger.warn('Top.gg token not found. Skipping auto poster.');
    }

    manager.on('shardCreate', async shard => {
        shard.on('ready', () => {
            logger.start(`[CLIENT] Shard ${shard.id} connected to Discord's Gateway.`);
        });
    });

    await manager.spawn();

    logger.start(`[CLIENT] ${manager.totalShards} shard(s) spawned.`);
}

Hello, I have a problem, I would like to send my total statistics of the shards with the package "topgg-autoposter" except that the dsa put only the statistics of a single shard and not of the total

lean cliff
#

I have a question, the webhook has the authentication option, how does it send this to my endpoint? in the headers?
If so, how is it shipped?

restive otter
#

Hello, I want to retrieve the total rating from the reviews (e.g., 4.2 stars) and display it on my website. Does Top.gg have an API for this?

spring lake
#

anyone know that the Top.gg Webhooks use TCP or UDP?

restive otter
spring lake
#

nvm already foundet

vital anvil
#

HTTP CatHeartEyes

#

so it depends on which version of http u use

spring lake
#

i have get it but thanks i havent read the docs correctly

zealous salmon
#

Help me lexar pls

restive otter
#

@untold sparrow wants

ebon spoke
#

what is the top.gg api used for?