forked from wzpan/wukong-contrib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
YouDaoFanYi.py
79 lines (67 loc) · 2.47 KB
/
YouDaoFanYi.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# -*- 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