#topgg-api
1 messages · Page 154 of 1
this is error because my bot is not aprove yet?
looks like your trying to use an api endpoint, not webhooks, but the same is true for using the api too. yes
i dont really know what i use i just look in docs and read and trying to understand
xD
https://docs.top.gg/resources/webhooks/
or if you are using the js lib
https://docs.top.gg/libraries/javascript/#webhooks
Sorry, quick question, what header does the top.gg webhook use? (both webhook and server)
the url to your webhook.
the auth you make for your webhook.
https://docs.top.gg/resources/webhooks/
this page covers all the headers and body.
where i make that??? and how
you just type it, its like a password.
as long as its the same between your code, and the site its valid.
Sorry but i already looked there, i don't see it
a normal webhook link, like this?
This might help you : https://comhad.github.io/webhook.html
It's an actual webhook, you need a webhook server to listen for it
Oh sugar, i forgot i already sent that to you lol
which you can set up using the libraries
it sends an auth header, and all the standard headers, such as content type and whatnot.
everything else is in the body.
Sorry, i meant content header, is it application/json?
I just ran it on a webhook site, it is
yeah
can anyone help me make vote logs?
@modern lagoon not sure what you mean, but you can send votes into a discord channel by using this
okk i will look into it thanks
DO NOT deploy this using the default flask server, you
should deploy it using WGSI module in apache2 or similar
setting.
may i know wht is meant by this?
why not pin that link lol its super usefull
When ever you run the standard flask server, it warns you that it's not tested for security issues and is only designed for testing, they mention this in the flask docs aswell
I would be honoured if that happened lol
lol
so how to bypass it?
Research how to deploy it onto your webserver of choice
DM a mod when
I don't think it's worth it, if a mod benefits from it, they're more than welcome to pin it but i don't think anyone should really go out of their way
i might be able to, do you have a specific question?
yes
i made a webhook and put it into the box and saved when i click test nothing happens in the channel
top.gg webhooks are not compatible with discord webhooks, you need to make your own webhook.
how can i do that?
theres a few libraries that might be able to help here.
https://docs.top.gg/
or you can make your own from scratch.
https://docs.top.gg/resources/webhooks/
ty
Can you get upvotes for the server without a bot?
Oh right, thank you
Hi, i'm doing a Bot for a school project and trying to include a vote command, but im seeing people complaining about the approval delay, i'll like to know if i can do something on the code to get a test vote link, or i'll have to exclude the vote function for the presentation of the project
You can setup your webhook service and use the test function on the topgg website
I’m not aware of delays but it they’re caused by topgg there’s nothing you can do about other than waiting until it may be fixed
There is no approval "delay". It's just the time it takes due to the amount of bots being submitted each day
lmao... I read webhook delay
Should wear glasses probably
Sorry, english isnt my main language, im aware the time it takes due to a lot of bots being submitted, i meant that saying delay, and thanks for the responses
How i create a webhook that is tiggered by someone vote?
Take a look at the pinned docs.
The contain examples how to use the API with or without libraries.
Keep in mind incoming connections from topgg to your webhook service do require to open your specified port in the firewall
so im self hosting my bot how do I setup my webhook settings page
like what ip should i add to port forward
your public ip:port/webhookpath
ok and do I need to port forward
Keep in mind incoming connections from topgg to your webhook service do require to open your specified port in the firewall
Yes you do
Port forwarding to the right device and setting up the firewall
where r u getting that info from
Hmm?
Keep in mind incoming connections from topgg to your webhook service do require to open your specified port in the firewall
that
Just scroll up a little bit
oh 

Make sure you actually have a real public IPv4 address and not DS-Lite
If not you won’t be able to host it at home
Can u say how to ignore that?
compare error codes?
You can just catch the error and ignore it with pass. Not related to the API though so move to #development if you have any further questions
wht is a webhook path?
@modern lagoon it is like https://someaddress.com/path
The endpoint which will receive data
where can i get this?
What do you mean where you can get?
Purchase a vps or something
Make sure the pot is opened
Do it something like
22.343.2.42:2334/path
That will not work it's just a example
so when i use this https://top.gg/api//bots/659980150946922497/check?userId=600707283097485322
it says unauthorized
how do i authorize it
i known but how do i put it in the url
Send an Authorization header
How Do I Get A Username While User Is Voting On My Top.gg Server
What Should I Use vote.username or what
try vote.user.username
Ok
cool

