#topgg-api
1 messages · Page 152 of 1
ok
there's no Request body thing
You sure?
yes
send a sceenstho
where it should be located?
Scroll down
Click into it
Request content then sorry
Idk, do you have the pop up
wot pop up?
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
Wrong link
i don't have the red lines
;/
wait
i do have
OH YES
i have da pop up
wot i do?
Nice, click them to put them in
ok
Remember to click ok to save
Okey
its loading forever

not what you were supposed to do
Go back to the HTTP module
And reinsert the variables now, they'll be corrupted
I've got to go now
Why am I getting this error when using top.gg's voting module?
app.post('/dblwebhook', webhok.listener(vote => {
^
TypeError: webhok.listener is not a function
?
pls help
webhok?
I wrote a webhok for a definition called webhook :D
how can i solve this problem?
nobody helps :(
very likely misspelled webhook
yes
same error
send the error
app.post('/dblwebhook', webhook.listener(vote => {
^
TypeError: webhook.listener is not a function
I'm updating the module
ok the problem is gone but when i press the webhook part of top.gg it doesn't write to the console
make sure the url is correct
//myserverip:5000/dblwebhook
not working
what port i changed and it worked :D
thanks man
How can I create a vote webhook?
So I am pretty sure I use the right api token, but when I try to update the server number, I get:
Failed to post server count
Unauthorized: Unauthorized (status code: 401)
I use the same code that is on the Python page btw.
probably dumb, but is top gg token the big ass string it gives you, not your bots id right
this token
on the webhook page
correct
kk
also would just like to say thanks to all the helpfull issues reported on the java api wrapper for topgg https://cdn.discordapp.com/attachments/822545886058905640/837809052930146364/Screen_Shot_2021-04-30_at_4.53.25_PM.png
I mean
still am thinking about asking veld to maintain it
literally hasn't been maintained since 2019

I'd volunteer
when veld crashes topgg entirely 😳
then again whoever made this wrapper is an idiot https://cdn.discordapp.com/attachments/822545886058905640/837808452113006642/Screen_Shot_2021-04-30_at_4.51.00_PM.png
thats on the freaking readme
thats intended use
Still don't understand the source code of it
Nah I've seen the source code
yet it's so outdated, can't even understand it with my smol brain
Ik, I might make a pull request its really fucking annoying
I still use Java 8 baybee
Only have Java 11 for intellicode
hello, can anyone help me? im trying to create a top.gg webhook using discord.js and heroku but im stuck with this problem
2021-05-01T01:04:42.536430+00:00 heroku[router]: at=info method=POST path="/dblwebhook" host=[app_name].herokuapp.com request_id=1103d16e-586f-4597-b3df-185e5bc9fd53 fwd="159.203.105.187" dyno=web.1 connect=0ms service=4ms status=403 bytes=238 protocol=https
this is my code
const express = require('express');
const Topgg = require('@top-gg/sdk');
const app = express();
const webhook = new Topgg.Webhook(process.env.TOPGG);
app.post('/dblwebhook', webhook.listener((vote) => {
console.log(`Vote from: ${vote.user}`);
}));
const port = process.env.PORT || 8080;
app.listen(port);
Enable your web dyno afaik
ok, but i have them enabled 
I'm having a rate limiting issue on the top.gg API, every 30 minutes my bots will update their online stats to show on the "Overview" section of my bot's page. But recently my bot has spat out a bunch of errors and it says things like "No json provided" etc etc, someone told me to post this here, so does anyone maybe know why this happening, perhaps i should raise the duration of when it post stats? much appreciated
30 minutes difference is fine I guess, so idk why are you rate limited. Try raising it to 1 hour
maybe mistake in ur code
top.gg resends webhooks until you give respond with a 200 response.
or until 10(or so) failed attempts
oh
Try pip install discord or pip3 install discord
So I Have To Set Res.200
Oko
🙂
const express = require('express'), {post, get} = require('superagent'), app = express();
const fetch = require('node-fetch');
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.get('/', (req, res) => {
res.send(`Response`)
})
app.post('/dblwebhook', async (req, res) => {
let auth = req.headers['authorization'];
if(!auth) return res.json({status: "Failed", message: `You didn't provide a 'Authorization' header!`});
if(auth !== process.env.Auth) return res.json({status: "Failed", message: `You didn't provide the correct authorization key!`});
if(!req.body) return res.json({status: "Failed", message: `You didn't provide any data!`});
if(!process.env.dbl) {
console.log(`You didn't add your dbl api key in the .env file.. smh`)
return res.status(401).json({status: false, message: `Unauthorized`})
}
let bot = req.body.bot;
let {body: user} = await get(`https://top.gg/api/users/${req.body.user}`).set("Authorization", process.env.dbl);
post(process.env.Webhook)
.send({embeds: [{
title: `Click Here To Vote Ratio™`,
color: 0xbc00ff,
url: `https://top.gg/bot/${bot}/vote`,
timestamp: new Date(),
author: {
name: `Ratio™ Voted By: ${user.username}#${user.discriminator}`,
icon_url: `https://cdn.discordapp.com/avatars/${user.id}/${user.avatar}${user.avatar.toString().startsWith("a_") ? ".gif" : ".png"}`
},
footer: {
text: `Powered By Discord Bot List`,
icon_url: `https://i.imgur.com/78Hl85r.gif`
}
}]})
});
app.listen(4000, () => console.log(`DBL Voting Log Is Running`));
Why Its Not Working

app.set('view engine', 'ejs');
app.get("/dblwebhook", (req,res) => {
res.render("Voting");
});
@lean harbor
Ok
why not just use @top-gg/sdk
Its Done
So i voted my bot and then made a request to check if i voted. But it always returns 0. I tried on my alt and got the same result. Do we need to wait some time or?
Nvm, found a different solution.
How can I define my library?
@restive otter stop that
ok
@restive otter ?
Anyone know how to use the DBL webhook in JS to listen for when someone "unvotes" (listener for when someone's vote is ready) ?
get their vote, start a timer for 12 hours, after 12 hours, tell that user they can re-vote
if you want a more command-based check, simply use hasVoted through the API to check if they have voted in the last 12 hours
but if you want a notification-based "your vote is ready", you need the timer approach
ahhh ok thank you
How long does it take for server stats to update after sending the POST request?
@restive otter I think we're exposing the wrong object here https://github.com/top-gg/python-sdk/blob/master/topgg/webhook.py#L123-L135
A simple API wrapper for top.gg written in Python. Contribute to top-gg/python-sdk development by creating an account on GitHub.
since it's basically a pain in the ass to customize routes this way imo 
Should probs expose self.__app instead
xd, thing is, everything in Python is public 
Ya well
What was the idea behind exposing it btw?
As the PR#45 or something says
sec
This is useful to customise routes and request handling.
Ah, so that you can add routes and middlewares eh
Pretty much
yeah ig, it should've been app
inb4 dbl_webhook('/dbl', 'eee').webhook.router.add_post('/dbl', some_func)
At that point I'm sure the dev knows what they're doing
... or at the very least have a slight idea of what they are doing
And, let's be fair
That just gives me more reason to blame them if they break something
But um, I think you can access the app through the TCPSite anyway
<WebhookManager>.webserver._runner.app is <WebhookManager>._WebhookManager__app returns True
So ig, by exposing the webserver, it also exposes AppRunner and the Application. But they're public in the first place anyway 
Wait am I that dumb
Omg
You legitimately just lowered my self-esteem so bad
Oh well what's done is done
I spent like 20 minutes on trying to get that attr via the source code
the _WebhookManager__app attr?
lmao
const Topgg = require('@top-gg/sdk');
const api = new Topgg.Api('"you really thought you were going to see the token')
const app = express();
const webhook = new Topgg.Webhook("you really thought you were going to see the password");
setInterval(() => {
api.postStats({
serverCount: client.guilds.cache.size
})
}, 1800000)
app.post('/dblwebhook', webhook.listener((vote) => {
console.log(`Vote from: ${vote.user}`)
client.channels.cache.get('833702889062662170').send(`${vote.user} just voted **Mitsu**!`)
}));
app.listen(3031);```
I got a error saying "Cannot get /"
Oh wait
you're trying to access that webserver without a context
can very likely just be ignored
Uhhh
well path
not context, wrong wording
you're trying to access http://yourip:port/ instead of http://yourip:port/dblwebhook
I read the docs of top-gg/sdk and they said to use /dblwebhook...
How can I add /dblwebhook to http://ip:port/
No no, what you're doing is correct
you tried to access your webserver without a path, that's what the error is
just ignore it
your webhook url is http://ip:port/dblwebhook
replacing ip:port with your ip and port
@sullen nymph shall I remove test_import.py?
Up to you tbf. We could also keep it in one file but that seems cleaner
The import test is just that, a test that imports the module, so you could leave it in case it's needed at whatever point
Yeah but another tests import it as well xd
Ok, Imma leave it as it is, you can always delete it 
I'll leave it for tomorrow since it's 4 am and inner me just wants to have a peaceful night
Thanks btw
Seems like we got 1 hour diff
Resolve conflicts button time
Ya np, I also made some minor changes
Will take a look, thanks
okie
hm?
How to I find cwl clans info , I dont know how to use it
-wrongserver
Hey! We think you have our server mistaken. We do not provide support, help, or advice for any bot. You need to click on the "Get Support" button on the bot's page of the bot you need support for, not the "Join Discord" button at the top of our website. If there isn't a button that says Support Server or you were banned from the bot's support server, then we can't help you. Sorry :(
How to create a vote webhook
I am trying to update the number of servers my bot is in but I consistently get a :
Unauthorized: Unauthorized (status code: 401)
I use the python code provided in the top.gg documentation and I have copy-pasted the token I generated for my bot. Does anyone know how to resolve this?
Yes
Isn't it the one I need?
Even forcing the token to be a string doesn't do anything
Ok so I fixed it:
- When you copy-paste the token from the site to the .env in replit, it adds a newline at the start and the end of the token. They need to be removed.
- When getting the token (with
os.genv('token')), it needs to be explicated that the type of the token isstr.
is there an http request to see total votes for the year (for a bot)?
or something like that
you may only see the last 1000 votes
the only way to do that currently is find a way to make the bot track votes for each day and then cumulatively add them all up for the end of the year
i don't want the votes, i want the total number of votes
the only information i need is the total votes per month at the end of each month
i don't need any info about the votes
so write a function that determines the end of whatever month it currently is and at the last minute count all the votes
does top.gg not keep track?
the problem is that i'm using http requests
not the library
okay
a webhook receiver is just an http server, with an endpoint configured in a specific way.
those specifics are listed here.
https://docs.top.gg/resources/webhooks/
or if you want to use a library, on the left hand menu it lists a few, some have webhook support.
ive tried whats listed on the documentation but the test button still doesnt do anything for me. Is something wrong with my code?
client.dblpy = dbl.DBLClient(client, dbl_token, webhook_path='https://MY_IP:6593/dblwebhook', webhook_auth='password', webhook_port=6593)
@client.event
async def on_dbl_vote(data):
print(f"Received an upvote:\n{data}")
@client.event
async def on_dbl_test(data):
print(f"Received a test upvote:\n{data}")
The webhook path should only be /dblwebhook
Also, topggpy is up
it introduces a separate webhook manager
Oh I didn’t know that
I’ll try it
It still isn’t working. Is there something I need to do elsewhere for this to function?
Did you pass https://MY_IP:6593/dblwebhook to the site? Ig just use http scheme for this. Also, you passed /dblwebhook to the webhook_path parameter, didn't you? Make sure port 6593 is open
Yeah I’ve done all of this
And I checked if the port was open and it is
Does the password thing need to have something? Or is the “password” fine? I couldn’t find anything in the documentation that mentioned that.
It's fully up to you, so that's fine.
Do you have any other ideas to why it may not be working?
Did you migrate to v1?
I believe so
Can you show the code?
Can someone help me, I get a "Cannot get /" error
client.dblpy = dbl.DBLClient(client, dbl_token, webhook_path='/dblwebhook', webhook_auth='password', webhook_port=6593)
@client.event
async def on_dbl_vote(data):
print(f"Received an upvote:\n{data}")
@client.event
async def on_dbl_test(data):
print(f"Received a test upvote:\n{data}")```
Uh, you didn't migrate then
Oh there is diff code?
The topggpy thing has this code so im not really sure what the migration is
Does anyone know why I get this error ? ClientException: autopost must be activated if autopost_interval is passed. Unclosed client session
Yeah, shiv hasn't update it ig
So I should just wait for them to update it and try again?
so my code is right, but the update isn't out yet on their servers ?
Yeah, this issue is fixed in my PR. If you want to autopost, then explicitly pass True to autopost parameter. Otherwise, pass 0 to autopost_interval
I'm updating it, dunno when it'll be merged
where do I must to put this ?
when instantiating DBLClient
like this ? topgg.DBLClient(self.client, self.token, autopost = True) ?
const Topgg = require('@top-gg/sdk');
const api = new Topgg.Api('"you really thought you were going to see the token')
const app = express();
const webhook = new Topgg.Webhook("you really thought you were going to see the password");
setInterval(() => {
api.postStats({
serverCount: client.guilds.cache.size
})
}, 1800000)
app.post('/dblwebhook', webhook.listener((vote) => {
console.log(`Vote from: ${vote.user}`)
client.channels.cache.get('833702889062662170').send(`${vote.user} just voted **Mitsu**!`)
}));
app.listen(3031);```
Can someone help, I get a "Cannot get /" error
I don't know why is it happening
@client.event
async def on_dbl_vote(data):
print(data)```
Sorry im still confused but is this the v1 version of how the on vote needs to be done?
got the error back... ```
Failed to post server count
Unauthorized: Unauthorized (status code: 401)
Ignoring exception in auto post loop:
Traceback (most recent call last):
File "C:\Users\fouk\AppData\Local\Programs\Python\Python37\lib\site-packages\topgg\client.py", line 131, in _auto_post
await self.post_guild_count(shard_count=self.bot.shard_count if self.post_shard_count else None)
File "C:\Users\fouk\AppData\Local\Programs\Python\Python37\lib\site-packages\topgg\client.py", line 186, in post_guild_count
await self.http.post_guild_count(guild_count, shard_count, shard_id)
File "C:\Users\fouk\AppData\Local\Programs\Python\Python37\lib\site-packages\topgg\http.py", line 166, in post_guild_count
await self.request('POST', '/bots/stats', json=payload)
File "C:\Users\fouk\AppData\Local\Programs\Python\Python37\lib\site-packages\topgg\http.py", line 142, in request
raise errors.Unauthorized(resp, data)
topgg.errors.Unauthorized: Unauthorized (status code: 401)
same lol
:(
@restive otter I broke something again, didn't I?
I'll get to laptop in about few hours
Sure
What do you think? This makes the run method can be awaited, but not necessary
Sounds convenient 👀
This isn't on us, the old version doesn't break the loop on 401. Meanwhile, the new version breaks the loop so that you know that the token was invalid
okay I solved this problem. But now, I got this error HTTPException: Bad Request (status code: 400)
Here is my code : ```py
class TopGG(commands.Cog):
"""Handles interactions with the top.gg API"""
@commands.Cog.listener()
async def on_ready(self):
print("TopGG Server cog ready !")
def __init__(self, client):
self.client = client
self.token = 'MY TOKEN'
self.client.topggpy = topgg.DBLClient(self.client, self.token, autopost = True)
self.update_stats.start()
@tasks.loop(minutes=30)
async def update_stats(self):
"""This function runs every 30 minutes to automatically update your server count."""
try:
await self.client.topggpy.post_guild_count(guild_count = len(self.client.guilds), shard_count = self.client.shard_count)
except Exception as e:
print('Failed to post server count\n{}: {}'.format(type(e).__name__, e))
def setup(client):
global logger
logger = logging.getLogger('bot')
client.add_cog(TopGG(client))
Ugh, you already got autopost enabled, you don't need to do another post loop
Does anyone here can help with @top-gg/sdk
Pro tip: you can pass True to the post_shard_count parameter
okay thanks

yes
just ask your question
So basically
I've getting an "Cannot get /" error
const Topgg = require('@top-gg/sdk');
const api = new Topgg.Api('"you really thought you were going to see the token')
const app = express();
const webhook = new Topgg.Webhook("you really thought you were going to see the password");
setInterval(() => {
api.postStats({
serverCount: client.guilds.cache.size
})
}, 1800000)
app.post('/dblwebhook', webhook.listener((vote) => {
console.log(`Vote from: ${vote.user}`)
client.channels.cache.get('833702889062662170').send(`${vote.user} just voted **Mitsu**!`)
}));
app.listen(3031);```
thats fine
Is it something to ignore
yup
where do you host your bot
Repl rn
btw vote.user wont work
you need to fetch the user with their id
Hey
Can I know if a user has voted for a server without access to API just by a get request?
or any other way to know if a user has voted for a server
Sorry for ping but how do I fetch it
in the docs it's stated vote.user for user id
you just can do <@${vote.user}> if you want
Oh
And if I use https://replname.username.repl.co/dblwebhook than what's the use of port and ip
ok
hello, for using on_dbl_vote in the python sdk, do I need to run a quart server or something and manually process the POST or is there some utility for that in dblpy?
It's now topggpy, and yes, there's a helper class for this
@restive otter Bro my single quote strings :( this is discrimination

Could you guys make a system to detect if users left a review and how many stars they added? It would be useful for many things!
People would use that to reward people for leaving a review, which is against our rules.
Hey, I'm currenlty reading the documentation for the python sdk, where can I get my top.gg token?
read pins
thx
Well, now I'm getting the error TypeError: object Lock can't be used in 'await' expression
What do I need to do here?
Did you install dblpy? Install topggpy instead
Do I need to change the imports/code then?
can you show me the code for it?
A simple API wrapper for top.gg written in Python. Contribute to norinorin/python-sdk development by creating an account on GitHub.
This is dblpy not topggpy
It is topggpy
topggpy == dblpy v1
Shivaco hasn't updated the examples; therefore, take a look at it instead
client.topgg = topgg.DBLClient(client, DBL_TOKEN, autopost=True, autopost_interval=900)
Is that enough code to post all my stats, or do I need more code?
That's enough, if you want to post shard count as well, you can pass True to post_shard_count parameter
tysm
I was looking into the readme, sorry
all good
I mean 

I only use php because it's in my school syllabus 
i can feel the pain in that
Look, it was 2 am when I wanted to update them

lmao
Wh
Is there a way to put your bot in testmode
Like test the /bot features
And that good stuff
-api
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.
ask in #development
This is for the api
Yeah
Why would you need your bot in some test mode for that?
then no there's not
Oh
So you don't have to wait for it to be like accepted
Alr
@restive otter What do you think about renaming post_shard_count to something like autopost_shard_count?
And autopost to something like autopost_toggle?
Umm, I'm personally fine with it as it is now. What about making a class, do you think it's redundant to make an AutoPostConfig class?
Eh probably at some point if it's needed
It might implement __getitem__ method, so one could pass a dict as well
It's fine the way it is now and I haven't seen anyone even suggest a class for it so
This one is reasonable
The autopost_toggle is kinda idk, I'd prefer the former
It's pretty identical, but nothing is wrong by testing it ig. I'll add it soon
Shall I add the dsl one?
Full coverage, I guess
In case I happen to somehow break the authentication process
Alright, done ig
sa
-api
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.
How is guild inflation dealt with?
guild inflation?
Like when you post to the webhook
Like, you add 30 to the actual count
30 + (actual) = 92
then when a user reports it we check it against the actual count.
How can you do that tho?
invite links give server count
it always does, it just gets less accurate when you get into the millions, which as long as its mostly correct it doesnt matter at that point.
How can I alert when someone upvotes my bot?
Webhook
How can I get my bot to talk?
Fr? What library are you using?
Hello, I needed your help to make the webhook system, because "Authorization" I don't know what to do, can someone help?
when you receive a web hook, there's a section in the header called "Authorization" compare it to ensure someone isn't spoofing your web hook
TypeError [ERR_INVALID_CHAR]: Invalid character in header content ["authorization"]
how i can fix it ?
you probably have a newline in your token
check for invalid characters in your header then
should be "Authorization" not "authorization" right?
nah that doesn't make a difference
How can I make vote Tracker?
by coding one: https://docs.top.gg
I like it but I don't understand anything 🙂
what are the pros and cons btwn using on _dbl_vote() and a webhook?
it is a webhook, just in a premade library.
If you use on_dbl_vote() do you have to provide a webhook url?
on_dbl_vote is useless without a webhook
Hey I was wondering if Shivaco has fixed the errors that were on the topggpy library
@gray yew Like
what errors?
They mentioned that they broke something and that they would get on their laptop in a few hours and that was like a while ago
This is intended #topgg-api message
This is fixed in my patch #topgg-api message
I dont follow
anyone know how to do that like someone votes my bot and my bot msg that guy in dm sayin ty :/
ty
@restive otter you are just bullying me with your experience and knowledge, admit it 😛
Why the install itself workflow tho? Not sure why that's used in this case but regardless merged the PR
Cuz pytest ig, it refers to topgg module, so if it wasn't installed, it can't run the tests
No, lmao. You're more experienced than me. I'm only almost a year with python 
But hm pytest runs in the parent directory, haven't tried relative import though. Well this install itself can also validate in case I happen to break the setup.py 

@sullen nymph forgot to int these lmao https://github.com/top-gg/python-sdk/blob/master/topgg/__init__.py#L19
A simple API wrapper for top.gg written in Python. Contribute to top-gg/python-sdk development by creating an account on GitHub.
Tsk tsk
I was already about to open PyCharm so this will take like a few minutes
inb4 custom func split_auto_type LMFAO
inb4 [int(i) for i in __version__.split(".")] 
Just make it tuple ezpz
How to check if a user has voted for a server without my bot having access to dbl client
Can you elaborate on your question? What library do you use?
Python
How do you not have access to your DBLClient object is my question
I want to check if a user has voted for a server just by making a get request
Oh boy, a server
There's no endpoint for server, is there?
DSL doesn't have an API
The only way you can achieve this is with webhooks
Setup a webhook and store it in your own database
aka receive votes in real time and- yeah what norizon said
I'm not exactly sure why DSL doesn't have an API tbf
major, minor, micro are exposed in module imports, aren't they?
Hm, probably
Or actually, I think if it has a trailing underscore, it wouldn't get exposed
NVM, I think it'd only work for wildcard imports lmao
Guess there's only one way to find out? 😛
I have some code for checking for server votes
I mean, there's the option of literally just doing what I did before
Form __version__ from the version_info namedtuple
Was fixing this https://github.com/top-gg/python-sdk/runs/2488584015?check_suite_focus=true#step:5:9
the __version__ value is only known at runtime, so I reversed it xd
Something like ".".join((version_info.major, version_info.minor, version_info.micro)) 😛
Oh
I could've suppressed the imports error, but dunno if that's an elegant way to do it
Probably not
inb4
VersionInfo = namedtuple("VersionInfo", "major minor micro releaselevel serial")
major, minor, micro = __version__.split(".")
version_info = VersionInfo(
major=major, minor=minor, micro=micro, releaselevel="final", serial=0
)
del major, minor, micro
``` 🤣
What about this 
Oh my lord
Overcomplicating shit 
😂
Well, let's leave it for another day
I doubt someone will use any of those vars along with from topgg import *
I doubt you ever want to do a star import with topggpy soooooooooooooooooooooooooooooooooooooooo 
xd, I'll leave casting the number as int to you 
Aye, we'll be ready to go in a few seconds
noice
Yeah, "a few" 
dw, I'm myself a procrastinator 
btw it's not a tuple, it's a generator
ig del major, minor, micro is more readable than my shit
HAHAHAHAHAHAHAHAHAHAHAHA
joy
LMAO, true
uh oh
Does ```py
opts = _WidgetOptions(
format=options.get("format") or "png",
type=options.get("type") or "",
noavatar=options.get("noavatar") or False,
colors=options.get("colors") or options.get("colours") or {}
)
Yes 😂
weird, I never used pycharm xd
Sure, I've been thinking of that. Working with raw data isn't newbie-friendly ig. And, also it'd be good if the intellisense tells you what fields it has.

Rename or abuse Python?
def __init__(self, bot_id: int = None, widget_format: str = "png", widget_type: str = ""):
super().__init__()
self.id = bot_id
self.format = widget_format
self.widget_type = widget_type
``` 👀
Ig it's fine as they're just attributes. You aren't shadowing the built-in functions
Does it still complain if it was a property instead?
ah nevermind lmao
It was pointing to the parameter 
ya
Hell yeah ab
se it 
Time to just silence warnings about shadowing built-in names
Now, I'm wondering if I should add both colours and colors as parameters and then check if either was specified with colors taking priority
Scrap colours because colors is superior
What about ```py
def init(self, **kw):
self.colors = kw.get('colors', kw.get('colours', {}))
@property
def colours(self): return self.colors
Intellisense is lost that way, isn't it?
Though I mean, it's literally a dictionary... 
also shivaco and norizon, with topggpy 1.0.1
bot.topgg = topgg.DBLClient(bot, DBL_TOKEN)
returns autopost must be activated if autopost_interval is passed
That's fixed in the master branch
For now, if you want to autopost, then explicitly pass True to autopost parameter. Otherwise, pass 0 to autopost_interval
That's what I do, just letting you know
Yeah, we're aware and it's fixed, thanks though
yeah I just pip installed topggpy, not git+https://github.com/top-gg/python-sdk/
so ig it still has some bugs
Oh it's not on pypi is it
nope
New version will be released like today-tomorrow very likely
nice ty
I wrote the examples by hand, you'd better check it, shiv 
LMFAO will do once I'm back on my laptop
Didn't touch the manual posting though, as it's pretty much identical ig
Will change them once I'm done with the WidgetOptions class
pep8 on those x: hint = x 
space separated = when in conjunction with type hints
all good, it's just the intellisense does that
😌
😂
@restive otter https://docs.python.org/3/library/asyncio-task.html#asyncio.create_task
This function has been added in Python 3.7.
Backwards compatibility 👀
loop.create_task exists in earlier versions though
I'm not sure but it's at least supported since 3.5
Yeah, no worries then
@restive otter Is there any better way of doing widgetoptions test you can think of?
You can add something like this ig https://github.com/top-gg/python-sdk/blob/master/tests/test_client.py#L32-L80
A simple API wrapper for top.gg written in Python. Contribute to top-gg/python-sdk development by creating an account on GitHub.
How is WidgetOptions written?
const Topgg = require("@top-gg/sdk")
const express = require("express")
const app = express()
const webhook = new Topgg.Webhook("xxxxx")
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, function () {
console.log("Server is running on localhost80");
});```
From where can i get Topgg.Webhook?
First of all, you can't use port 80 for webhooks
And you set the webhook auth yourself on your bot's webhook page
guys how can i make a webhook i wanna make a vote rewards for my bot i use (python)
🙂 pls help me
You might want to do bot.loop.create_task(bot.topgg_webhook.run(5000)) instead of bot.topgg_webhook.run(5000)
class WidgetOptions(dict):
id: Optional[int]
format: str
type: str
noavatar: bool
colors: _Colors
def __init__(
self,
id: int = None,
format: str = None,
type: str = None,
noavatar: bool = False,
**kwargs,
):
self.id = id
self.format = format or "png"
self.type = type or ""
self.noavatar = noavatar
self.colors = kwargs.get("colors", kwargs.get("colours", {}))
super().__init__(id=id, format=format, type=type, noavatar=noavatar, colors=self.colors)
def __getitem__(self, item):
return getattr(self, item)
def __setitem__(self, key, value):
setattr(self, key, value)
@property
def colours(self):
return self.colors
@colours.setter
def colours(self, value):
self.colors = value
Could've just sent the edited client.py rn instead of copy pasting that
Is it necessary to implement __getitem__ and __setitem__? Doesn't the dict implement it already?
Also, take a look at this, it'd have different values
What about this ```py
class WidgetOptions:
id: Optional[int]
format: str
type: str
noavatar: bool
colors: _Colors
def __init__(
self,
id: int = None,
format: str = None,
type: str = None,
noavatar: bool = False,
**kwargs,
):
self.id = id
self.format = format or "png"
self.type = type or ""
self.noavatar = noavatar
self.colors = kwargs.get("colors", kwargs.get("colours", {}))
def __getitem__(self, item):
return getattr(self, item)
def __setitem__(self, key, value):
setattr(self, key, value)
def items(self):
return self.__dict__.items()
def values(self):
return self.__dict__.values()
def keys(self):
return self.__dict__.keys()
@property
def colours(self):
return self.colors
@colours.setter
def colours(self, value):
self.colors = value
Why reimplement those? 
yeah, but the values are only set when instantiating the object, it'd still have different values if you set the colours, for instance, manually
It doesn't subclass dict
There's the option of handling None in the generate_widget method
Is there any benefit in implementing those methods manually instead of just subclassing dict?
Just curious
This
OH
It doubles the data, and once you edit some attributes, the dict values won't get updated
If you want to subclass dict, you can instead implement a __getattr__ method
It'd get invoked if the attribute doesn't exist, so it can instead subscript itself with the attr name
if the attribute doesn't exist
Hm
dicts don't have id, format, etc. so that'll work just fine ig
getattribute is invoked before looking at the actual attributes on the object, and so can be tricky to implement correctly. You can end up in infinite recursions very easily.
👀
Yeah, that's why it should implement __getattr__ instead
Why not use __getattribute__ with getattr?
Something like this ```py
class WidgetOptions(dict):
def init(
self,
id: Optional[int] = None,
format: str = None,
type: str = None,
noavatar: bool = False,
**kwargs,
):
super().init(id=id, format=format or "png", type=type or "", noavatar=noavatar, colors=kwargs.get("colors", kwargs.get("colours", {})))
def __setattr__(self, key, value):
self[key] = value
def __getattr__(self, key):
return self[key]
@property
def colours(self):
return self.colors
@colours.setter
def colours(self, value):
self.colors = value
Not sure if this way the intellisense would work properly though
It probably wouldn't
Also, what's awkward is, it'd raise KeyError if you accessed non-existing attributes 
The intellisense would work on this one I suppose #topgg-api message
I'm thinking of something, sec
def __init__(
self,
id: Optional[int] = None,
format: str = None,
type: str = None,
noavatar: bool = False,
**kwargs,
):
self.id = id
self.format = format or "png"
self.type = type or ""
self.noavatar = noavatar
self.colors = kwargs.get("colors", kwargs.get("colours", {}))
super().__init__(id=self.id, format=self.format, type=self.type, noavatar=self.noavatar, colors=self.colors)
def __getitem__(self, item):
return getattr(self, item)
def __setitem__(self, key, value):
setattr(self, key, value)
def __setattr__(self, key, value):
self.__dict__[key] = value
setattr(self, key, value)
@property
def colours(self):
return self.colors
@colours.setter
def colours(self, value):
self.colors = value
What do you think?
Oh, sec
def __setattr__(self, key, value):
if key == "colour":
key = "color"
self.__dict__[key] = value
setattr(self, key, value)
Plural, yeah
What's the superclass though?
self.__dict__[key] would set it as the dict's attribute instead of putting it as key
Oh, interesting
How come? 
RecursionError: maximum recursion depth exceeded
What do you know 
You implemented a __setattr__ just to call it again
Yup
Give me like 30 minutes
You got the gist why this doesn't need to subclass dict #topgg-api message
okie, take your time
Ohhh
Now I get what you mean
Good fucking lord I feel so dumb 
@restive otter
class WidgetOptions(object):
id: Optional[int]
format: str
type: str
noavatar: bool
colors: _Colors
def __init__(
self,
id: Optional[int] = None,
format: str = None,
type: str = None,
noavatar: bool = False,
**kwargs,
):
self.id = id
self.format = format or "png"
self.type = type or ""
self.noavatar = noavatar
self.colors = kwargs.get("colors", kwargs.get("colours", {}))
# super().__init__(id=self.id, format=self.format, type=self.type, noavatar=self.noavatar, colors=self.colors)
def __getitem__(self, item):
return getattr(self, item)
def __setitem__(self, key, value):
setattr(self, key, value)
def items(self):
return self.__dict__.items()
def values(self):
return self.__dict__.values()
def keys(self):
return self.__dict__.keys()
def __setattr__(self, key, value):
if key == "colours":
key = "colors"
super(__class__, self).__setattr__(key, value)
@property
def colours(self):
return self.colors
@colours.setter
def colours(self, value):
self.colors = value
So this should be good?
um, the __setattr__ is redundant imho
lmfao true
Because colours got a setter, so it'll work just fine.
Btw, you can make a Base Class that implements these methods
BaseWidget?
So that if you're planning to make classes for the data returned from the API, it can inherit it instead
At this point I should probably move it to a new file types.py imo
Uh, not only for Widget. Like it can have a from_dict class method, and then calls obj.__dict__.update(data)
Yeah
Hmm... I'm really unsure of what I can name it tbh
If not something like DBLDataDict or just DataDict
DataDict sounds better, I think
Yeah up to you xd
I'm bad with naming stuff lmao so DataDict is it
If you do obj["non_existing_key"], it'd raise AttributeError instead of KeyError, would it be better for __getitem__ to do self.__dict__[key] instead?
Yeah, might be a better idea lol
Actually, I'm curious about from_dict. Why not use __init__ to create it?
Oh yeah sure, the __init__ can take the dict from the API. I forgot that the users are not supposed to instantiate it.
Keep the channel on topic, please :)
Hm, ig the __init__ isn't necessary, is it? I'd let the subclass implement its own __init__. Cuz you wanna cast some objects to a different type. For instance, the date to a datetime object, the id to int
That DataDict class is inherited so that the subclasses become dict-like objects. That way it won't be a breaking change as the users can access it as if it was a dict.
More like you are trying to start an unnecessary argument
It's overridden when a subclass implements it, isn't it?
Yeah, even though it can still be called
How much of a good idea is this?
class DataDict:
def __init__(self, object_dict: dict, **kwargs):
self.__dict__ = object_dict
self.__dict__.update(kwargs)
😂
I'd parse the data first
Like convert camelCased keys to snake_cased ones. Cast snowflakes as int, the date string as datetime object
Hm
I'll implement a from_dict method instead of overriding init and do that in the func instead
Changing the typehints is gonna be fun
Why? Are you gonna let the users instantiate it or something?
I think of this like most of discord.py's objects where they can only be instantiated with the raw data from the Discord API
That's pretty much what it's gonna be, but it will provide me convenient way to initiate it without having to worry about super().__init__
I'm curious how that'd end up, looking forward to it
This is gonna be a fun change
Oh my dear lord converting camel case to snake case is a headache
my quick approach xd
(?<!^)(?=[A-Z]) replaced with _ and then lowered is better ig
I prefer to avoid regex here
Oh well, ''.join(f'{"_"*(char.isupper() and idx != 0)}{char}' for idx, char in enumerate('isWeekend')).lower() 
exdee, this one worth to have a test
I'll try out the one I have rn and then test that
pytest.parametrize goes brr
Hm
I modified my poststats so that it only posts my server count, and in the logs it says error 400, what is the issue?
I'm using dblapi.js
nvm
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.
k ill follow that
it doesnt btw
it does
how's your bot going to interact with discord's api nonetheless
though yeah #development
ok come to #development
@elfin solstice, seems as if there are still API issues with the GET /bots API endpoint with 504 time outs every time we attempt to do anything with that endpoint. Is there a chance there are still problems occuring?
Attempted without search parameters and got the same response.
was this working before?
because I don't think it's been working for many many months
pain
with a search query it fails
oh
and for now we most likely won't fix that
So is there not a way to get all the bots for a certain user?
rip
it's called top.gg/user/12461027846124 
bots isnt a param on a GET request to a user
and v1 will start very soon (with limited functionality for now) since i'm working on it for an upcomming feature
You missed the implication of that
pog
ah yes, scraping 
we should probably stop the off-topic conversation in here and move memes to #general
Works with PHP when doing search query
x
how do u make it so that whenever someone votes the bot gets triggered? LIke i mean I know that top.gg sends a post request to some url, but can the url be like localhost? or...
yeah
It has to be IP address of the machine the webserver is hosted on
how to make a webhook idk how
so lets say I accidently hosted 2 instances of the bot, and they are different ips, what would happen then?
2 instances on the same machine means same IP
no but how bout different ips?
Top.gg doesn't support multiple URLs for a bot/server so you'd need a system to cover that
How to check if someone voted
https://comhad.github.io/webhook.html i made a guide
You'll see on the bot's page at top.gg. It shows the amount of votes the bot has gotten
By using webhooks. See the pines messages. They contain a link to the docs.
hmm
You can define a password on the topgg site but you don’t have to.
See the topggpy webhook instead
import topgg
# This example uses dblpy's autopost feature to post guild count to top.gg every 30 minutes.
dbl_token = 'token' # set this to your bot's top.gg token
bot.dblpy = topgg.DBLClient(bot, dbl_token, autopost=True)
@bot.event
async def on_dbl_vote(data):
"""An event that is called whenever someone votes for the bot on top.gg."""
print(f"Received an upvote:\n{data}")```
Is this the correct way ?
that'll autopost yeah, but the on_dbl_vote event won't fire as you need a topgg.WebhookManager object
hey i need help
with what exactly?
What was the response status code?
there is no print
Uh, is that flask?
not
If you have installed topggpy from the pypi, your webhook won't even run
You need to do bot.loop.create_task(bot.topgg_webhook.run(5000)) instead
but if i do that this errors
see
How is that not flask
yes
I can't really help with that, but if you accessed the / route and it shows 404, then the webhook might be running. Try accessing /dblwebhook and see if it shows something else
ok
It should show 405 if you GET request it iirc
ok
const webhook = new Topgg.Webhook(processe.env.VOTE_AUTH)
app.post(process.env.VOTE_PATH, webhook.listener(async (vote) => {
const user = vote.user // User ID of the user who voted
const guildId = vote.guild // The guild the user voted for
const type = vote.type
if(!guildId == config.guild)
{
return
}
console.log(`User ${user} has voted for ByteCode Studios`)
const guild = await client.guilds.cache.get(guildId)
const channel = await guild.channels.cache.get(process.env.VOTE_CHANNEL_ID.toString())```
will this work?
I have a question,the following is my code,but it doesn't give any error or response
@client.event
async def on_dbl_vote(data):
print(data)
what must i pay who much is it?
Did you set up your DBLClient correctly? With port, webhook path etc?
Uhh what
In the docs it said only this code..
You can refer to topggpy instead, it uses a separate WebhookManager class for this
So i never actually tried something with webhooks
how am i getting a URL for the webhook?
http://<your public ip>:<port>/<webhook path>
port and path can be whatever it wants to be? (ok obv the port needs to be open)
or what exactly is the webhook path? 
You specify the path and port in your code, yes
so like http://340.34.5.33.2:5555/votes e.g.
Yes
Ah i see thanks 
how do i do a system where it dont require a webhook using discord.js for vote messages
You can't listen for votes without a webhook
Hey guys, the on_dbl_vote event isn't working for some reason
I did everything right
mate
i did everything
made webhooks, clients etc
from discord.ext import commands
import os
import dbl
#CODE BY WOOZY NOBODY TOUCH
class TopGG(commands.Cog):
"""
This example uses dblpy's webhook system.
In order to run the webhook, at least webhook_port must be specified (number between 1024 and 49151).
"""
def __init__(self, bot):
self.bot = bot
try:
self.token = os.getenv("TOPGG_TOKEN") # set this to your DBL token
self.dblpy = dbl.DBLClient(self.bot, self.token, webhook_path='0.0.0.0', webhook_auth='password', webhook_port=8080)
except Exception as e:
print(e)
@commands.Cog.listener()
async def on_dbl_vote(self, data):
"""An event that is called whenever someone votes for the bot on top.gg."""
print("Received an upvote:", "\n", data, sep="")
@commands.Cog.listener()
async def on_dbl_test(self, data):
"""An event that is called whenever someone tests the webhook system for your bot on top.gg."""
print("Received a test upvote:", "\n", data, sep="")
def setup(bot):
bot.add_cog(TopGG(bot))```
this is my code
I'm using repl.it to host the beta bot right now
It doesn't even return any errors
First of all, the webhook path isn't supposed to be an IP
For instance, yes
same with me nothing happened but in js
Second of all, you need to make sure you entered the correct URL on your webhook page, as well as making sure the port you're using is open on the network
Well 0.0.0.0 isn't the public IP
const app = express() // Your express app
const webhook = new topgg.Webhook('password')
app.post('/dblwebhook', webhook.listener(vote => {
console.log(vote.user)
}))
app.listen(3000)
no error nothing happening
did you fill in the webhook url and auth on the website?
how can we get the user id of the voter?
You can't use the API until your bot is approved
i did auth @jaunty plank
need the url too
but not webhookurl
otherwise where will it send the request to
i know im just researching
that information can be found on the docs.
https://docs.top.gg/resources/webhooks/#bot-webhooks
https://docs.top.gg/resources/webhooks/#server-webhooks
i still dont understand the syntax
of what? theres nothing unique to top.gg going on with the webhooks.
just basic http requests
ohh
@jaunty plank i created webhook and pasted webhook URL still same
a discord webhook? top.gg webhooks are not compatible with discord webhooks.
you must use the url to your webhook receiver(your express app in this code)
@jaunty plank so how to get URL then
welp, its the url to your webhook receiver.
so probably something like this.
http://YOURPUBLICIP:3000/dblwebhook
YOURPUBLICIP should be replaced with the public ip your express webserver can use.
if your using a host which only gives a url and not a ip you must use the url they give, with the path added at the end.
Hello, is there a way to track votes without using cogs?
i did still

so its hosted on your pc?
yea
youll need to use your public ip for your computers network, and port forward then
your bots edit page, webhook section, test
does that do a vote? im not sure what it did
async def on_dbl_test(self, data):
print("Received a test upvote:", "\n", data, sep="")```
is this correct for receiving test vote notices?
yes i found my PC ip nothing happening
is there something can we do with port?
Hello, is there a way to track votes without using cogs? I'm Asking this twice
you need to use the public ip, and port forward
Sigh
yes
i dont know py. if you need it without cogs, you can make your own receiver. pretty sure there is a way with the library but i dont know it.
If you want to know how, I know how
that is his question, yes
I mean he just asked if there was a way
done bro
Can you tell me in dms?
I can tell you anywhere doesn't matter to me
const DBL = require('top.gg');
const dbl = new DBL('myapitoken', { webhookPort: 5000, webhookAuth: 'password' });
dbl.webhook.on('vote', vote => {
console.log(`User with ID ${vote.user} just voted!`);
});
nothing hapening
the ip in the url on top.gg, your using the public ip correct?
https://www.google.com/search?q=whats+my+ip
The port you use in your url, since you changed it should now be 5000, not 3000.
the portforward you did should be done from your router thats how you did it right?
also note, the top.gg library is deprecated, and may not function correctly.
this is the current library. https://www.npmjs.com/package/@top-gg/sdk
i did port forwad of my 1pv4 ip
hmm. then im out of ideas
but 1pv4 ip is different form my ip address
i can port forward 1pv4 ip but cant do my ip address
when you port forward you should forward the port to your local machine.
https://portforward.com/ may be able to help more than i can.
agh i am tired thank you so much for helping
@brittle sail please dont post ads
There's a data dictionary that is returned once the event is trigerred, you can get the user id by typing data["user"]
Are you using dblpy or topggpy
Hey guys
get_user_vote isnt working
It just returns False
even though we have voted
I use dblpy
Wait a few minutes then try again
@commands.command(brief="utils", description="Upvote Proteus")
async def vote(self, ctx):
try:
g = await self.dblpy.get_user_vote(int(ctx.author.id))
except Exception as e:
print(e)
print(g)
if g:
vote = "You have already voted for Proteus! Check back later to vote again."
else:
vote = "[top.gg](https://top.gg/bot/809077913080299535)"
embed = discord.Embed(
title="Vote for Proteus",
description=vote,
color=ctx.author.color
)
await ctx.send(embed=embed)```
No exceptions are returned
E
we did wait for some minutes
Wait more
bruh alright
The API can be slow in terms of user votes
im trying to get the user from webhook post request in php via $_POST['user'] but not working..
autopost still not working?
Hi anyone here who knows how to add the server count to your bot page?
What do you mean?
Is it okay when I post every 5 minutes my server stats guild without getting ratelimited?
Or when should I update my stats?
5 minutes is fine
kk thanks
When someone is voting can I receive this information?
(Java)
And when Im sending stats when should they update?
(on the website)
Via webserver yes
If the data doesn't refresh after posting stats, press Refresh Data on bot page
I pushed
But here stays N/A
Posting like this:
List<Guild> guilds = jda.getGuilds();
discordBotListAPI.setStats(guilds.size());
Something tells me that library either doesn't work or your code isn't working
Hmm any way to check if library does not work?
Seems like the code does not execute... Im confused but I hope now it works
When i did this i think it took a few minutes to come through first time, but you could always proxy it through something like burp to see what it's doing when it sends the request
Thank you soo much
Is setStats async because it stops my code
Vote messages are not working for me since end of April
const DBL = require("dblapi.js");
const dbl = new DBL(topggToken, { webhookPort: 5000, webhookAuth: webHookPassword }, client);
dbl.webhook.on('vote', vote => { //vote routine
console.log(`User with ID ${vote.user} just voted!`);
});
When voting I do not receive any message anymore.
use the new one in pins
Thank you
Or should I execute setStats in a new thread?
is this for discord api or dbl api or both
Only top.gg api
(This channel)
ok ty
nvm i just found out abt the topggpy, thanks!
hi
my ```js
const Topgg = require("@top-gg/sdk");
const express = require("express");
const app = express()
const DBL = require('dblapi.js');
const AutoPoster = require('topgg-autoposter');
const ap = AutoPoster(config.DBL_TOKEN, client)
const dbl = new DBL(config.DBL_TOKEN, { webhookPort: 5555, webhookAuth: '11211' });
dbl.webhook.on('vote', (vote)=>{
const eco = ecoschema.findOne({userID: vote.user.id})
const webhook = new Discord.WebhookClient('839215460624891915', 'OZ7wMQqK-wlzBlA33Lh0bwFYJvSAeXCQE_V_tcxBx1GRQEck5kRmxxZl_7hy--Fmx5Bb');
const voteembed = new Discord.MessageEmbed()
.setAuthor(`Thanks for Voting!`, client.displayAvatarURL())
.setDescription(`Thanks **${vote.user.tag}** for voting for Cyte Bot! \n You can vote again in 12 hours!\n [Click here to vote again!](https://top.gg/bot/754765403489828946/vote)`)
.setFooter("I have provided you your vote rewards successfully!")
.setColor("#0afa08")
webhook.send(`${vote.user}`, voteembed)
eco.money += Number(2000000)
eco.save()
vote.user.send(new Discord.MessageEmbed().setAuthor("Thanks for voting for me!", vote.user.displayAvatarURL({dynamic: true}))
.setDescription("I have successfully provided you `2,000,000` coins as your vote rewards!")
.addField("Please consider voting for me in the next 12 hours again!", `[Click here to vote again in the next 12 hours!](https://top.gg/bot/754765403489828946/vote)`)
.setColor("RANDOM")
)
})``` is not working, pls help







