Skip to content

Commit 8cfcc2c

Browse files
author
shivaco
committed
Added webhook and more
* Added webhook * Removed support for discord.py versions lower than 1.0.0 * Made get_weekend_status return a boolean value * Added webhook example in README * Removed post_server_count and get_server_count
1 parent c1461ae commit 8cfcc2c

5 files changed

Lines changed: 99 additions & 24 deletions

File tree

README.rst

Lines changed: 43 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -47,16 +47,15 @@ Not Working / Implemented
4747

4848
* Searching for bots via the api
4949

50-
Example
51-
-------
50+
Examples
51+
--------
5252

5353
.. code:: py
5454
5555
import dbl
5656
import discord
5757
from discord.ext import commands
5858
59-
import aiohttp
6059
import asyncio
6160
import logging
6261
@@ -66,13 +65,13 @@ Example
6665
6766
def __init__(self, bot):
6867
self.bot = bot
69-
self.token = 'dbl_token' # set this to your DBL token
68+
self.token = 'dbl_token' # set this to your DBL token
7069
self.dblpy = dbl.Client(self.bot, self.token)
7170
self.updating = self.bot.loop.create_task(self.update_stats())
7271
7372
async def update_stats(self):
7473
"""This function runs every 30 minutes to automatically update your server count"""
75-
await self.bot.wait_until_ready()
74+
await self.bot.wait_until_ready() # this is important, do not touch it
7675
while self.bot.is_ready():
7776
logger.info('Attempting to post server count')
7877
try:
@@ -87,6 +86,45 @@ Example
8786
logger = logging.getLogger('bot')
8887
bot.add_cog(DiscordBotsOrgAPI(bot))
8988
89+
.. code_webhooks:: py
90+
91+
import dbl
92+
import discord
93+
from discord.ext import commands
94+
95+
import asyncio
96+
import logging
97+
98+
99+
class DiscordBotsOrgAPI(commands.Cog):
100+
"""Handles interactions with the discordbots.org API"""
101+
102+
def __init__(self, bot):
103+
self.bot = bot
104+
self.token = 'dbl_token' # set this to your DBL token
105+
self.dblpy = dbl.Client(self.bot, self.token, webhook_path='/dblwebhook', webhook_auth='password', webhook_port=5000)
106+
self.updating = self.bot.loop.create_task(self.update_stats())
107+
108+
async def update_stats(self):
109+
"""This function runs every 30 minutes to automatically update your server count"""
110+
await self.bot.wait_until_ready() # this is important, do not touch it
111+
while self.bot.is_ready():
112+
logger.info('Attempting to post server count')
113+
try:
114+
await self.dblpy.post_guild_count()
115+
logger.info('Posted server count ({})'.format(self.dblpy.guild_count()))
116+
except Exception as e:
117+
logger.exception('Failed to post server count\n{}: {}'.format(type(e).__name__, e))
118+
await asyncio.sleep(1800)
119+
120+
@commands.Cog.listener()
121+
async def on_dbl_vote(self, data):
122+
print(data)
123+
124+
def setup(bot):
125+
global logger
126+
logger = logging.getLogger('bot')
127+
bot.add_cog(DiscordBotsOrgAPI(bot))
90128

91129
.. _discordbots.org: https://discordbots.org/
92130
.. _discordbots.org/api/docs: https://discordbots.org/api/docs

dbl/__init__.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
__author__ = 'Francis Taylor'
1313
__license__ = 'MIT'
1414
__copyright__ = 'Copyright 2019 Francis Taylor'
15-
__version__ = '0.2'
15+
__version__ = '0.2.1'
1616

1717
from collections import namedtuple
1818

@@ -22,4 +22,4 @@
2222

2323
VersionInfo = namedtuple('VersionInfo', 'major minor micro releaselevel serial')
2424

25-
version_info = VersionInfo(major=0, minor=2, micro=0, releaselevel='final', serial=0)
25+
version_info = VersionInfo(major=0, minor=2, micro=1, releaselevel='final', serial=0)

dbl/client.py

Lines changed: 37 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -24,14 +24,10 @@
2424
DEALINGS IN THE SOFTWARE.
2525
"""
2626

27-
import asyncio
28-
#import string
29-
#import random
3027
import logging
28+
from aiohttp import web
3129

32-
from . import __version__ as library_version
3330
from .http import HTTPClient
34-
#from .errors import InvalidArgument
3531

3632
log = logging.getLogger(__name__)
3733

@@ -56,29 +52,34 @@ class Client:
5652
Defaults to ``bot.loop``.
5753
**session : Optional
5854
The aiohttp session to use for requests to the API.
55+
**webhook_auth: Optional
56+
The string for Authorization you set on the site for verification.
57+
**webhook_path: Optional
58+
The path for the webhook request.
59+
**webhook_port: Optional
60+
The port to run the webhook on. Will activate webhook when set.
5961
"""
6062

