#topgg-api
1 messages Β· Page 54 of 1
It works but... yeah
It's bad
You could try and find them but idk if that's better than just giving users more practice with aiohttp 
i have no practice with it
Just copy the source code and modify it kek
If dblpy didn't make it all to complicated on the backend, yep
just looking at the source code even it is kind of a mess
@sullen nymph any clue what self.BASE is?
Iirc, the formatted link to DBL endpoint
ah i just found it
eww no IPv4 didnt make it
it would've been deleted by now
@plain timber thought that too but because I generated it in the docs page It didn't work. i generated a new one on the edit page of the bot and now it works , wierdd , thanks for your help
Thonkku could you please check if my server's ip has been banned? On windows I don't get any 403 errors but on my server yes
it's not
why does it then spit 403 error on my linux server
I am using the example from doc
to be exact :
import dbl
import discord
from discord.ext import commands
import aiohttp
import asyncio
import logging
class DiscordBotsOrgAPI(commands.Cog):
"""Handles interactions with the discordbots.org API"""
def __init__(self, bot):
self.bot = bot
self.token = 'xxx' # set this to your DBL token
self.dblpy = dbl.Client(self.bot, self.token)
self.bot.loop.create_task(self.update_stats())
async def update_stats(self):
"""This function runs every 30 minutes to automatically update your server count"""
while True:
logger.info('attempting to post server count')
try:
await self.dblpy.post_server_count()
logger.info('posted server count ({})'.format(len(self.bot.guilds)))
except Exception as e:
logger.exception('Failed to post server count\n{}: {}'.format(type(e).__name__, e))
await asyncio.sleep(1800)
def setup(bot):
global logger
logger = logging.getLogger('bot')
bot.add_cog(DiscordBotsOrgAPI(bot))