try this way then
hmm
Hmm
you need to fetch the user then get the users name
Oo
Ok
Hi, i just tried this webhook code ```py
from discord import *
from discord.ext import commands, tasks
from discord.utils import get
from datetime import datetime, timedelta
import random
import asyncio
import pyrebase
import os
import topgg
CONFIG = {
"secret config"
}
firebase = pyrebase.initialize_app(CONFIG)
db = firebase.database()
intents = Intents.all()
prefix = "."
client = commands.Bot(command_prefix=prefix, intents=intents)
random_color = 0x651DFF
#dbl_token = 'Top.gg token' # set this to your bot's Top.gg token
client.topgg_webhook = topgg.WebhookManager(client).dsl_webhook("/dblwebhook", "yamizero31")
client.loop.run_until_complete(client.topgg_webhook.run(5000))
@client.event
async def on_dsl_vote(data):
if data["type"] == "test":
return client.dispatch('dbl_test', data)
print(f"Received a vote:\n{data}")
@client.event
async def on_dsl_test(data):
print(f"Received a test vote:\n{data}")``` so i can get data when someone votes the server
it's not working and idk why
Could someone give me a sample guild stats autoposter code for my bot? (JavaScript)
I have no errors in my logs but nothing is displayed
and the same for the top.gg webhook
Do you have an approved bot to test your webhook with
approved bot? in topgg or in discord in general ?
@sullen nymph^
it's a custom bot so i don't think it will get approved in both of them
hmm? it's for the server
@client.event
async def on_dsl_vote(data):
if data["type"] == "test":
return client.dispatch('dbl_test', data)
why are you dispatching dbl_test and not dsl_test instead?
Yeah that clicked in my head halfway through my message
no worries
@sullen nymph so i made a friend who has his ports open test it but it didn't work with voting or testing webhook
i wonder if this will work
from discord.ext import commands
import dbl
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
self.token = 'dbl_token' # set this to your DBL token
self.dblpy = dbl.DBLClient(self.bot, self.token, webhook_path='/dblwebhook', webhook_auth='password', webhook_port=5000)
@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))```
What happens when you slap the URL in your browser and open it?
hmm it's not my IP so lemme tell them to do it
it says that this site can't be reached
Port isn't open then 👀
Could someone give me a sample guild stats autoposter code for my bot? (JavaScript)
and the same for the top.gg webhook plz 
https://docs.top.gg/ gang
Show your code and explain how it doesn't work
in the logs I have no error or operating message
it's been 1 hour and nothing changes
that is to say ?
That is to say that you're not running the client object
Could you send me the line to run it?
@sullen nymph we tried to enable port forward in the router but it's still closed
nvm i tried it with a hosting website and it worked

I want to put a webhook when a user votes my bot. But when I click on "Send test" via the site, its not working ...
For the webhook URL I put the given URL on my discord server (webhook management)
And for authorization, I put the code after the last "/" on the webhook link: https://discord.com/api/webhooks/identifer/authorization_here
I've been told I can't use discord webhooks, why?
Because Discord could block top.gg's IP addresses for sending too many webhook requests
Discord webhooks aren't compatible with Top.gg's webhooks. You need an actual webhook server to listen for votes
Plus it encourages you to do stuff manually instead of expecting support for everything
type IFTTT ?
You don't even need IFTTT for this tbh
How should I do it? Is there a tutorial?
You can host a webserver on your machine
someone should make a one click serverless deployment that forwards topgg webhooks to discord
on aws lambda
Repl 
it's free for the first 1 million votes a month
you are very useful
i've worked with api in the past but i can't understand these can anyone help me?
Bees?
sorry
Just install the topggpy package
can you write what lines I have to add to my repl
because I don t using visual studio code so I don t need to istall pip
or?
thx my boi
So i'm a little confused on this api here.
I have used it at all granted - but can the bots endpoint grab info for any bot?
Or just bots i've submitted?
That's fine, but when you do have an approved bot, does that /bots endpoint allow querying of all top.gg submitted bots, or just bots i myself have submitted?
first 500 afaik
Gotcha
Use contextually based HTTP requests instead
curl is an outdated method of pulling information
i am unable to authorize myself for the api idk why
is this the correct way to authorize?
just put the blurred value, don't put the {"Authorization": part
o
I'm not receiving the POST request on webhook when I hit the test button?
The authorization is a PASSWORD
If you want to set one, it’s not necessary needed
Make sure you save
Make sure to open your specific webhook service port in the firewall
how does the voting of a server exactly work, does anyone have an example of it?
How do I get who voted for my bot?
const Topgg = require('@top-gg/sdk')
const api = new Topgg.Api(process.env.TOPTOKEN)
setInterval(() => {
api.postStats({
serverCount: client.guilds.cache.size,
})
}, 1800000)
const webhook = new Topgg.Webhook(process.env.TOPGGAUTH)
app.post('/diamond_bot_wh', webhook.listener(vote => {
console.log(`Someone just voted ( ${vote.user} )`)
vote.user.send("**Thank You** so much for voting **DiamOnd_bOt [ db! ]** .\nI really do appreciate it!")
}))
app.listen(5000)
I did the things required in the webhook section of top.gg and saved it also.
No errors , no nothing.
And it doesn’t show the number of guild in top.gg
and also did
const app = express();
Installed the package express and @top-gg/sdk
Hello
@tawny smelt whats your code look like(please include the line you log req.body)
const express = require('express');
const app = express();
app.use(express.static('public'));
app.get('/', (req, res) => {
res.send('Online')
})
const voteWeb = new Discord.WebhookClient('841765098121199686', process.env.voteWebTOKEN)
app.post('/new/vote', (req, res) => {
console.clear()
console.log('new vote')
console.log(req.body)
/*if (req.header('Authorization') == process.env.voteTOKEN) {
res.send('Good!')
var user = req.body.user
const voteWebEmbed = new Discord.MessageEmbed()
.setTitle('Aha another vote!')
.setDescription(`<@!${user}> has voted!\nBe like them and vote [here](https://top.gg/servers/768927312178577449)`)
voteWeb.send(voteWebEmbed)
} else {
res.send('YOU THOUGHT')
}*/
})
app.listen(3000, () => console.log('Running'));
this code was used when i realized voting was broken
this is what console returns when i press test webhook ```txt
new vote
undefined
@jaunty plank?
all the libraries use the request body. https://github.com/top-gg/node-sdk/blob/master/src/structs/Webhook.ts#L59
not sure why it wouldnt work here
if it was, there would be others having this issue.
just ran it on a test bot, got a proper body response back.
https://i.woo.pics/9f5f9897fa.webp
oop, are you using a parser for json?
They're not
how to set up dbl server webhooks?
k
can I have the url?
me too
@restive otter Do you think topggpy should store IDs as int?
If you'd like to make some models, I guess
Yeah, thinking about them models
I can see they'll subclass DataDict 
Hey. Is there any examples for python with top.gg api
so when a user votes my bot it logs to console
A simple API wrapper for top.gg written in Python. Contribute to top-gg/python-sdk development by creating an account on GitHub.
Do you need it?
Yeah for the apis
Hey when i run the script it gives this error:
Traceback (most recent call last):
File "C:\Users\vxi\Desktop\Top.gg Noti System\main.py", line 7, in <module>
bot.topggpy = topgg.DBLClient(bot, dbl_token)
NameError: name 'bot' is not defined```
Should've added more comments in the example
, but isn't that pretty self-explanatory?
bot is supposed to be any object that subclasses discord.Client

