Exemplo n.º 1
0
class TencentAIBase(object):
    def __init__(self, appid, appsec):
        self.appid = appid
        self.appsec = appsec
        self.http_client = HttpClient()
        self.base_url = 'https://api.ai.qq.com/fcgi-bin'

    def get_sign(self, data):
        data['app_id'] = self.appid
        data['time_stamp'] = int(time.time())
        data['nonce_str'] = random_str(16)
        sorted_list = sorted(data.keys())
        sign_str = u''
        for param in sorted_list:
            sign_str += u'{}={}&'.format(param, quote(str(data[param])))
        sign_str += u'app_key={}'.format(self.appsec)
        return hashlib.md5(sign_str.encode('utf-8')).hexdigest().upper()

    def do_get(self, url, data):
        sign = self.get_sign(data)
        data['sign'] = sign
        url = self.base_url + url
        return self.http_client.get(url, params=data)

    def do_post(self, url, data):
        sign = self.get_sign(data)
        data['sign'] = sign
        url = self.base_url + url
        return self.http_client.post(url, data=data, data_fromat='str')
Exemplo n.º 2
0
class HeFengWeather(object):

    API_BASE = 'https://free-api.heweather.net/s6'

    def __init__(self, user_name, api_key):
        self.user_name = user_name
        self.api_key = api_key
        self.client = HttpClient()

    @sign_wrapper
    @convert_res
    def get(self, url, **kwargs):
        kwargs['verify'] = False
        return self.client.get(url, **kwargs)

    @sign_wrapper
    @convert_res
    def post(self, url, **kwargs):
        kwargs['verify'] = False
        return self.client.post(url, **kwargs)

    def forecast_weather(self, city):
        url_path = '/weather/forecast'
        data = {'location': city}
        return self.get(url_path, params=data)
Exemplo n.º 3
0
def check_img_risk(image_path):
    client = WechatClient(XCX_APPID, XCX_APPSEC, session=data_cache)
    url = 'https://api.weixin.qq.com/wxa/img_sec_check?'\
        'access_token={}'.format(client.access_token)
    media = {'media': open(image_path, 'rb')}
    _http = HttpClient()
    res = _http.post(url, files=media)
    return res
Exemplo n.º 4
0
class TuringClient(object):

    API_KEY = ['14c218cb6cb23bb27b7dc89e18eb9689']
    _HTTP_CLIENT = None
    URL = 'http://openapi.tuling123.com/openapi/api/v2'
    DEFAULT_UID = '14c218cb6cb23bb27b7dc89e18eb9689'

    def __init__(self):
        self._HTTP_CLIENT = HttpClient()
        self.DEFAULT_REPLY = u"我还不太懂呢,我去学习啦:)"

    def _handle_result(self, resp):
        intent = resp.get("intent")
        if not intent:
            return self.DEFAULT_REPLY
        resp_code = intent.get("code")
        if resp_code in (5000, 6000):
            return self.DEFAULT_REPLY
        elif int(resp_code) / 1000 == 4:
            print("error resp: %s", resp)
            return self.DEFAULT_REPLY
        results = resp.get("results", [])
        return_msg = []
        for result in results:
            result_type = result.get('resultType', 'text')
            if result_type == 'text':
                return_msg.insert(0, result['values']['text'])
            elif result_type == 'url':
                return_msg.append(result['values']['url'])
            elif result_type == 'news':
                newses = result['values']['news']
                for news in newses:
                    detail_url = news['detailurl']
                    info = news['info']
                    tmp = info + '\n' + detail_url + '\n'
                    return_msg.append(tmp)
        return '\n'.join(return_msg)

    def query_text(self, content, uid=None, location=None):
        '''
        @parameter
        : param uid  --- userid
        : param location --- user location;{'city': '北京', 'province':'北京',
        'street': ''}
        '''
        if isinstance(content, unicode):
            content = content.encode("utf-8")
        req_data = {"reqType": 0}
        req_data['perception'] = {"inputText": {'text': content}}
        if location:
            req_data['perception'].update({'selfInfo': {'location': location}})
        req_data['userInfo'] = {
            'apiKey': random.choice(self.API_KEY),
            'userId': uid if uid else self.DEFAULT_UID
        }
        resp = self._HTTP_CLIENT.post(self.URL, json=req_data)
        LOGGER.info("turling query: %s, res: %s", content, resp)
        return self._handle_result(resp)
Exemplo n.º 5
0
def check_msg_risk(content):
    client = WechatClient(XCX_APPID, XCX_APPSEC, session=data_cache)
    url = 'https://api.weixin.qq.com/wxa/msg_sec_check?'\
        'access_token={}'.format(client.access_token)
    _http = HttpClient()
    if isinstance(content, unicode):
        content = content.encode("utf-8")
    data = {'content': content}
    data = json.dumps(data, ensure_ascii=False)
    res = _http.post(url, data=data)
    return res
Exemplo n.º 6
0
class BaiduAIBase(object):
    def __init__(self, appid, appsec):
        self.appid = appid
        self.appsec = appsec
        self.http_client = HttpClient()
        self.base_url = 'http://tsn.baidu.com'

    @property
    def token_key(self):
        return 'bdtoken_{}'.format(self.appid)

    def refresh_new_token(self):
        token_url = 'https://openapi.baidu.com/oauth/2.0/token'
        params = {
            'grant_type': 'client_credentials',
            'client_id': self.appid,
            'client_secret': self.appsec
        }
        res = self.do_get(token_url, params)
        if 'error' in res:
            raise Exception('get token {} error {}'.format(
                token_url, res.get('error_description', '')))
        token = res['access_token']
        expire = res.get('expires_in', 3600)
        wx_cache.set(self.token_key, token)
        wx_cache.expire(self.token_key, int(expire))
        return token

    @property
    def access_token(self):
        token = wx_cache.get(self.token_key)
        if token:
            return token
        return self.refresh_new_token()

    def do_get(self, url, data):
        if not url.startswith(('http', 'https')):
            url = self.base_url + url
        return self.http_client.get(url, params=data)

    def do_post(self, url, data):
        if not url.startswith(('http', 'https')):
            url = self.base_url + url
        return self.http_client.post(url, data=data, data_fromat='str')