-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtranslate.go
69 lines (56 loc) · 1.54 KB
/
translate.go
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
package translate
import (
"encoding/json"
"fmt"
"github.com/0x263b/porygon2"
"io/ioutil"
"net/http"
"net/url"
)
const (
translateURL = "https://api.datamarket.azure.com/Bing/MicrosoftTranslator/v1/Translate?Text='%s'&To='%s'&From='%s'&$format=json"
)
type Translation struct {
D struct {
Results []struct {
Metadata struct {
URI string `json:"uri"`
Type string `json:"type"`
} `json:"__metadata"`
Text string `json:"Text"`
} `json:"results"`
} `json:"d"`
}
func translate(command *bot.Cmd, matches []string) (msg string, err error) {
from := matches[1]
to := matches[2]
if from == "cn" {
from = "zh-CHS"
} else if from == "tw" {
from = "zh-CHT"
} else if to == "cn" {
to = "zh-CHS"
} else if to == "tw" {
to = "zh-CHT"
}
client := &http.Client{}
request, _ := http.NewRequest("GET", fmt.Sprintf(translateURL, url.QueryEscape(matches[3]), to, from), nil)
request.SetBasicAuth(bot.Config.Nick, bot.Config.Translate)
response, _ := client.Do(request)
defer response.Body.Close()
body, _ := ioutil.ReadAll(response.Body)
var translation Translation
json.Unmarshal(body, &translation)
if err != nil {
return fmt.Sprintf("Translate | %s >> %s | Could not get translation", from, to), nil
}
if len(translation.D.Results) == 0 {
return fmt.Sprintf("Translate | %s >> %s | Could not get translation", from, to), nil
}
return fmt.Sprintf("Translate | %s >> %s | %s", from, to, translation.D.Results[0].Text), nil
}
func init() {
bot.RegisterCommand(
"^tr(?:anslate)? (\\w+) (\\w+) (.+)$",
translate)
}