6163
def __init__(self, bot, token, **kwargs):
6264
self.bot = bot
6365
self.bot_id = None
6466
self.loop = kwargs.get('loop') or bot.loop
67+
self.webhook_port = kwargs.get('webhook_port')
68+
self.webhook_auth = kwargs.get('webhook_auth') or ''
69+
self.webhook_path = kwargs.get('webhook_path') or '/dblwebhook'
6570
self.http = HTTPClient(token, loop=self.loop, session=kwargs.get('session'))
6671
self._is_closed = False
67-
self.loop.create_task(self.__ainit__())
68-
69-
self.get_server_count = self.get_guild_count
70-
self.post_server_count = self.post_guild_count
72+
self.task1 = self.loop.create_task(self.__ainit__())
73+
if self.webhook_port:
74+
self.task2 = self.loop.create_task(self.webhook())
7175

7276
async def __ainit__(self):
7377
await self.bot.wait_until_ready()
7478
self.bot_id = self.bot.user.id
7579

7680
def guild_count(self):
7781
"""Gets the guild count from the Client/Bot object"""
78-
try:
79-
return len(self.bot.guilds)
80-
except AttributeError:
81-
return len(self.bot.servers)
82+
return len(self.bot.guilds)
8283

8384
async def get_weekend_status(self):
8485
"""This function is a coroutine.
@@ -91,7 +92,8 @@ async def get_weekend_status(self):
9192
weekend status: bool
9293
The boolean value of weekend status.
9394
"""
94-
return await self.http.get_weekend_status()
95+
data = await self.http.get_weekend_status()
96+
return data['is_weekend']
9597

9698
async def post_guild_count(
9799
self,
@@ -348,12 +350,32 @@ async def get_widget_small(self, bot_id: int = None):
348350
url = 'https://discordbots.org/api/widget/lib/{0}.png'.format(bot_id)
349351
return url
350352

353+
async def webhook(self):
354+
async def vote_handler(request):
355+
req_auth = request.headers.get('Authorization')
356+
if self.webhook_auth == req_auth:
357+
data = await request.json()
358+
self.bot.dispatch('dbl_vote', data)
359+
return web.Response()
360+
else:
361+
return web.Response(status=401)
362+
363+
app = web.Application(loop=self.loop)
364+
app.router.add_post(self.webhook_path, vote_handler)
365+
runner = web.AppRunner(app)
366+
await runner.setup()
367+
self._webserver = web.TCPSite(runner, '0.0.0.0', self.webhook_port)
368+
await self._webserver.start()
369+
351370
async def close(self):
352371
"""This function is a coroutine.
353372
354373
Closes all connections."""
355374
if self._is_closed:
356375
return
357376
else:
377+
await self._webserver.stop()
358378
await self.http.close()
359-
self._is_closed = True
379+
self.task1.cancel()
380+
self.task2.cancel()
381+
self._is_closed = True

docs/api.rst

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,12 @@ Client
3030

3131
All of the following functions return their data as a JSON object (except widget generation)!
3232

33+
.. warning::
34+
35+
`bot.wait_until_ready`_ method must be called before using this library!
36+
37+
.. _bot.wait_until_ready: https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.wait_until_ready
38+
3339
.. autoclass:: Client
3440
:members:
3541

docs/whats_new.rst

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,20 @@ What's New
88
This page keeps a detailed human friendly rendering of what's new and changed
99
in specific versions.
1010

11-
.. _vp0p2p0:
11+
.. _vp0p2p1:
1212

13-
v0.2
13+
v0.2.1
1414
------
1515

16+
* Added webhook
17+
* Removed support for discord.py versions lower than 1.0.0
18+
* Made `get_weekend_status`_ return a boolean value
19+
* Added webhook example in README
20+
* Removed ``post_server_count`` and ``get_server_count``
21+
22+
v0.2
23+
----
24+
1625
* Added ``post_guild_count``
1726
* Made ``post_server_count`` an alias for ``post_guild_count``
1827
* Added ``get_guild_count``

0 commit comments

Comments
 (0)