lmao
just realized that I haven't deleted the dbl_token in the webhook example, it's pretty much redundant 

@restive otter on to add all of these as fields!
python has structs?
nah 
a data class sorry
never knew python had them, i haven't written anything yet in the language requiring me to use one
Are you gonna decorate DataDict then?
What do I decorate here? 
Well, how will type hinting behave though?
oh @dataclass won't override dunder methods
Superclass methods take priority?
Nevermind lmao, I think those which subclass DataDict should be decorated instead
But, won't it duplicate the data? Cuz it'll have them as attributes while we also have it as key-value pairs
Duplicate...
Maybe?
Will I be able to modify specific fields for typehinting with dataclass though?
Modify as in type casting them?
Yeah
Can't you do it in parse_dict?
by going to the library you use?
Ok i use javascript
the go to the javascript one
Ok.....
Then?
umm
When top.gg is sending request (because someone voted for the server) its sending without anything in the body (or am i just not receiving it?)
can some1 check if its just me or some1 else as well is having same problems?
hi, did you look at the conversation yesterday? seems we found the solution, guess you left though?
whoops
but thats on a bot not a server and what difference was there between my code and urs?
hello, I have a hard time understanding how to set up vote rewards with Java, I've looked into the docs, but I'm not sure if I need to set up a webserver or not for this API. So far I've implemented the API into the bot which works with JDA, but to create a new API object every time a message is sent gives me eventually an out of memory error while I got 48GB RAM.
the difference seems you are not parsing json
lemme try
webhooks needs a webserver, the api however does not need you to run a webserver on your end.
JSON.parse(req.body) thats correct right?
no, you need to tell app to use express.json()
how-?
I noticed that, but the API does not know when a user voted, which means I need to save when they voted myself, but this is a little unreliable. The only thing the API seems to know is that a user has voted or not.
👀 app.use(express.json())
webhooks are needed to get events when someone votes, you can make one then just have a single event handle all of them.
👀 doesnt seem the java lib supports webhooks anyway, so youll need to make your own from scratch
it will send up to 10(or 17?) until you send a proper status response
but in this case I wouldn't need to make a webhook with Java I assume? Plus I'm not sure on how to deploy webhooks neither
you would need to make a webhook with java to receive the webhooks.
that's what I thought 
One message removed from a suspended account.
O
what if i return 401 what will it do?
its just an http server, which receives requests
One message removed from a suspended account.
BotData(**resp_dict) with type hinting available
So yeah I can do what I want just fine with dataclass
maybe
401 will not be retried, however if you are properly receiving them you should send a 200
I know, just use TomEE in this case and it'll be fine, but I'm still not sure how to deploy this on a VPS
since they support default values
ye incase wrong auth is used
I'll have to figure it out as I go I guess, thanks for the info
if you do rewrite it and if it's possible, it would be great to know when a user has voted
use my library for that: https://github.com/Hopeful-Developers/topggwebhooks4j
Java Webhook Library for Top.gg. Contribute to Hopeful-Developers/topggwebhooks4j development by creating an account on GitHub.
if you're referring to webhooks
I'm not using webhooks yet, but seems like I will have to xD
even if the main library adds it, it will be in the form of webhooks.
I was referring to the API of Java, would be great if I could get the date time of when a user voted
yeah that's not possible with the api at all, best approach is using webhooks for that
Yeah I came to that conclusion as well with what Woo told me haha, thanks though 
btw lmao
It raises the proper AttributeError instance
Ah
But IDK, I haven't found someone does this, so I don't really know the drawbacks
Hey I need help
import dbl
# This example uses dblpy's webhook system.
# In order to run the webhook, at least webhook_port argument must be specified (number between 1024 and 49151).
dbl_token = 'top.gg token' # set this to your bot's top.gg token
bot.dblpy = dbl.DBLClient(bot, dbl_token, webhook_path='/dblwebhook', webhook_auth='password', webhook_port=5000)
@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}")
@bot.event
async def on_dbl_test(data):
"""An event that is called whenever someone tests the webhook system for your bot on top.gg."""
print(f"Received a test upvote:\n{data}")
When I run this, it shows 404 error. (P.S. I don't know much about APIs)

I am hosting on replit
Also, consider using topggpy
It shows 404 error
Whats the difference?
Well, I don't have right to say so when I'm literally still using dblpy
LMAO
404 when you visit the page in a browser?
or?
I don't know when I ran this, replit opened a browser webpage of my repl inside it. It shows 404 error
If you're accessing the / path, then your webhook is definitely running
seems normal, as your not running anything on that endpoint
Ah
Try accessing /dblwebhook, it should return 405 if it's running
That explains everything. Replit by default opens the root route
Root? Main? / you get it
How do I access that?
yourRepliturl/dblwebhook
But, it should be BASEURL/dblwebhook, yes ^^
I got 405
Then it's running
thats the url youll need to fill in on your bots page in the webhook section
Ohh, thank you
I wonder if adding a GET listener for DBL and DSL endpoints as a confirmation could be a good idea
still when I send a test webhook, I still don't get the data
did you fill in the auth section too?
Nope
youll need to fill it in
return web.Response(status=200, text="Webhook is running!1!1!1!1!1")
whatever is here in the code
webhook_auth='password'
with what?
In your case, it's password
in the example you showed, just password probably should make it something more secure
ohh
ohh finally got it.
Thanks a lot
Pfft, why do it the easy way?
>>> l
[87, 101, 98, 104, 111, 111, 107, 32, 105, 115, 32, 114, 117, 110, 110, 105, 110, 103]
>>> el
[33, 49, 33, 49, 33, 49, 33, 49, 33, 49, 33, 49, 33, 49, 33, 49, 33, 49, 33, 49, 33, 49, 33, 49, 33, 49, 33, 49, 33, 49, 33, 49, 33, 49, 33, 49, 33, 49, 33, 49]
>>> f"{''.join(chr(e) for e in l)}{''.join(chr(e) for e in el)}"
'Webhook is running!1!1!1!1!1!1!1!1!1!1!1!1!1!1!1!1!1!1!1!1'
👀 wth am i looking at
ASCII codes
char* gang
oh wth lmao
Does type hinting it without the decorator work?
I mean the init method doesn't have typehints
This is as ugly as it could ever get lmfao
Oh, I think I know what to do, let me test it
Guess who was using a different class
Sometimes I disappoint myself
Oh, so no, it doesn't help with type hints
Dataclasses were introduced in 3.7?
Welp, I tried this but seems like it only updates the __init__ annotations at runtime, so won't really type hint it.
I suppose so, it's in the what's new of 3.7 ig
oh oof, forgot to do self.__dict__ = self but w/e
I guess I'm going the painful way then
def __init__(self, donatebotguildid: int, id: int = None, username: str = None, discriminator: str = None,
avatar: str = None, def_avatar: str = None, prefix: str = None, shortdesc: str = None,
longdesc: str = None, tags: List[str] = None, website: str = None, support: str = None,
github: str = None, owners: List[int] = None, guilds: List[int] = None, invite: str = None,
date: datetime = None, certified_bot: bool = None, vanity: str = None, points: int = None,
monthly_points: int = None, *args, **kwargs):
Actually, am I okay?
No one's gonna need the type hints in the init since it's gonna be a received dictionary
That's why I asked you if you're gonna let the users instantiate the objects. Cuz they should be rest objects which shouldn't be instantiated manually xd
dbl_token = 'dbl token' # set this to your bot's top.gg token
client.dblpy = dbl.DBLClient(client, dbl_token, webhook_path='http://ip/dblwebhook', webhook_auth='password', webhook_port=5000)
@client.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}")
@client.event
async def on_dbl_test(data):
"""An event that is called whenever someone tests the webhook system for your bot on top.gg."""
print(f"Received a test upvote:\n{data}")```This isnt working plz help
how can i give test upvote?
go to webhook scroll down u will see test
thanks
this isnt a path webhook_path='http://ip/dblwebhook'
what should I put there ?
someone told me to put ip there
if thats the path you want, yes.
the actual url you use then will look something like this
http://yourpubliciphere:5000/dblwebhook
Do u want me to put webhook_path = http://yourpubliciphere:5000/dblwebhook
it should be a string ?
I am not able to understand
webhook_path = "/dblwebhook"
webhook_path is ONLY a path, not a url.
ya
did you replace yourpubliciphere with the proper ip
Is port 5000 open on the network you're hosting the bot on?
I am just using my pc for testing
youll need to port forward then
Yeah 
how I can do that ?
https://portforward.com/ lists guides for all the common routers for port forwarding
You can use websites like https://portchecker.co or https://canyouseeme.org to check if a port is open
See the link Woo sent, you need to forward the port on your Router
ok
I got an unclosed client session error after removing a webhook that didn't work. How do I fix this? And how do I build a functioning webhook?
(I can't post the full traceback as it is 5069 characters long, and Discord has a 2k limit)
Trace:
client_session: <aiohttp.client.ClientSession object at 0x7fc2c44ef040>
Task exception was never retrieved
future: <Task finished name='Task-1' coro=<DBLClient._webhook() done, defined at /opt/virtualenvs/python3/lib/python3.8/site-packages/dbl/client.py:436> exception=OSError(98, "error while attempting to bind on address ('0.0.0.0', 8080): address already in use")>
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/dbl/client.py", line 457, in _webhook
await self._webserver.start()
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/aiohttp/web_runner.py", line 121, in start
self._server = await loop.create_server(
File "/usr/lib/python3.8/asyncio/base_events.py", line 1463, in create_server
raise OSError(err.errno, 'error while attempting '
OSError: [Errno 98] error while attempting to bind on address ('0.0.0.0', 8080): address already in use
Traceback (most recent call last):
File "main.py", line 62, in <module>
bot.run(token)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 718, in run
return future.result()
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 697, in runner
await self.start(*args, **kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 660, in start
await self.login(*args, bot=bot)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 509, in login
await self.http.static_login(token.strip(), bot=bot)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/http.py", line 293, in static_login
data = await self.request(Route('GET', '/users/@me'))
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/http.py", line 209, in request
raise HTTPException(r, data)
discord.errors.HTTPException: 429 Too Many Requests (error code: 0):
#html & css spam -->
"error while attempting to bind on address ('0.0.0.0', 8080): address already in use")>
looks like your still opening a webserver, and opening it on a port which is already used
ratelimited 
oh yeah, looks like discords ratelimiting your bot too
I'm using Replit.com to host the bot, so whenever I reload the page I'm hosting the bot on, that should close the webserver and start a new one right? (I'm relatively new to webservers and have no idea how webhooks work. This happened after trying to add a webhook to read votes from Top.gg, but the error stayed after removing the non-functional webhook)
There's a lot going on in the trace, so I'm not sure where my initial issue is and how to fix it.
Not exactly. Ideally, you only want to run the webhook once and let the repl keep alive keep your stuff running. Reloading pages on its own shouldn't re-run a webhook (or anything really)
I have a half-assed repl laying around to showcase such scenarios https://replit.com/@AssanaliMukhano/dpy-webserver-cog-example#cog.py
I removed the webhook which started the huge trace, but it didn't fix anything. I don't understand why
Seems like the culprit isn't the webhook
Maybe it's just your bot failing to start that causes all this
@restive otter Does this even need any tests?
DataDict may do
def test_data_dict_fields(data_dict: types.DataDict):
for attr in data_dict.copy():
if 'id' in attr.lower():
assert isinstance(bot_data[attr], int)
assert data_dict.get(attr) == data_dict[attr] == getattr(data_dict, attr)
btw why is there kwargs there?
Because PyCharm decided to add it there 
You're setting the attributes btw, that'll be fine if you do self.__dict__ = self in the DataDict as it won't duplicate them.
Never seen someone doing that though, might be uncommon
If it works, I don't see a problem 😛
Micro-optimization™️

Will pycharm scream at you if you pass the parameters to the superclass init instead of setting them as attributes?
Oh, actually
nevermind, I think both implementations should work lmao. They won't duplicate the data
def __init__(
self,
id: Optional[int] = None,
format: str = None,
type: str = None,
noavatar: bool = False,
colors: Colors = None,
colours: Colors = None,
):
super().__init__(
id=id,
format=format or "png",
type=type or "",
noavatar=noavatar or False,
colors=colors or colours or {}
)
this is what I have for WidgetOptions right now and PyCharm is fine with it
yeah lmao, I might be sleepy, it won't duplicate the data
But this is so compact
```py
class Test(dict):
def init(self, *args, **kwargs):
super().init(*args, **kwargs)
self.dict = self
It is 
Ah, but I think better stick with the former as it won't override built-in methods such as keys, items and whatnot. I mean, it's not like people are gonna assign it
but w/e
Who knows 
Back to "I usually prefer to think that whoever uses dblpy is a newbie, so anything is possible" xd
Yup 😂
Ehh
I'll blame whoever decides to override built-in methods since I prefer to have the attribute error show up properly
How do I know what my webhook path is?
it's whatever you set it to
I know I did somewhere, but idk where I stored that info. :/
by using the check endpoint: https://docs.top.gg
yeahh got it!! Thankss
didnt see the docs before 😅
What library do you use?
You can use topggpy's autopost feature
pls
A simple API wrapper for top.gg written in Python. Contribute to top-gg/python-sdk development by creating an account on GitHub.
All tokens are private and you use them to authenticate your bot
For this you want your bot's top.gg token
ye
See pinned messages in this channel
isnt it
done thankyou
What do you mean?
i want to use top.gg api so that i can get to know that who voted it and it should come in a specified channel like Samey#0174 jus votes Rythm like this
Top.gg supports webhooks, which means you can receive votes (for your bots only) in real-time and process them as needed
hi i'm using dblpy to make a post req to top.gg to post guild count (using autopost = True thing), but that doesn't work
it don't post the guild count :/
also tried with manual post, same result
Are you sure the client gets instantiated?
Are you sure the client you attach DBLClient to is listed on top.gg?
Are you sure the top.gg token you entered is valid?
Okay my fingers hurt from typing
class Top(commands.Cog):
def __init__(self, bot):
self.bot = bot
dbl_token = 'token' # set this to your bot's Top.gg token
bot.dblpy = dbl.DBLClient(bot, dbl_token, autopost=True, webhook_path='/dblwebhook', webhook_auth="my_auth", webhook_port=myport)
@commands.Cog.listener()
async def on_ready(self):
print(f"TopGG Loaded")
that's my code
yes, 100% sure
regenered rn
already tried, same result
not poggers
@commands.Cog.listener()
async def on_guild_post(self):
"""This function runs every 5 minutes to automatically update your server count."""
await self.bot.wait_until_ready()
try:
await self.bot.dblpy.post_guild_count()
channel = 834212576061161472
d = self.bot.get_channel(channel)
a = "[**`top.gg`**](https://top.gg/bot/801742991185936384)"
em = discord.Embed(description=f' Server count (**`{len(self.bot.guilds)}`**) was succesfully posted on {a} with **`{round(self.bot.latency*1000, 2)}ms`**', color = 0xffcff1)
await d.send(embed=em)
except Exception as e:
print('Failed to post server count\n{}: {}'.format(type(e).__name__, e))
``` that's the listener i use for recive posted guild
neither, autopost and manual post broken f
@vital anvil there's an issue with the api or i'm unlucky? tried manual guild post and autopost, no one work, the token is the right one
We didn't do any changes on the API
well, so i'm unlucky, i can't post guild count anymore
One message removed from a suspended account.
what response do you get
no response, my shell isn't logging anything
waow sexs
One message removed from a suspended account.
owww sorryy
Try using topggpy ftw
well, lemme try
wait
topggpy is what i'm using
._.
why the docs are the same of dblpy
One message removed from a suspended account.
One message removed from a suspended account.
One message removed from a suspended account.
well, so i'm using it already
how can i make a manual request to top.gg to post guild count?
postman, curl or something similar
@sullen nymph might be a good thing to add errors if something goes wrong in the autoposting then
lemme try make a post req with aiohttp
what's the url where send post req? my bot page?
Would be good if you spend some time reading the docs
Sorry, didn't mean to, I mean, the docs tell the URL
Here's the URL look for "Bot stats" https://docs.top.gg/api/bot/
I'll update them in v1.1
It shouldn't, idk what's going on
I'm still using it and it works, so it shouldn't
Thing is they manually post it in a listener which gets dispatched on auto post
ReCuRSION????????
Whre can i get a api token?
not as bad 
I use js
See pinned messages ig
Thank you ❤️
401
Put your token in the authorization header
@gio
well, with post req it worked
but why autopost doesn't work?
Hmm, try migrating to topggpy if you were using dblpy
lemme try
@vital anvil is there no way for us to determine which rate limit we hit? https://docs.top.gg/resources/ratelimits/#exceeding-a-rate-limit
Or is this something that will be addressed in API/1.1?
right now there isnt
ah, alright
Where can i generate a Token and Auth?
You cannot generate a token while your bot isn't approved
Ok
hi
how to use the server api pls?
i need to get votes and create a webhook server (like for the bot api)
its the same thing practically for server and bot webhooks
ok thanks!
only real difference https://docs.top.gg/resources/webhooks/#server-webhooks
I want to know how can i check whether someone has voted for my bot or not? I saw some documents but i am not able to do the header : authorisation part
In what way are you "not able to"? Do you just not know what to do, or are you running into errors?
import discord
import dbl
class TopGG(commands.Cog):
def __init__(self, client):
self.client = client
self.token = 'dbl_token'
self.dblpy = dbl.DBLClient(self.client, self.token, webhook_path='/dblwebhook', webhook_auth='yamizero31', webhook_port="somePortNum")
@commands.Cog.listener()
async def on_dbl_vote(self, data):
print(data)```guys this event gets called twice
idk why
how should i fix it?
btw it's for server vote and not bot votes
Use topggpy
How...
idk, i putted the 2 packages
topggpy and dbl
one in each file and ran the bot
the one that responded was dbl
My question is why would you combine both
Yeah well there are changes in topggpy
That's probably why it didn't work 🤷
Because it works just fine for me
widget_options = {'id': 264811613708746752, 'format': 'png', 'type': '', 'noavatar': False, 'colors': {'text': 0}}
def test_widget_options_fields(widget_options: types.WidgetOptions):
for attr in widget_options:
if "id" in attr.lower():
assert isinstance(widget_options[attr], int)
> assert (
widget_options.get(attr)
== widget_options[attr]
== getattr(widget_options, attr)
)
E AssertionError: assert '' == None
test_type.py:74: AssertionError
@restive otter Well, this sounds fun 😂
I'm not sure which comparison it's complaining about honestly
Since it's showing '' == None
Let's divide them
So, must be the last 2
Yup
widget_options = {'id': 264811613708746752, 'format': 'png', 'type': '', 'noavatar': False, 'colors': {'text': 0}}
def test_widget_options_fields(widget_options: types.WidgetOptions):
for attr in widget_options:
if "id" in attr.lower():
assert isinstance(widget_options[attr], int)
assert widget_options.get(attr) == widget_options[attr]
> assert widget_options[attr] == getattr(widget_options, attr)
E AssertionError: assert '' == None
test_type.py:75: AssertionError
@sullen nymphsorry but i remember you told me that i can await this using client.something
client.topgg_webhook.run(5000) i don't remember what was it so can u help me?
Is that the repr of widget_options? If not, that should be a dict?
In version 1.0.1 you can just run it as-is
oh alr
Yeah, that's the repr
@pytest.fixture
def widget_options():
wo = types.WidgetOptions(id=int(d["id"]))
wo.colours = {"background": 0xFF0000}
wo["colours"]["text"] = 0
return wo
this is the fixture I use for that
/home/container/philosophia.py:69: RuntimeWarning: coroutine 'WebhookManager.run' was never awaited
client.topgg_webhook.run(5000) # this method can be awaited as well
RuntimeWarning: Enable tracemalloc to get the object allocation traceback```
Either pass it onto client.loop.run_until_complete or client.loop.create_task
Oh, it's not in 1.0.1?
You haven't pushed it iirc
Let me see
Btw the attr raising the error was type, wasn't it? How can it be None lmao, it defaults to "", doesn't it?
Yup, last release was 12 days ago and your PR was merged 11 days ago
It's multiple attrs actually
Oh? Interesting
id
True
False
False
format
True
True
True
type
True
False
False
noavatar
True
True
True
colors
True
False
False
>>> for attr in wo:
... print(attr)
... print(wo.get(attr) == wo[attr])
... print(wo[attr] == getattr(wo, attr))
... print(wo.get(attr) == getattr(wo, attr))
Yeah, give me a sec
that's the one i am looking for lol
i forgot it
Having an issue with colors and colours right now, that issue is fixed
How did you alias it?
If you've overridden the __setitem__, __getitem__ and get, ig the setter and getter will be redundant
Wonder if get is synced with __getitem__
We'll see
It's not?
>>> print(wo.get('colours'), wo.get('colors'))
None {'text': 0}
nvm, it's not redundant
Cuz, __getattr__ is getting directly from __dict__ attr
id
True
True
True
format
True
True
True
type
True
True
True
noavatar
True
True
True
colors
True
True
True
So why is my test failing lol
lmao
f /home/container/requirements.txt ]]; then pip install -U --target /home/container/ -r requirements.txt; fi; /usr/local/bin/python /home/container/philosophia.py
Traceback (most recent call last):
File "/home/container/discord/ext/commands/bot.py", line 606, in _load_from_module_spec
spec.loader.exec_module(lib)
File "<frozen importlib._bootstrap_external>", line 783, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/home/container/philosophia_Cogs/moderation.py", line 14, in <module>
from philosophia import AUTOACTIONS
File "/home/container/philosophia.py", line 70, in <module>
asyncio.get_event_loop().run_until_complete(client.topgg_webhook.run(5000))
File "/usr/local/lib/python3.8/asyncio/base_events.py", line 616, in run_until_complete
return future.result()
File "/home/container/topgg/webhook.py", line 120, in run
await self._webserver.start()
File "/home/container/aiohttp/web_runner.py", line 121, in start
self._server = await loop.create_server(
File "/usr/local/lib/python3.8/asyncio/base_events.py", line 1463, in create_server
raise OSError(err.errno, 'error while attempting '
OSError: [Errno 98] error while attempting to bind on address ('0.0.0.0', 5000): address already in use
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/container/philosophia.py", line 3225, in <module>
client.load_extension(f'philosophia_Cogs.{filename[:-3]}')
File "/home/container/discord/ext/commands/bot.py", line 678, in load_extension
self._load_from_module_spec(spec, name)
File "/home/container/discord/ext/commands/bot.py", line 609, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'philosophia_Cogs.moderation' raised an error: OSError: [Errno 98] error while attempting to bind on address ('0.0.0.0', 5000): address already in use``` i get this error when i try to await it
My fields and keys aren't synced lmao
OSError: [Errno 98] error while attempting to bind on address ('0.0.0.0', 5000): address already in use
Port 5000 is already used by something