@restive otter u didnt blur it in the command part
i realize that
lol
deletd it
he removed his server ip so
not gunna repost it
but his sql server is wide open
and his apache install has some vulnerabilities
for now I am using it only for private purposes uber
so I am not worring about that
will deal with them at some point
you might want to close your sql port if your only using it locally
on your firewall
and update apache
it's not locally only
does someone know why I get the 403 on linux?
Forbidden: Forbidden (status code: 403): {"error":"Forbidden"}
Traceback (most recent call last):
File "/home/discord/alcapone/cogs/dbl.py", line 25, in update_stats
await self.dblpy.post_server_count()
File "/usr/local/lib/python3.6/dist-packages/dbl/client.py", line 100, in post_server_count
await self.http.post_server_count(self.bot_id, self.guild_count(), shard_count, shard_no)
File "/usr/local/lib/python3.6/dist-packages/dbl/http.py", line 189, in post_server_count
await self.request('POST', '{}/bots/{}/stats'.format(self.BASE, bot_id), json=payload)
File "/usr/local/lib/python3.6/dist-packages/dbl/http.py", line 160, in request
raise Forbidden(resp, data)
I am using the dblpy version installed with pip
Might just be because dblpy is broken
and there isn't another library right ?
Just use aiohttp
ok thanks
Well
something new about my problem?
xd
haiii
can i catch some help here with the website server count for python 3.6? ._.
Posting or getting?
getting
i have a servercount in my status but would like build in the function from #312614469819826177
I have the code
oh cool
in discord.js how would i make it so that if there is a ratelimit of some kind it would send the details about it in a channel, for example #ratelimits pm me if possible
@devout dragon That is a question for #development
Sorry
When you post a server count does it normally take a few minutes?
Because if it does then maybe my code worked if it didnt then my code lied to me and it didnt actually work
No, it's normally as soon as you recieve a response
Yeh it's normally instant
Anyone know how to do the webhook stuff in js with dblapi.js? For me when i try webhook it just errors about the on thing
dbl.webhook.on('ready', hook => {
// stuff
});
Send The error @restive otter
well it just says it can't 'on' of undefined or somethin
Send it
dbl.webhook.on('vote', vote => { console.log(`User with ID ${vote.user} just voted!`); });
yeah i did that yos
You are hosting
Where?
@restive otter
ima get it
hmm
nvm now it works somehow π€ didn't work with exact same code before smhh
π
dbl.errors.Forbidden: Forbidden (status code: 403): {"error":"Forbidden"}```
Anyone know why I might be getting this error
Token invalid
My bots showing as offline.
I did a quick search for online in:api (as I assumed it was an API thing like server count) and it appears the bot needs to be invited to this server for the status to show online.
How long after approval does that happen or do I have to request it somewhere?
Improper channel, but you get the bot dev role as soon as it's accepted and thry are added as soon as their accepted so whenever luca dms you
It may have been kicked
@sullen nymph but what if my token is not invalid?
you get forbidden if you are banned from the api or the token is wrong
No why do you have to use the right id with the right token
Cuz then I cant test it without fucking up my bot
Because you post stats with the id and token
/bots/id/stats
You cant post to a bot that isnt yours or doesnt exist
But you should be able to.............................................
For testing purposes
So you can test and not mess up the things that matter
just console.log the servers
Ok it still doesnt work
I still get a forbidden error even when I use the right ID
import dbl
import discord
from discord.ext import commands
import asyncio
class DiscordBotsOrgAPI(commands.Cog):
"""Handles interactions with the discordbots.org API"""
def __init__(self, bot):
self.bot = bot
if 'DBLToken' not in self.bot.config:
self.bot.logger.error("Please disable modules.Discord Bots List API.DiscordBotsOrgAPI in bot.py")
exit(3)
self.token = self.bot.config['DBLToken'] # set this to your DBL token
self.dblpy = dbl.Client(self.bot, self.token)
self.bot.loop.create_task(self.update_stats())
async def update_stats(self):
"""This function runs every 30 minutes to automatically update your server count"""
while True:
self.bot.logger.info('Attempting to post server count')
try:
await self.dblpy.post_server_count()
self.bot.logger.info('Posted server count ({})'.format(len(self.bot.guilds)))
except Exception as e:
self.bot.logger.exception('Failed to post server count\n{}: {}'.format(type(e).__name__, e))
await asyncio.sleep(1800)
def setup(bot):
bot.add_cog(DiscordBotsOrgAPI(bot))
This is my code
isnt dblpy known to be broken?
I just learned this
yeah youre better off making a regular POST request to the api or seomrhitn
you only need a webserver if you want to use the webhooks
if you just want to post server count you dont need a webserver
i dont really use python. just google "python http POST request" and read the dbl api docs
read the docs
the documentation of the api is amazing
scroll down on this page
so its /api/bots/id/stats
idk, i didnt read it xd
nvm
hey is there like a starboard leaderboard?
Hi
@cyan wyvern use aiohttp
Anyone using the npm package for webhooks that also hosts using NGINX have issues with the webhook receiving votes?
hi guys
help
pip install dblpy
Traceback (most recent call last):
File "/usr/bin/pip", line 11, in <module>
sys.exit(main())
File "/usr/lib/python2.7/dist-packages/pip/init.py", line 215, in main
locale.setlocale(locale.LC_ALL, '')
File "/usr/lib/python2.7/locale.py", line 581, in setlocale
return _setlocale(category, locale)
locale.Error: unsupported locale setting
when installed libs such error
reinstall pip? idk
his question already got answered in #development
he reposted here at the same time he asked there
@here
no
not even close
@everyone
Is it disable
at least do it in #memes-and-media smh
...
this is off topic for this channel
very
i need fun api
Why does it say that my bot is offline?
On the site? I just enabled the API and now it says its offline.
i dunno
@slender void the API isn't related to online/offline status on the site
It gets that through discord
Oh
Ok
I was wondering that
Guess it just takes a few minutes to register
I do like the API though
Its really easy to use
for the api, are the only stats you can post server_count?
You can look at the docs
Dblpy is broken, dont use it
Does the current dblpy wersion work with the latest discord.py@rewrite version? Any experiences with it?
It does depend on the bot lib.
Not really
It works
But not quite well
Just make a HTTP request yourself
With aiohttp
ok, or I could make another api lib
If you want to
Client lib wat
client for dbl api, language doesn't matter
Probably dbljs
Ok then I can look at it for reference how the API works, thank you!
Better to actually use dblpy source code for that tbh
But it is incomplete
It has working stuff
xd
it literally takes like 3 lines to make the request with aiohttp
I'm getting duplicate votes for some users? one guy got 2 votes, another got 6
import aiohttp
auth={'Authorization': dbl_token}
async def post_count(n):
data = {'server_count': n}
session = aiohttp.ClientSession()
await session.post(url, data=data, headers=auth)
await session.close()```
or python with aiohttp.ClientSession() as session: session.post(url, data=data, headers=auth) to make it two lines
@dusty marsh
xd
FIX THE FUCCIN WEBHOOKS LIKE BRUH THEY STOP WORKIn
I mean mine works, but ok
@vivid surge spoonfeed
You also forgot Content-Type header
Also, it's async with for aiohttp
yeah I was just trying to prove a point so I didn't worry about edditing also I didn't see anything about needing content type in the docs I must've missed it
Most of APIs require that 
Pretty much every request system defaults to json tbh
this reminded me of someone from other bot list, a guy answered someone's development question which already got the answer over 4 months ago
xd
mood
how do i figure out the gateway thing
@restive otter this channel is for the DBL api, as the channel topic says
anyone know why my dbl.webhook doesn't work with 'posted' event on 2.3 (node/discord.js)
voting works, but reposting server count doesn't. Do I have to wait for all the shards to finish or something else?
Uh posted isn't related to webhook π€
can someone help me
if i do this:
async with aiohttp.ClientSession() as ss:
async with ss.get(f"https://discordbots.org/api/bots/440176226338865167") as r:
bot = await r.json()
await ctx.send(bot)
it gives back {'error': 'Unauthorized'}
That normally means invalid token
You need an Authorization header
With your dbl token
Your bots*
Your bots dbl token*
Lmao I can type clear messages
oof
Iirc dbl only allows the auth header
@ornate abyss blah.get(url, headers=your_dict)
your_dict will be a dict where key is Authorization and its value is your bot's DBL token

