<commit_before>"""
   Wrapper for the Slack API.  Based on the Python Zendesk library by <NAME> <<EMAIL>>.
"""


import httplib2
import re
import urllib
try:
    import simplejson as json
except:
    import json
from endpoints_v1 import mapping_table as mapping_table_v1
from httplib import responses


SLACK_BASE_URL = 'https://slack.com'
DEFAULT_HTTP_METHOD = 'POST'
DEFAULT_HTTP_STATUS_CODE = 200
DEFAULT_CONTENT_TYPE = 'application/x-www-form-urlencoded'


class SlackError(Exception):
    def __init__(self, msg, error_code=None):
        self.msg = msg
        self.error_code = error_code

    def __str__(self):
        return repr('%s: %s' % (self.error_code, self.msg))


def clean_kwargs(kwargs):
    for key, value in kwargs.iteritems():
        if hasattr(value, '__iter__'):
            kwargs[key] = ','.join(map(str, value))


class Slack(object):

    def __init__(self, token=None, api_version=1, client_args={}):
        self.token = token
        if api_version == 1:
            self.mapping_table = mapping_table_v1
        else:
            raise ValueError("Unsupported Slack API Version: %d" %
                    api_version)
        self.client = httplib2.Http(**client_args)

    def __getattr__(self, api_call):
        def call(self, **kwargs):
            api_map = self.mapping_table[api_call]
            path = self.mapping_table.get('path_prefix','') + api_map.get('path','')
            method = api_map.get('method', DEFAULT_HTTP_METHOD)
            status = api_map.get('status', DEFAULT_HTTP_STATUS_CODE)
            valid_params = api_map.get('valid_params', [])
            body = kwargs.pop('data', None)
            url = re.sub(
                    '\{\{(?P<m>[a-zA-Z_]+)\}\}',
                    lambda m: "%s" % urllib.quote(str(kwargs.pop(m.group(1),''))),
                    SLACK_BASE_URL + path
            )
            clean_kwargs(kwargs)
            for kw in kwargs:
                if kw not in valid_params:
                    raise TypeError("%s() got an unexpected keyword argument "
                            "'%s'" % (api_call, kw))
            url += '?' + urllib.urlencode(kwargs)
            return self._make_request(method, url, body, status)
        return call.__get__(self)

    def _make_request(self, method, url, body, status):
        headers = {}
        if method not in ('GET','DELETE') and body is None:
            body = {}
        if body:
            content_type = self.mapping_table.get('content_type', DEFAULT_CONTENT_TYPE)
            headers["Content-Type"] = content_type
            if isinstance(body, dict):
                body['token'] = self.token
                if content_type == 'application/x-www-form-urlencoded':
                    body = urllib.urlencode(body)
                elif content_type == 'application/json':<commit_msg>Fix a parameter encoding issue for empty parameter values.<commit_after>"""
   Wrapper for the Slack API.  Based on the Python Zendesk library by <NAME> <<EMAIL>>.
"""


import httplib2
import re
import urllib
try:
    import simplejson as json
except:
    import json
from endpoints_v1 import mapping_table as mapping_table_v1
from httplib import responses


SLACK_BASE_URL = 'https://slack.com'
DEFAULT_HTTP_METHOD = 'POST'
DEFAULT_HTTP_STATUS_CODE = 200
DEFAULT_CONTENT_TYPE = 'application/x-www-form-urlencoded'


class SlackError(Exception):
    def __init__(self, msg, error_code=None):
        self.msg = msg
        self.error_code = error_code

    def __str__(self):
        return repr('%s: %s' % (self.error_code, self.msg))


def clean_kwargs(kwargs):
    for key, value in kwargs.iteritems():
        if hasattr(value, '__iter__'):
            kwargs[key] = ','.join(map(str, value))


def urlencode(d):
    encoded = {}
    # TODO Handle mutiple parameters with the same name
    for k,v in d.iteritems():
        k = k.encode('utf-8')
        if v is None:
            v = ''
        elif isinstance(v,basestring):
            v = v.encode('utf-8')
        else:
            v = json.dumps(v)
        encoded[k] = v
    return urllib.urlencode(encoded)


class Slack(object):

    def __init__(self, token=None, api_version=1, client_args={}):
        self.token = token
        if api_version == 1:
            self.mapping_table = mapping_table_v1
        else:
            raise ValueError("Unsupported Slack API Version: %d" %
                    api_version)
        self.client = httplib2.Http(**client_args)

    def __getattr__(self, api_call):
        def call(self, **kwargs):
            api_map = self.mapping_table[api_call]
            path = self.mapping_table.get('path_prefix','') + api_map.get('path','')
            method = api_map.get('method', DEFAULT_HTTP_METHOD)
            status = api_map.get('status', DEFAULT_HTTP_STATUS_CODE)
            valid_params = api_map.get('valid_params', [])
            body = kwargs.pop('data', None)
            url = re.sub(
                    '\{\{(?P<m>[a-zA-Z_]+)\}\}',
                    lambda m: "%s" % urllib.quote(str(kwargs.pop(m.group(1),''))),
                    SLACK_BASE_URL + path
            )
            #clean_kwargs(kwargs)
            for kw in kwargs:
                if kw not in valid_params:
                    raise TypeError("%s() got an unexpected keyword argument "
                            "'%s'" % (api_call, kw))
            url += '?' + urlencode(kwargs)
            return self._make_request(method, url, body, status)
        return call.__get__(self)

    def _make_request(self, method, url, body, status):
        headers = {}
        if method not in ('GET','DELETE') and body is None:
            body = {}
        if body:
            content_type = self.mapping_table.get('content_type', DEFAULT_CONTENT_TYPE)
            headers["Content-Type"] = content_type
            if isinstance(body, dict):
                body['token'] = self.token
                if content_type == 'application/x-www-form-urlencoded':
                    body = urlencode(body)
                elif content_type == 'application/json':
{'fraction_non_alphanumeric': 0.11934156378600823, 'fraction_numerical': 0.003950617283950617, 'mean_word_length': 2.172845953002611, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 11, 'https://': 2, 'lorem ipsum': 0, 'www.': 4, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3340730', 'n_tokens_mistral': 1844, 'n_tokens_neox': 1794, 'n_words': 436}