Issues (115)

api/translate/translate.go (1 issue)

Severity
1
package translate
2
3
import (
4
	"encoding/json"
5
	"errors"
6
	"fmt"
7
	"net/http"
8
	"strings"
9
10
	"github.com/FlameInTheDark/dtbot/bot"
11
)
12
13
// TranslateResponse : Translate API struct
14
type TranslateResponse struct {
0 ignored issues
show
type name will be used as translate.TranslateResponse by other packages, and that stutters; consider calling this Response
Loading history...
15
	Code     int      `json:"code"`
16
	Language string   `json:"lang"`
17
	Text     []string `json:"text"`
18
	Message  string   `json:"message"`
19
}
20
21
// GetTranslation returns translated text
22
func GetTranslation(ctx *bot.Context) (string, error) {
23
	var (
24
		result    TranslateResponse
25
		translate string
26
	)
27
28
	if len(ctx.Args) > 1 {
29
		translate = strings.Join(ctx.Args[1:], "+")
30
	} else {
31
		return "", errors.New(ctx.Loc("translate_request_error"))
32
	}
33
34
	resp, err := http.Get(fmt.Sprintf("https://translate.yandex.net/api/v1.5/tr.json/translate?key=%v&text=%v&lang=%v&format=plain", ctx.Conf.Translate.APIKey, translate, ctx.Args[0]))
35
	if err != nil {
36
		return "", fmt.Errorf("%v: %v", ctx.Loc("translate_get_error"), err)
37
	}
38
39
	err = json.NewDecoder(resp.Body).Decode(&result)
40
	if err != nil {
41
		return "", fmt.Errorf("%v: %v", ctx.Loc("translate_parse_error"), err)
42
	}
43
44
	// Checking request status
45
	switch result.Code {
46
	case 502:
47
		return "", errors.New(ctx.Loc("translate_request_error"))
48
	case 200:
49
		return strings.Join(result.Text, "\n"), nil
50
	default:
51
		return "", errors.New(ctx.Loc("translate_api_error"))
52
	}
53
}
54