this worked for me :) (posting it for other people on discord.py@rewrite π€· )
token= 'TOKEN HERE'
headers = {"Authorization": token}
async with aiohttp.ClientSession() as session:
async with session.get(f'https://discordbots.org/api/bots/{botid}', headers=headers) as r:
data = await r.json()
It should be something like data instead of bot tbh
oh yea
how can i let my bot send a message when someone votes on my bot?
@ornate abyss O your here as wel
π€
hmm
get_upvote_info right?
So you basically need a webhook running and upon getting a POST request, you would need to send a request to Discord
I actually have the webhook but it's not set up for posting in a channel
so like how it posts the server count?
Not really
Posting the server count is just a HTTP request
Whereas webhook is a server awaiting requests to be sent to it
hmmm
You and with the webhook you can set a message on some event link vote
that triggers when someone votes on your bot
But your using python right
ye
I don't know how it works in python
I should add that into my to-do list for the webhook
Did you look at this @ornate abyss https://github.com/DiscordBotList/DBL-Python-Library
A simple API wrapper for discordbots.org written in Python - DiscordBotList/DBL-Python-Library
I should mention that that library doesn't have any support for webhooks
you but you can get upvote info some maybe you can do something with that?
yea
ik how to get info etc
π
I'll send you the code for webhook later (most likely tomorrow)

It's rather a separate script running in the background than a code for their bot
Spoonfeeding is just straight up giving code
Doesn't dbljs spoonfeed the users with its webhook support at this point?
idk I made my own
Setting up will be the users' problem, mine is to code it and make it work as well as possible
Dblpy is broken and doesn't work well
Exactly
Just use http requests
They want webhooks
For webhooks, run a webserver
hi
how can i make a dbl info command so it get all the info from the id but what if the bot doesnt have the servercount thing setup?
it gives this KeyError: 'server_count'
Instead of doing ['server_count'], you can do .get('server_count') and check if that returns None or handle that error in try-except
And that's becoming more of #development question
Ah yeah
oh so checking if its None?
Sooooo anyone else having votes process multiple times?
Either a bug or weekend votes multiplied
I'd check the logs
Perhaps you had it set on an interval to post the count?
Or an API lag
for .js is there a way to .catch if the login failed? or is it just <DBL>|events#error ?
With that I mean
It canβt restart for no reason only if I do it manually
Which I donβt
I have it set as if the bot is ready
I think
webhook not working?
just receive it, 30 mins delay wow
Im not really sure what to do with the api webhooks, am I supposed to give the link of an existing webhook or is there something else that needs to be setup?
Nvm
url
βIf youβre lost read more about our (link)β
events.js:183
throw er; // Unhandled 'error' event
^
Error: listen EADDRINUSE :::5000
at Server.setupListenHandle [as _listen2] (net.js:1360:14)```
The port is in use
I just put dbl.webhook.on('vote', console.log)
i put the same auth as the api options and put the url of the ported location into the api options and i pressed test it's just not doin a thing. any idea?
Last time I used console.log it was a function 
thats the point?
You need the parentheses
it'll run console.log(theParamPassedThroughListener)
console.log(vote)
no then itll set the returned value of console.log to the event lol
you know the second param is a function that's ran on call?
do u need me to prove u rn?
No
The callback is a function. It will work
That is shorthand for a function
Lmao
You are still passing a function
He isnt
console.log is a function
Then something else is wrong
no shit but its not that part lol
im generally new to this so idek if the test button does the stuff?
It would emit the vote
I use my own lib for this, but if you arent recieving it, the address may be wrong on the dbl side on the site
You have it as http://ip:port/path right?
im using and nginx that passes it through 443 but yea ive tried like every different variation
And your console tells you the server is running?
yea
lmao steven learned something about programming today
Yes
:p
you should
much nicer
I dont just log on my callbacks
.on("something", console.log)
is much better then
.on("something", (thing) => {
console.log(thing)
})```
its good for debug tho
anyways
whenever you would do this, you should use the trick u just learned
doesnt just apply to console.logs
How is it much better if it does the same thing 
so your webhooks arent coming through?
u can also handle it with the same written function wherever and stuff
yea basically i guess
i tried posting manually but there's a cors error but idk if discordbots.org is allowed too or whatever the case is
- cleaner
- you dont need a to declare a new function
But I dont just do one thing in my callbacks either
- less memory lul
If I cared about mem usage why would I use js
Besides this is my vote function .on('vote', (vote) => { try{ var test = bot.playerstorage.get(vote.user) if(!test) return console.log(`${vote.user} voted`) }catch(err){ console.error(err) } if(!vote.isWeekend){ bot.playerstorage.math(vote.user, "add", 1000, "balance") }else{ bot.playerstorage.math(vote.user, "add", 2000, "balance") } return console.log(`User with ID ${vote.user} just voted!`) })
but like what if you have the same callback for two different functions

