代码拉取完成,页面将自动刷新
# -*- 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
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。