1 Star 0 Fork 0

AlimTech/wukong-contrib

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
YouDaoFanYi.py 2.47 KB
一键复制 编辑 原始数据 按行查看 历史
1509098778 提交于 2019-02-24 11:54 . Merge branch 'master' into master
# -*- coding: utf-8
# 有道翻译插件
import json
import re
import requests
import hashlib
import random
from robot import config, logging
from robot.sdk.AbstractPlugin import AbstractPlugin
logger = logging.getLogger(__name__)
class Plugin(AbstractPlugin):
SLUG = "youdao"
def translate(self, appId, appSecret, sentence):
url = 'https://openapi.youdao.com/api'
salt = random.randint(1, 65536)
sign = appId+sentence+str(salt)+appSecret
m1 = hashlib.md5(sign.encode('utf-8'))
sign = m1.hexdigest()
params = {
'q': sentence,
'from': 'auto',
'to': 'auto',
'appKey': appId,
'salt': salt,
'sign': sign
}
result = requests.get(url, params=params)
res = json.loads(result.text, encoding='utf-8')
s = res['translation'][0]
return s
def getSentence(self, text):
pattern1 = re.compile("翻译.*?")
pattern2 = re.compile(".*?的翻译")
if re.match(pattern1, text) is not None:
sentence = text.replace("翻译", "")
elif re.match(pattern2, text) is not None:
sentence = text.replace("的翻译", "")
else:
sentence = ""
sentence = sentence.replace(",", "")
sentence = sentence.replace(",", "")
return sentence
def handle(self, text, parsed):
profile = config.get()
if self.SLUG not in profile or \
'appId' not in profile[self.SLUG] or\
'appSecret' not in profile[self.SLUG]:
self.say('有道翻译插件配置有误,插件使用失败', cache=True)
return
appId = profile[self.SLUG]['appId']
appSecret = profile[self.SLUG]['appSecret']
sentence = self.getSentence(text)
logger.info('sentence: ' + sentence)
if sentence:
try:
s = self.translate(appId, appSecret, sentence)
if s:
self.say(sentence+"的翻译是" + s, cache=False)
else:
self.say("翻译" + sentence + "失败,请稍后再试", cache=False)
except Exception as e:
logger.error(e)
self.say('抱歉, 我不知道怎么翻译' + sentence, cache=False)
else:
self.say(u"没有听清楚 请重试", cache=True)
def isValid(self, text, parsed):
return u"翻译" in text
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/alimtech/wukong-contrib.git
git@gitee.com:alimtech/wukong-contrib.git
alimtech
wukong-contrib
wukong-contrib
master

搜索帮助