package main import ( "encoding/json" "fmt" "log" "net/http" "net/url" "strings" "git.nefrace.ru/nefrace/nechotron" ) var docApiURL = "https://docs.godotengine.org/_/api/v2/search/?q=%s&project=godot&version=%s&language=en" var docURL = "https://docs.godotengine.org/ru/stable/search.html?q=%s" type DocResponse struct { Count uint `json:"count"` Next string `json:"next"` Previous string `json:"previous"` Results []DocResult `json:"results"` } type DocResult struct { Title string `json:"title"` Domain string `json:"domain"` Path string `json:"path"` Highlights DocHighlights `json:"highlights"` } type DocHighlights struct { Title []string `json:"title"` } func getDocs(topic string, version string) (string, error) { topic_escaped := nechotron.EscapeMd2(topic) not_found := fmt.Sprintf("Извините, по запросу *%s* ничего не найдено.", topic_escaped) req, err := url.ParseRequestURI(fmt.Sprintf(docApiURL, url.QueryEscape(topic), version)) if err != nil { return not_found, err } result, err := http.Get(req.String()) if err != nil { return not_found, err } defer result.Body.Close() var response DocResponse err = json.NewDecoder(result.Body).Decode(&response) if err != nil { return not_found, err } textResults := "" for i, r := range response.Results { if i > 9 { break } text := nechotron.EscapeMd2(r.Title) link, _ := url.JoinPath(r.Domain, r.Path) textResults += fmt.Sprintf("%d\\. [%s](%s)\n", i+1, text, link) } text := fmt.Sprintf("Вот что я нашла по запросу *%s* \\(для версии `%s`\\): \n\n%s", topic_escaped, version, textResults) return text, nil } func handleDocRequest(u *nechotron.Update) error { topic := u.Ctx.Value(nechotron.FilteredValue("docTopic")).(string) kb := nechotron.NewInlineKeyboard(). Row( nechotron.InButtonCallback("Дай для 3.5", fmt.Sprintf("docs3:%s", topic)), nechotron.InButtonCallback("А на русском можно?", "rudocs")). Row(nechotron.InButtonURL("Поищу сам", fmt.Sprintf(docURL, url.QueryEscape(topic)))). Row(nechotron.InButtonCallback("Спасибо, не надо", "delete")) opts := nechotron.NewOptions(). MarkdownV2(). ReplyTo(u.MessageID()). ReplyMarkup(kb.Markup()). MessageOptions() text, docerr := getDocs(topic, "latest") if docerr != nil { log.Println("Can't get docs: ", docerr) } _, err := u.AnswerText(text, opts) return err } func handleDocRequest3(u *nechotron.Update) error { topic := strings.TrimPrefix(u.Callback(), "docs3:") kb := nechotron.NewInlineKeyboard(). Row( nechotron.InButtonCallback("А на русском можно?", "rudocs")). Row(nechotron.InButtonURL("Поищу сам", fmt.Sprintf(docURL, url.QueryEscape(topic)))). Row(nechotron.InButtonCallback("Спасибо, не надо", "delete")) opts := nechotron.NewOptions(). MarkdownV2(). ReplyMarkup(kb.Markup()). MessageTextOptions() text, docerr := getDocs(topic, "3.5") if docerr != nil { log.Println("Can't get docs: ", docerr) } _, err := u.EditText(text, opts) return err }