still same issue
i changed it from 5000 to client.loop.run_until_complete(client.topgg_webhook.run(4484))
4484 is supposed to be the port of the server i am hosting the bot in
Sounds like you're trying to run it twice
?
Sounds like you're trying to call .run twice
i don't get it
where else would i run it?
Can you show your code?
Seems like it runs because you imported your file again, try __main__ guard it
if __name__ == '__main__':
# run the webhook
hmm?
sorry but where should i put that?
like when i run the bot? cause that's the main file so
if __name__ == "__main__":
client.run("token")``` ?
The <WebhookManager>.run method
what's that?
do u mean this?
client.loop.run_until_complete(client.topgg_webhook.run(4484))``` ?
Yes, would be a good idea if you also __main__ guard the client.run
Would be a better idea to implement this so you don't need to import your main file 

it's still being called more than 1
this time it got called 4 times
now two times
Not sure what you're doing
inb4 it's a recursion

This hurts to read but... it works?
@restive otter What do you think?
The getattr seems redundant
I'll probably adjust the test and test field/key changes
is this your json decoder/encoder
is colors present everywhere?
Yeah, I've been playing around with WidgetOptions and colors key was always present
- I create it in superinit so it's always present
I mean, in every payload
Oh I see what you mean
Think I should move the check to WidgetOptions methods and call supermethods?
Nah, I don't need one here
These aren't necessary ig, since you already got the getter and setter
Yeah, I removed the getattr method
I do seem to need the setitem in setattr to sync the data
It already is?
Give me a minute
def __setitem__(self, key, value):
if key == 'colours':
key = 'colors'
dict.__setitem__(self, key, value)
setattr(self, key, value)
def __getitem__(self, item):
if item == "colours":
item = "colors"
return dict.__getitem__(self, item)
def get(self, key):
if key == 'colours':
key = 'colors'
return super().get(key)
def __setattr__(self, key, value):
if key == 'colours':
key = 'colors'
object.__setattr__(self, key, value)
dict.__setitem__(self, key, value)
Should I change anything here? These are WidgetOptions methods
Since I'm basically redirecting anything colours to colors
setattr(self, key, value) is redundant imo
As well as object.__setattr__(self, key, value)
Why is the __setattr__ still there? Did something break when you removed it?
Yeah, I want setattr to update the dict
The latter wouldn't update if I did WO().colours = y
Ah, I think I see the problem
self.__dict__ = kwargs, it's referencing to kwargs dict, instead of the dict object itself
Try changing it to self and remove the setattr method
But my parse_dict 
It's fine because it's already passed to the init
Oh oh
At that point, kwargs is equivalent to the dict instantiated, but they're not the same object
So, when you're modifying the attribute, you're modifying the kwargs, not the dict.
Yeah, since apparently it's not synced with __getitem__
I have a print in getitem and using .get does nothing, soooooooo

