def wiki_func(paras, infos): """中文维基百科查询""" wikipedia.set_lang("zh") candidates = wikipedia.search(paras) if len(candidates) <= 0: return { 'text': 'not found', } else: summary = None for keyword in candidates: try: summary = wikipedia.summary(keyword, sentences=1) break except Exception: # 可能发生歧义异常,见 wikipedia 文档 continue if summary: answer = decode_to_unicode(summary) + \ u'\n候选关键词: %s' % u', '.join(candidates) return { 'text': answer, } else: return { 'text': 'not found', }
def help(self, paras, infos): """输出使用帮助""" result = "" _ = paras _ = infos # 遍历已注册组件 for name, func in self._comps.iteritems(): description = func.__doc__ if func.__doc__ else "no description" description = decode_to_unicode(description) if len(name) > 0: result += "+ %s: %s\n" % (name, description) if self._default_cmd: result += decode_to_unicode('不指定命令时,使用 "%s" 命令\n' % self._default_cmd) return {"text": result}
def __init__(self, trigger_word, controller): """初始化操作 :type trigger_word: str :param trigger_word: 在 BearyChat 的机器人管理页面中为 Outgoing 机器人设置的触发词 :type controller: Controller :param controller: Outgoing 机器人的中心控制模块,包含了预处理、 命令响应和后处理三个模块 """ self._trigger_word = decode_to_unicode(trigger_word) self._config = {} self.read_config() self._controller = controller self._app = Flask(__name__.split('.')[0]) self._app.config.update(DEBUG=True) self._app.add_url_rule('/', view_func=self.proc, methods=['POST'])
def dict_func(paras, info): """有道词典查询""" key = info.get('youdao_api_key') key_from = info.get('youdao_key_from') if not key or not key_from: return { 'text': 'robot component error(invalid api key)', } data = {} data['key'] = key data['keyfrom'] = key_from data['type'] = 'data' data['version'] = '1.1' data['doctype'] = 'json' data['q'] = decode_to_unicode(paras) r = requests.get('http://fanyi.youdao.com/openapi.do', params=data) req = None try: req = json.loads(r.text) except Exception: return { 'text': 'unknown error', } err_dict = { 20: u'要翻译的文本过长', 30: u'无法进行有效的翻译', 40: u'不支持的语言类型', 50: u'无效的key', 60: u'无词典结果', } err_code = req.get(u'errorCode', 60) if err_code in err_dict: return { 'text': err_dict.get(err_code), } return { 'text': explain_dict_res(req), }
def image_search(paras, infos): """使用 Google API 搜索图片""" _ = infos _api_url = 'http://ajax.googleapis.com/ajax/services/search/images' params = { 'v': '1.0', 'rsz': '8', 'q': decode_to_unicode(paras), 'start': str(int(random.random() * 10)) } try: resp = requests.get(_api_url, params=params) data = resp.json() img_url = data[u'responseData'][u'results'][0]['unescapedUrl'] return { 'attachments': [{'images': [{'url': img_url},]},] } except Exception: return { 'text': 'not found' }