-bots @hearty lintel
@candid blade
@lament vale
@thorny walrus
@blazing token
oh
It uses your id to test
the system is probably a bit clogged so there's delays
wait now auth isnt working
sksk
ok it works when i have no auth at all
yall should really like console the request response when testing a webhook it'd make thing much easier to debug
no in the browser
Oh
when u press the test button
its supposed to console the error
but here's the thing
it doesnt
You can log auth erros on your side
errors*
I think that's it tho
But maybe a server not found or no response etc would be nice to have
Delays on point
I'm still not having a delay
dbl likes me
It used to do that back when I first set my webhook up
Took me like 2 mins of spamming test button to get it working
well spamming clogs it more
either you didnt save the password
or you're getting old requests in the queue from testing with no auth
Welp, I am sure I saved the password back then
Also, don't worry, no requests are coming
I was talking to jpb
oops
yea it seems all good now
how would i go about attaching the webhook to express or do i just have to write my own post handler? cuz i see option.webhookServer
the docs have an example at the bottom
can somebody help me get my bot to have a WATCHING or PLAYING status? i tried multiple things but, it doesn't work.
so I made my bot using visual studio code, when I invite it to the server, it appears to be offline how do i make it online>
run the code, and #development @short pendant
uhmmm
did the api break?
it cant find my bot > https://discordbots.org/api/bot/440176226338865167 @potent garden
hmm luca still works
nvm
/api/bots
yep.. π€¦
hmmm now this,
KeyError: 'owners'
it cant find the owners
code:
owner=' '.join([str((x)) for x in bot['owners']])
em.add_field(name="Owner(s)",value=f"<@{owner}>")
ye
async with aiohttp.ClientSession() as ss
async with ss.get(f'https://discordbots.org/api/bots/{botid}', headers=headers) as r:
bot = await r.json()
isnt this for the api?
i dont think i did lol
its like that on the site
well nvm
Lol apparently my token was revoked
Can we send non-integer as server count to the API?
I think you can send anything xd
/shrug


Β―_(γ)_/Β―
{'error': 'Invalid value for server_count'}
Well, rip my dreams of putting weird stuff on it
xD
Here goes CSS, ig
@azure pollen β€
#credit
I fixed
Xd
So now i just wait
Why am i so daffed e.e
Ok
Let me check my web
Shall i send u the web link
ok
shall I type in console
pnpm nodebot.js
node bot
Ok
I cant type in console on phone
Wow
Yes
@rapid ledge
Ok
And
Ok
No
Its undefined still
Yes
Cant use rn
Is there a way I can see the coolodown where I can vote again?
it's 12 hours
Don't think so...
only if you save it to a db when they vote and check times
Anyone know a good tutorial for the ping to keep ur bot online on glitch.com ?
is my bots api key on https://discordbots.org/ the token i would insert to see if a user has voted?
yes
how does one authorize their api token?
add it in your Authorization header
@vivid surge what am i supposed to do
this is so that when someone votes for my bot on DBL it will send them a DM
What do you know about http requests and stuff like that?
nvm not that much obviously
yah
ok so I'd reccomend learning about them a little bit
in the http request
ok
You read and comprehend
i have
i just dont know how to use the api token
i get an error saying my api token is invalid
Are you using the one from that page?
you're using djs right?
correct
if you're getting an error then that means you're not using it right
Like you're not using the authorization header right
ok
well thanks for helping, im really tired so im going to sleep and think about it and then get back to it tomorrow
how do i add the api to my bot
i want it to show the members and have vote support so that it sends a message on vote
im using discord.py rewrite
@kind walrus https://discordbots.org/api/docs#pylib
Flask script mainly to handle POST requests from discordbots.org - shivaco/DBL-python-webhook
@sullen nymph im going to steal this i love this
Nah Imma sue you for using my stuff with MIT license
yo so i added the discord server list bot right and it didnt add my server to my profile, any ideas on how to fix this
Other than being in the incorrect place, I believe the bot is offline rn
can someone help me
Hello guys, I got 500 votes in 15 days so I bet next month I will reach 1k votes. I wanna ask something.
How do I use webhooks
@restive otter you need to set up a webserver to receive post requests from DBL
If you use js then dblapi.js can handle it for you
If you use python take a look at https://github.com/shivaco/DBL-python-webhook
Thanks
Yw
delet?
yeah i got it
ah
@sullen nymph you're a legend thanks for the flask thing

