// GetDefinitionYandex get definitions from yandex func GetDefinitionYandex(word string) (string, error) { params := url.Values{} params.Set("format", "plain") params.Set("lang", "en-vi") params.Set("text", word) params.Set("key", YANDEX_TRANSLATOR_APIKEY) resp, err := http.PostForm(YURL, params) if err != nil { util.LogError("yandex", 0, err) return "", err } defer resp.Body.Close() meJSON, err := ioutil.ReadAll(resp.Body) if err != nil { util.LogError("yandex", 1, err) return "", err } var result Result err = json.Unmarshal(meJSON, &result) if err != nil { util.LogError("yandex", 2, err) return "", err } definition := strings.Join(result.Text, " ") if definition == word { return "", errors.New("sameWord") } return "-> " + definition, nil }
func main() { //init redis redisClient = redis.NewClient(&redis.Options{ Addr: "localhost:6379", Password: "", DB: 1, }) dict.PrepareIndex() bot, err := telebot.NewBot(BOT_TOKEN) if err != nil { return } util.LogInit() messages := make(chan telebot.Message) bot.Listen(messages, 2*time.Second) for message := range messages { sender_id := message.Chat.ID // analytics purpose k := "u:" + strconv.Itoa(sender_id) redisClient.ZIncrBy("sorted_users", 1, k) definition := GetDefinition(message.Text, message.Chat) err = bot.SendMessage(message.Chat, definition, &telebot.SendOptions{ParseMode: "Markdown"}) if err != nil { util.LogError("sendMessage", sender_id, err) } } }
// GetDefinitionFromDb defines a function lookup from db/map func GetDefinitionFromDb(word string, sender telebot.Chat) string { word = strings.Trim(strings.ToLower(word), " ") sender_id := sender.ID // analytics purpose w := "w:" + word redisClient.ZIncrBy("sorted_words", 1, w) // should get from redis desc, err := redisClient.Get(word).Result() if err == nil { return desc } else if err == redis.Nil { result, err := dict.Check(word) if err != nil { if r.MatchString(word) { def, err := GetDefinitionYandex(word) if err != nil { util.LogError("yandex", sender_id, err.Error()) return fmt.Sprintf(APOLOGY_MSG, GetName(sender), word, GetName(sender), word) } else { SetWord(word, def) return def } } else { return fmt.Sprintf(APOLOGY_MSG, GetName(sender), word, GetName(sender), word) } } else { SetWord(word, result) return result } } log.Errorln(err.Error()) return "" }