Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add asynchronus feature #28

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 40 additions & 18 deletions pyslack/__init__.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,28 @@
import datetime
import logging
import requests
import unirest


class SlackError(Exception):
pass


class SlackClient(object):

BASE_URL = 'https://slack.com/api'

def __init__(self, token, verify=False):
def __init__(self, token, verify=False, async=False, callback=None):
"""
:param token:
:param verify:
:param async:
:param callback: function call_back(response): # do whatever you want with response
:return:
"""
self.token = token
self.verify = verify
self.async = async
self.callback = callback or self._response_handler
self.blocked_until = None
self.channel_name_id_map = {}

Expand All @@ -27,26 +36,17 @@ def _make_request(self, method, params):
http://requests.readthedocs.org/en/latest/user/advanced/#ssl-cert-verification
"""
if self.blocked_until is not None and \
datetime.datetime.utcnow() < self.blocked_until:
datetime.datetime.utcnow() < self.blocked_until:
raise SlackError("Too many requests - wait until {0}" \
.format(self.blocked_until))
.format(self.blocked_until))

url = "%s/%s" % (SlackClient.BASE_URL, method)
params['token'] = self.token
response = requests.post(url, data=params, verify=self.verify)

if response.status_code == 429:
# Too many requests
retry_after = int(response.headers.get('retry-after', '1'))
self.blocked_until = datetime.datetime.utcnow() + \
datetime.timedelta(seconds=retry_after)
raise SlackError("Too many requests - retry after {0} second(s)" \
.format(retry_after))

result = response.json()
if not result['ok']:
raise SlackError(result['error'])
return result
if self.async:
unirest.post(url, params=params, callback=self.callback)
else:
response = requests.post(url, data=params, verify=self.verify)
return self.response_handler(response)

def channels_list(self, exclude_archived=True, **params):
"""channels.list
Expand Down Expand Up @@ -108,13 +108,35 @@ def chat_update_message(self, channel, text, timestamp, **params):
})
return self._make_request(method, params)

def _response_handler(self, response):
"""
This method handle response
:param response: response object
:return:
"""
code = response.code if self.async else response.status_code # The HTTP status code
result = response.body if self.async else response.json() # The parsed response

if code == 429:
# Too many requests
retry_after = int(response.headers.get('retry-after', '1'))
self.blocked_until = datetime.datetime.utcnow() + \
datetime.timedelta(seconds=retry_after)
raise SlackError("Too many requests - retry after {0} second(s)" \
.format(retry_after))

if not result['ok']:
raise SlackError(result['error'])
return result


class SlackHandler(logging.Handler):
"""A logging handler that posts messages to a Slack channel!

References:
http://docs.python.org/2/library/logging.html#handler-objects
"""

def __init__(self, token, channel, verify=False, **kwargs):
super(SlackHandler, self).__init__()
self.client = SlackClient(token, verify)
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
author="@LoisaidaSam",
author_email="sam.sandberg@gmail.com",
description="A Python wrapper for Slack's API",
install_requires=["requests"],
install_requires=["requests", "unirest"],
keywords="slack api wrapper",
license="MIT",
name="pyslack-real",
Expand Down