Actually hold on
>>> d['id']
id
123
>>> d.get('id')
123
yeah
Python™️
Can i get a link to any document which explains the whole api?
How come you can't
npm i @topgg/sdk not working
Any errors?
🖊️
pls help
yes
``C:\Users\Administrator\Desktop\SJ-Bot-main>npm i @topgg/sdk
npm ERR! code E404
npm ERR! 404 Not Found - GET https://registry.npmjs.org/@topgg%2Fsdk - Not found
npm ERR! 404
npm ERR! 404 '@topgg/sdk@latest' is not in the npm registry.
npm ERR! 404 You should bug the author to publish it (or use the name yourself!)
npm ERR! 404
npm ERR! 404 Note that you can also install from a
npm ERR! 404 tarball, folder, http url, or git url.
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\Administrator\AppData\Roaming\npm-cache_logs\2021-05-14T1
0_14_57_252Z-debug.log
``
npm install @top-gg/sdk
i try this
and give me error
what is going on
all my modules are gone
and i try to download it
error
i get
import discord
from discord.ext import commands
import dbl
client = commands.Bot(command_prefix="a!")
dbl_token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjgxMTczMzU5OTUwOTU0NDk2MiIsImJvdCI6dHJ1ZSwiaWF0IjoxNjE4NTIyNjA1fQ.HZzo6josspmshNaOq41LrwBJSMiJLeGmbtsTynFKgAo'
client.dblpy = dbl.DBLClient(client, dbl_token, webhook_path='/Testvote', webhook_auth='Astradiscord', webhook_port=5000)
class topgg(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_dbl_vote(self, data):
print(f"Received an upvote:\n{data}")
@commands.Cog.listener()
async def on_dbl_test(self, data):
print(f"Received a test upvote:\n{data}")
def setup(bot):
bot.add_cog(topgg(bot))```
why is this not working?
it's node-gyp error, not related top.gg
not @topgg/sdk
use @top-gg/sdk
thanks for your help but deleting the node_modules folder worked
okay
?
i changed it before
Why are you creating a commands.Bot instance in a cog file
idk a friend does that
Create DBLClient in the cog's init method
Your friend is dumb then
Well, rather, dumb in terms of working with d.py cogs
how to do that?
a method is something like keep_alive() or?
Egh
A function attached to a class
hence you have bot.add_cog
add_cog is a method
ah yes
of object bot, which is an instance of commands.Bot class
Do you see the init method
yes
How do you do this
sry but i dont understand you right now i'm not good in english
can you give me any examples?😬
yes but how must the function look like. i know how i can create a function in a class but what code must be in the function.
In the init method you attach some attribute to the cog (instance of one) with self.x = y where x is the attribute and y is the value
The attribute name is whatever you feel like using, value will be an instance of DBLClient
and how this looks like?
yes okay. what must in the webhook path and wbhook auth, where can i find these variables from my bot
Show me how an instance is created
class topgg(commands.Cog):
def init(self, bot):
self.bot = bot
Can anyone explain, what are http headers?
Webhook path is a path that's used in the webhook URL that you will use on top.gg. For example, http://1.2.3.4:5000/path is a URL you could use hypothetically. /path here is the path (also known as route) that will be used specifically for the DBL webhook.
No, that's creating a class with an init method. Why not take your time learning the basics of Python OOP?
How much time have you spent searching up your question on Google?
Not at all, i read the document and saw there headers, maybe i thought it was ok to ask here, sorry.
It's generally a better idea to search up your question and try to find an answer yourself. That way you teach yourself to be more or less independent
Plus it's easier if you just search up what's already there. On top of that, you might learn something new apart from what you search
okay, thank you

hi.
Ello
can someone give me or help me with the code of server count on top.gg
?
or tell me where should i put it?
read pins
Wdym
Can i have a voting in top.gg required command with bdfd? It has new updates, it now supports : httpGet, httpPost, httpPut, httpDelete, httpPatch and httpResult
: ( js FetchError: request to https://top.gg/api//bots/stats failed, reason: Client network socket disconnected before secure TLS connection was established at ClientRequest.<anonymous> (/home/runner/Pop-Cat-Official/node_modules/node-fetch/lib/index.js:1461:11) at ClientRequest.emit (events.js:314:20) at ClientRequest.EventEmitter.emit (domain.js:483:12) at TLSSocket.socketErrorListener (_http_client.js:427:9) at TLSSocket.emit (events.js:314:20) at TLSSocket.EventEmitter.emit (domain.js:483:12) at emitErrorNT (internal/streams/destroy.js:92:8) at emitErrorAndCloseNT (internal/streams/destroy.js:60:3) at processTicksAndRejections (internal/process/task_queues.js:84:21) { type: 'system', errno: 'ECONNRESET', code: 'ECONNRESET' }
i have a bot on top.gg and i want to show me the server count on the page
where should i put this
wdym
How do I make a topgg stats command?
Speak spanish?
hi, how to find out the password from the level in gd?
I speak spanish
Que bien
how can i make a command to see how much vote does user have
you need to track that yourself, you cannot check how many votes a specific user has
Hi, wanted to ask. If i didn't want to use the topgg/sdk npm, would that be possible (for vote webhooks)
and this would be the code right?
app.post("/dblwebhook", (req, res) => {
if (req.headers.authorization == "thepassword") {
console.log(req.body.user)
}
})```
can i give webhook url of my discord server?
so i will need to create a new website?
that gets the post request?
@crisp hound here's a guide that doesn't need a server https://comhad.github.io/webhook.html
thanks dude
discordbotlist won't let me sign in ( it turns out login with discord doesn't have an address to send us after we click it)
It just uses discordbotlist as an example, it still works with other platforms
@crisp hound
Provide what exactly? It just uses discordbotlist as an example, if you follow the same steps it works for top.gg
Yeah
There was a problem saving the webhook
I get this error @spice helm
Oh, that's odd, can you send a screenshot of it?
@spice helm dmed u if that's cool
Yeah
Hi
@rain heart sir i have seen a server from there there is vote count of their bot
ok?
wait i will give you link of the server in dm
Can you just ask here and wait for someone as I'm not able to help, nor can be
ok
Have something more important to do
yes can you tell me why webbook is exactly used
Read the docs. He just said he has other things to do.
ok
Gamer moment
@restive otter hey, what programming language is your bot in?
youll need to fill out the webhook url and webhook auth on your bots edit page in the webhook section
What should I do with webhook URL
its going to be the url to your webhook. will look something like
http://PUBLICIPHERE:PORT/PATH
your port and path will be defined in your code(linked above)
What is the limit to get voting information?
60/minute
could anyone send me the code to create an embed for discord.py that I can just paste in and fill in the way I want to?
cough see channel topic
Also you have to be dumb to not be able to understand how to do that by reading the d.py docs
k
im using discord.py for my bot and im not sure how to use the vote detection
I installed dbl and tried implementing the on_dbl_vote(data) bot event but it doesn't print anything when votes happen
I also tried implementing the on_dbl_test(data) but that also doesnt print when i try to test
Fixed it, i simply had the wrong IP in the webhook URL
👍
do I have to host a website for webhooks?
a webserver yes
Is there a doc or something to see how to create a webhook?
https://docs.top.gg/ the libraries section has some libraries many of them can make webhooks.
if you plan on making one without a library, https://docs.top.gg/resources/webhooks/, however it doesn't get into the webserver itself, that's up to you.
Hi I am new here and looking for friends 😊
What do you mean not in this channel
-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.
I want to make one without a library but I dont understand how to do it
webhooks is new to me
what programming language are you planning on making your webhook in?
python
thanks
guys is it possible to check vote users using the api? I don't like the webhooks
i have to delete their user name after they claimed their reward
you cannot get live votes though, only when for example the user uses a command for you to then check if they voted
see above
i mma stick with my webhook
lol
on https://docs.top.gg/api/user/ for defAvatar it should say if the user has one, not none
can u get the user id of a voter with the api?
You can get if a user has voted in the last 12 hrs
IDK about getting user (maybe use Webhook for that)
hmmm ayt
Yes you can as well as the incoming webhook will also contain the user id.


we're trying to debug here



