forked from nkoster/weechat-translate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tr.py
73 lines (56 loc) · 2.06 KB
/
tr.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
## Language translation, by Niels, [email protected], license is GPL3.
# v0.0.3: Updated to support Python3 -@pX <[email protected]> 03.30.2019
# v0.0.4: Py3 translate would fail if input included accented
# : characters -@pX <[email protected]> 04.01.2019
# : py3-ok
import weechat
import sys
# try for py2 urllib2, else load py3 urllib
try:
import urllib2
ulib = urllib2
except:
import urllib.request
ulib = urllib.request
weechat.register('tr', 'Translator', '0.0.3', 'GPL3', 'Google Translate Script', '', '')
def timer_cb(data, remaining_calls):
weechat.prnt(weechat.current_buffer(), '%s' % data)
return weechat.WEECHAT_RC_OK
weechat.hook_timer(2000, 0, 1, 'timer_cb', '/tr:\t/tr, Google Translate in Weechat')
def tr_cb(data, buffer, args):
a = args.split(' ')
if len(a) < 2:
weechat.prnt(weechat.current_buffer(), '/tr:\tUsage /tr lang[,lang] text')
return weechat.WEECHAT_RC_OK
o = 'nl'
l = a[0]
ol = l.split(',')
tl = ol[0]
if len(ol) > 1:
o = ol[1]
# fix py3 translation issue, else py2
if sys.version_info >= (3,3):
t = urllib.parse.quote(' '.join(a[1:]))
else:
t = ' '.join(a[1:])
url = 'https://translate.googleapis.com/translate_a/single' + \
'?client=gtx&sl=' + o + '&tl=' + tl + '&dt=t&q=' + t
url = url.replace(' ', '%20')
req = ulib.Request(url)
req.add_header('User-Agent', 'Mozilla/5.0')
response = ulib.urlopen(req)
html = response.read()
# support for py3, else py2
if sys.version_info >= (3, 3):
tr = html.decode().split('"')[1]
else:
tr = html.split('"')[1]
if tr != 'nl':
if o == 'nl':
weechat.command(weechat.current_buffer(), '%s' % tr)
else:
weechat.prnt(weechat.current_buffer(), '/tr:\t%s' % tr)
return weechat.WEECHAT_RC_OK
weechat.hook_command('tr', 'Google Translator', 'lang[,lang] text',
'Language codes: https://sites.google.com/site/tomihasa/google-language-codes\n'
'Github: https://github.com/nkoster/weechat-translate', '', 'tr_cb', '')