-bots 175680857569230848
User not found
Blload#6680's bots:
@restive otter
Uber please not in here
http://prntscr.com/n3ovxz
Help me
server post code
@mighty shuttle can you help me?
ok thnx resolved!
#312614469819826177 its exemples here
is webhook shut down?
my votes dont come
and webhook test
umm
does anyone have the invite 4 sfe?
@restive otter we arent the server to ask for that.. sorry. If an invite is expired then we cant do anything..
Check https://discordbots.org/api/docs and take a look at #312614469819826177
the channel is pretty old but still useful sometimes
i did but when i try it says Ops! Error:401 Unauthorized @tawdry spindle
Can you DM me your code and I'll help you there
ok
Since i set up a domain and HTTPS for my site on my vps, DBL webhooks no longer work.. How can i keep the site running but also the vote webhooks?
Use it through the domain?
500 codes are HTTP server-side codes so I'd assume the same for discord, and if so, it's not your fault and is on their end
ok
yeah, thats when DBL breaks
i get it almost everytime
my error channel for my bot is almost spammed with this error
why is it spamming the dbl api then
what?
like im getting it almost every 3 day's
but my bot is getting no command errors etc
so
ok?
Webhook isnt working correctly. Its Woking 5 days ago but isnt working now
Hey <@&265158261945270273> I dont know if its you, but @hot pebble crash I guess ...
@tacit siren DONT MENTION ADMINS for no reason
this isn't bot support
We can't help with Boxbot
Go to the boxbot server
Ok sorry about this !!
This is discord bot list
Okok sorry :x
Yw
https://i.imgur.com/wJ7Lpaz.png dear dbl staff, you should probably ratelimit the edit submit button
from,
uber
You probably should use Review button 
dear uber, you should probably post in the appropriate place instead of #topgg-api
from,
tonkku
dear @arctic arch ,
where? I thought api had everything to deal with site and api
from yours dearly xoxo hugs and kisses,
uber
Webhooks still wont work :/
dear moosegange,
maybe people want to use incremental development instead of trying to debug however dbl's janky code insertion fucks their shit
from,
cadence
Since i set up a domain and HTTPS for my site on my vps, DBL webhooks no longer work.. How can i keep the site running but also the vote webhooks?
Around 19 people voted but didnt get their rewards!
Now its still not coming through :/
@restive otter check your webhook URL set onyour bot page
do you have an IP there?
I just set up a website on my vps on port 443 and now the webhooks just wont arrive on port 5000 anymore
Yes because it worked since a year till now
The console says running on http://0.0.0.0:5000/dblwebhook
That should say the vps's ip..
Or atleast used to
@fading kraken
:/
0.0.0.0 will be your public IP (IPv4) in the link
If you're using Windows, the port might be closed and that could be the issue
Nope
Its open
No firewalls
I only set up a site with HTTPS & a domain. Until i did that the dbl voting worked fine @sullen nymph

And my vps also says HTTP is disabled but HTTPS is enabled
So i tried using https on dbl
No response either
dear @restive otter,
you have severely misunderstood the purpose of #topgg-api
I recommend you read channel descriptions, #rules-and-info and #502193464054644737 thoroughly before continuing further.
goodbye,
tonkku
tf is happening
dear admins
pls fix the webhooks
from,
Potato man
lots of salt is happening 

@restive otter this channel is only for asking for help with using the api (and complaining when the api breaks)
We don't need you mini-modding. We've already said what we need to say. @plain timber
Excuse me but, why doesn't this work?
async def post_server_count(bot):
dbl_url = f'https://discordbots.org/api/bots/{bot.user.id}/stats'
dbl_headers = {'Authorization' : config.dbl_token()}
dbl_data = {'server_count' : len(bot.guilds)}
requests.post(dbl_url, headers=dbl_headers, data=json.dumps(dbl_data))
Yeah
Wait
I think I still have to use dumps
The json parameter probably expects a json string
It will convert
ok
Yes @restive otter
It works with another site, which means I'm probably not building the request correctly
Tbh use aiohttp, requests fsr doesn't want to work
can someone please help me?
@crisp sentinel it should work! But if it doesnt, let me know
make sure to check the npm readme
I will, thanks π
@formal citrus @That12#2255 Just Tell The question?!
How can one make it so that when a user votes for your bot on DBL, it sends them a DM.
Please make sure that you know what you are talking about since the last person completely wasted my time
The second part of your message is kinda rude, everyone in here is trying their best to help, but here's a simple (and hence not too descriptive) run through of how to do what you want:
Make a webhook handler (a webserver with a specific endpoint that you have control over)
Hook this handler to an event on your bot (either run it on the same program, or have your bot poll a database or something)
Have your bot dm the people who voted (in the bot event handler)
arik btw requests.post is blocking and it'll stop everything on your bot from running
oh wait that was at 3:50am
Lol
So the docs say to not use the /votes endpoint if you have more than 1000 votes so like
Just curious if there's any way for a larger bot to get all of its votes, if it misses one of the webhook calls or loses its local count then is it out of luck?
oh you know what I didn't read 2 lines down at the next endpoint
/check
you can get the amount of votes with the normal bot endpoint
/check is for checking individual users
another thing you can do is make the voting server independent to your bot
hm
Are you running it on your local machine or a vps?
And I'm assuming you set the webhook link on DBL?
?
As in, in a discord channel?
Well that's your problem if that is true
Add the on 'ready' and then put in the webhook link that shows up
Does adding/editing a webhook require reapproval?
No
cool, thanks
I keep getting backend fetched and other errors from the api, any way to check if the api is up before I try to use it?
ok so my server count isn't updating, and for some reason my webhook is firing off a few times on the vote event randomly for a user (maybe once every 6-8 hours?). Using dblapi.js here is my code.
const dbl = new DBL(config.discordBots, {webhookPort: config.dblWebhookPort, webhookAuth: config.dblWebhookPass, webhookPath: "/" }, bot);
dbl.on('posted', (post) => {
console.log('Server count posted!');
});
dbl.webhook.on('ready', hook => {
console.log(`Webhook running at http://${hook.hostname}:${hook.port}${hook.path}`);
});
dbl.on('error', err => {
console.error(err);
});
//check if voted (give points)
dbl.webhook.on('vote', async vote => {
// sometimes triggers 5 times, or 10 times for a user.
});
thinking I may have done something wrong somewhere π€
@quartz heron change 0.0.0.0 to the IP of your vps
I believe it changes that to IPv4 of VPS
Or am I wrong and dbljs doesn't do that?
Wait, I got it wrong ig
Fuck
Use properly formatted code blocks please (add js after the ```, and then a new line)
remove the s from https
unless you actually have a ssl certificate on the webhook
const dbl = new DBL("api token", { webhookPort: 5000, webhookAuth: 'password'});
dbl.webhook.on('vote', vote => {
console.log(`User with ID ${vote.user} just voted!`);
});
dbl.webhook.on('ready', hook => {
console.log(`Webhook running at http://${hook.hostname}:${hook.port}${hook.path}`);
});```
is ok?
has anyone had this problem before? Or know how to help? I feel like I'm making a silly mistake:
https://discordapp.com/channels/264445053596991498/412006692125933568/561638212020469765
@grand salmon what language?
what do you mean?
Im asking how to create webhook
I don't know in what language i need to do it
thats why im asking
JavaScript
that does create the webhook
if you want to create your own using your own code to do something else, set up a server
are webhooks working?
@grand salmon that code does create the webhook...
What file do i put all the API stuff in?
@fleet pebble what... every bot is different, and it depends on what you're doing with the api + your file structure
@fallow grotto what's your code?
tbh mine has been doing that too
must be a silly mistake
it's not updating, it remembers the past value (or a wrong value)
to add guild count to dbl i need to add a background task with dblpy?
Why are webhooks so slow? People aren't gonna bother voting if they get the reward a hour later
Please fix this
Okay I scrolled up and I guess I should have used the thing from the API and not a php page lol
The API thing works instantly
This should be more clear
@jolly pond out of curiosity, what php page?
@bleak coyote just a php page I made on my host for the webhooks
there's a backlog of requests in the webhook
Well that might be why @jolly pond
Anyways it's fine now.
My point is that it should be more clear I should use the dbl npm webhook thing. I didn't know that was a thing until I scrolled up here
thats only for js?
Tho a request is a request, shouldnt be slow even with php
for php you should make it yourself
@bleak coyote Well it is
It gets it like a hour later sometimes
@plain timber Yes I did and it's slow
No
big lul
When I test it it's instant
When I use the webhook test it it takes time
And for real votes too
It's smth with your host or your code, php code doesnt take 1h to make a request lol
^
Okay Idk what was happening. π
the npm module just creates a webserver to listen to the same webhook requests
it should be the same whether u use ur own php or dblapi.js
@stray pendant whats the api response?
aiohttp.client_exceptions.ClientOSError: [Errno 104] Connection reset by peer
dblpy *
so I got this in log when updating guild count
dbl.errors.HTTPException: Backend fetch failed (status code: 503): <!DOCTYPE html>
<html>
<head>
<title>503 Backend fetch failed</title>
</head>
<body>
<h1>Error 503 Backend fetch failed</h1>
<p>Backend fetch failed</p>
<h3>Guru Meditation:</h3>
<p>XID: 382402563</p>
<hr>
<p>Varnish cache server</p>
</body>
</html>
should I worry?
I tried to regenerate my API token but didn't help
What are you trying to do
Update server count on bot
Hopefully you realize that DBL api needs its own token, not your bot token
Yes
using a library? or
dblpy yeah
yeah
raise Forbidden(resp, data)
dbl.errors.Forbidden: Forbidden (status code: 403): {"error":"Forbidden"}
await self.request('POST', '{}/bots/{}/stats'.format(self.BASE, bot_id), json=payload)
that's not
oh is that part of your stacktrace
you should be seeing Failed to post server count\n{}: {}
something along those lines
class DBots(commands.Cog):
"""Handles interactions with the discordbots.org API"""
def __init__(self, bot):
self.bot = bot
self.token = 'tokenherebutremovedforcopypaste'
self.dblpy = dbl.Client(self.bot, self.token)
self.bot.loop.create_task(self.update_stats())
async def update_stats(self):
"""This function runs every 30 minutes to automatically update your server count"""
while True:
log.info('attempting to post server count')
try:
await self.dblpy.post_server_count()
log.info('posted server count ({})'.format(len(self.bot.guilds)))
except Exception as e:
log.exception('Failed to post server count\n{}: {}'.format(type(e).__name__, e))
await asyncio.sleep(1800)
Yeah I see that
dbl.errors.Forbidden: Forbidden (status code: 403): {"error":"Forbidden"}
Failed to post server count
hmph
And the key here https://discordbots.org/api/docs#mybots
i cant think of any reason other than your token's wrong
I tried to regenerate it 3 times
you need to copy the whole thing, it's longer than the page
you should have a string that's quite long
yeah
has 3 segments, separated by .
Yeah I see the three .

Yeah idk
maybe @craggy sentinel can help 
(He's saying that he's getting 403 on vote api with a seemingly valid token using dblpy, his bot is posted there and i couldnt find anything wrong)
It's been a while since I've used the API
As rewrite released which was the new d.py library and I haven't tried it out with this one
looks like you copied the example code which should work
The example code works with rewrite and async alike
I could check my old code
but it's pretty much the example one as well
Is there a way to check if my token is valid?
I guess I could try it without the bot
You could try sending other API requests with it
gonna try with postman
oh god I feel so dumb
I used a test bot to try it out with the wrong ID, so sorry π

I assume i get my api token when my bot is approved?
Yep
How do I send a message to the vote.user? Javascript
So this is API help channel?
get user -> make sure they exist to your bot -> send message @restive otter
@short glade yes
Well this is an API help channel π
This isnt the discord api channel
Then specify that somewhere
It does
where?
In the topic
wait
client.users.fetchUser(vote.user).send("thanks for voting!")
You can go there
this?
That can work, but I think fetchUser is a promise iirc, you should also add a catch
.catch(error) { console.log(error) }?
I believe so
Why not just make a error event? π
Then you don't need to catch error all the time
nice token leak 
const dbl = new DBL(config.apiToken, client);
// Optional events
dbl.on('posted', () => {
console.log('Server count posted!');
})
dbl.on('error', e => {
console.log(`Oops! ${e}`);
})```
This doesn't work? This is in my ready event, using `discord.js`.
https://discordbots.org/api/docs#jslib
@ me with answer
Is there a way to make it so if someone clicks the vote button on the dbl website a message gets sent to a channel saying: (user) has just upvoted Cryptonox! My Bot is running on Discord.js
set up a webhook
Ok
not the channel to ask that
^
TypeError: Cannot read property 'on' of undefined
at Object.<anonymous> (D:\omnia-bot\omnia\bot.js:262:13)
at Module._compile (internal/modules/cjs/loader.js:738:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:749:10)
at Module.load (internal/modules/cjs/loader.js:630:32)
at tryModuleLoad (internal/modules/cjs/loader.js:570:12)
at Function.Module._load (internal/modules/cjs/loader.js:562:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:801:12)
at internal/main/run_main_module.js:21:11
(node:15720) UnhandledPromiseRejectionWarning: Error: Shard 0's process exited before its Client became ready.
at Shard.once (D:\omnia-bot\omnia\node_modules\discord.js\src\sharding\Shard.js:88:39)
at Object.onceWrapper (events.js:285:13)
at Shard.emit (events.js:197:13)
at Shard._handleExit (D:\omnia-bot\omnia\node_modules\discord.js\src\sharding\Shard.js:272:10)
at ChildProcess.emit (events.js:197:13)
at Process.ChildProcess._handle.onexit (internal/child_process.js:254:12)
(node:15720) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 12)```Code```dbl.webhook.on('vote', vote => {
client.vote.inc(vote.user, 'votes')
client.guilds.get('554742955898961930').channel.find(c => c.name === 'votes' && c.type === 'text')
console.log(`User with ID ${vote.user} just voted!`);
});```
@ me with answer
@short girder what's the .webhook for?
idk? I'm trying to add 1 in my db to that user every vote. So that when they do o!claim. I get the amount of votes with the amount I save in my db. But idk how to work this. First time with this api before.
try it without the .webhook
sure
Oops! Error: 522 Origin Connection Time-out Gives this after a while and never posts the server and shard count. Plus the websitr is giving me a 503 error
Oh ok
Ok now no errors web fixed. No errors now, so I don't need the webhook part right? @restive otter
yea
Ok. So it should work each time someone votes?
@restive otter no that's wrong
@short girder you need dbl.webhook.on, the error is because you didn't include the webhook settings in the new dbl line
Ok let me look api
@plain timber, I see the api, but don't know how to implement it. How?
Have you seen the docs
It has a webhook example
Would I need to run that separate from my bot or no?
In the new dbl line you didn't put the webhook settings
No
You just need to fix your code...
const dbl new DBL(config.apiToken, {webhookAuth: 'password', webhook: server }, client});
@plain timber
Like this?
Sorry I'm new to webhooks. Haven't used them yet.
I did
const dbl = new DBL(config.apiToken, { webhookPort: 5000, webhookAuth: 'password' }, client);
dbl.webhook.on('ready', hook => {
console.log(`Webhook running at http://${hook.hostname}:${hook.port}${hook.path}`);
});
dbl.webhook.on('vote', vote => {
console.log(`User with ID ${vote.user} just voted!`);
});```
Like this?
@plain timber
Sorry for pinging
Yeah
How does one get their server count to display on their bots page on DBL?
You have to post your server stats via our API @fleet pebble
cool beans
If only you viewed the channel topic
Hello guys !
My bot is written in Python3.7, and i'm using webhook to get the voters ID and give them some rewards.
But sometimes, DBL sends something wrong to me and it's throwing me this error :
Expecting value: line 1 column 1 (char 0)
INFO:aiohttp.access:::1 [29/Mar/2019:19:30:47 +0000] "GET /dblwebhook HTTP/1.1" 200 160 "-" "-"
ERROR:aiohttp.server:Unhandled exception
Traceback (most recent call last):
File "/usr/local/opt/python-3.7.0/lib/python3.7/site-packages/aiohttp/web_protocol.py", line 447, in start
await resp.prepare(request)
File "/usr/local/opt/python-3.7.0/lib/python3.7/site-packages/aiohttp/web_response.py", line 353, in prepare
return await self._start(request)
File "/usr/local/opt/python-3.7.0/lib/python3.7/site-packages/aiohttp/web_response.py", line 667, in _start
return await super()._start(request)
File "/usr/local/opt/python-3.7.0/lib/python3.7/site-packages/aiohttp/web_response.py", line 410, in _start
await writer.write_headers(status_line, headers)
File "/usr/local/opt/python-3.7.0/lib/python3.7/site-packages/aiohttp/http_writer.py", line 112, in write_headers
self._write(buf)
File "/usr/local/opt/python-3.7.0/lib/python3.7/site-packages/aiohttp/http_writer.py", line 67, in _write
raise ConnectionResetError('Cannot write to closing transport')
ConnectionResetError: Cannot write to closing transport```
As you can see i'm using aiohttp and this line is kinda strange :
INFO:aiohttp.access:::1 [29/Mar/2019:19:30:47 +0000] "GET /dblwebhook HTTP/1.1" 200 160 "-" "-"```
Usually the line above looks like this : `INFO:aiohttp.access:::1 [29/Mar/2019:19:30:47 +0000] "POST/dblwebhook HTTP/1.1" 200 160 "-" "DBL"`
And this exception makes my bot crash.
I'm listening for **POST** requests as this line shows up :
```python
app = web.Application()
app.add_routes([web.get('/', hello), web.get('/dblwebhook', Get_Voter), web.post('/dblwebhook', Get_Voter)])```
Do you guys have an idea on what the problem is ?
Thank you.
uhhhhhh, afaik the dbl api never GET requests
maybe you have something else GETting?
if its a public ip address (on port 80) there can be chinese web scanners that want your data
(also if you noticed, the DBL POST request has "DBL", but the GET request doesn't)
Thank you for your answer, i've changed the routes to app.add_routes([web.get('/', hello), web.post('/dblwebhook', Get_Voter)]) (I removed the web.get('/dblwebhook', Get_Voter))
For the moment it seems to work
The port i've chosen is the number 8000, which port should i use to avoid intrusions ?
1-1023 are a no-no
Me and a friend have a bot in discord.js, and we are trying to post our server count to the bot list. We are doing everything correctly and no errors are posting in console, but the server count isn't posting.
Thanks for showing the code so we can see what's going wrong π
const Discord = require("discord.js");
const bot = new Discord.Client();
const DBL = require("dblapi.js");
const dbl = new DBL('config.dblkey', bot);
bot.on('ready', () => {
setInterval(() => {
dbl.postStats(bot.guilds.size);
}, 300000);
});
well, when you provide a client, it auto posts
but idk why it wouldnt be posting
and dbl.postStats takes a client
it posts after 30 minutes iirc
not a number


