diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS new file mode 100644 index 0000000..3efc216 --- /dev/null +++ b/.github/CODEOWNERS @@ -0,0 +1 @@ +* @AshokShau diff --git a/.github/README.md b/.github/README.md new file mode 100644 index 0000000..bcc7eef --- /dev/null +++ b/.github/README.md @@ -0,0 +1,108 @@ +# Telegram Bot API Documentation Assistant + +This Telegram bot provides quick access to the Telegram Bot API documentation. Users can search for API methods and types using inline queries, and the bot will return detailed information about the specified API elements. + +### Demo Bot: [@BotApiDocsBot](https://t.me/BotApiDocsBot) + +## Features +- Inline search for API methods and types. +- Detailed descriptions, return types, and required fields for each method and type. +- Easy access to the official documentation. + +## Prerequisites +- Go version 1.23 or higher. +- A Telegram bot token obtainable from [BotFather](https://core.telegram.org/bots#botfather). + +## Installation + +### 1. Install Go +Follow the instructions to install Go on your system: [Go Installation Guide](https://golang.org/doc/install). + +
+Easy Way: + +```shell +git clone https://github.com/udhos/update-golang dlgo && cd dlgo && sudo ./update-golang.sh && source /etc/profile.d/golang_path.sh +``` + +Exit the terminal and open it again to check the installation. +
+ +Verify the installation by running: + +```shell +go version +``` + +### 2. Clone the repository + +```shell +git clone https://github.com/AshokShau/BotApiDocs&& cd BotApiDocs +``` + +### 3. Set up the environment + +Copy the sample environment file and edit it as needed: + +```shell +cp sample.env .env +vi .env +``` + +### 4. Build the project + +```shell +go build +``` + +### 5. Run the project + +```shell +./BotApiDocs +``` + +## Usage + +1. **Start a chat** with your bot on Telegram. Once the bot is running, you can search for API methods and types. +2. Use the inline query feature by typing `@YourBotUsername ` to search for methods or types. +3. The bot will return relevant results with detailed descriptions. + +## Contributing +
+Contribution Guidelines + +Contributions are welcome! Here's how you can help: + +1. **Fork the repository**. +2. **Clone your forked repository** to your local machine. + ```shell + git clone https://github.com/your-username/BotApiDocs.git + cd BotApiDocs + ``` +3. **Create a new branch** for your changes. + ```shell + git checkout -b feature-branch + ``` +4. **Make your changes** and commit them with a descriptive message. + ```shell + git add . + git commit -m "Description of your changes" + ``` +5. **Push to your branch** and submit a pull request. + +Please ensure your code follows the project's coding standards and includes appropriate tests. +
+ +## License + +This project is licensed under the MIT License—see the [LICENSE](/LICENSE) file for details. + +## Contact + +[![Telegram](https://img.shields.io/badge/Telegram-Channel-blue.svg)](https://t.me/FallenProjects) +[![Telegram](https://img.shields.io/badge/Telegram-Chat-blue.svg)](https://t.me/AshokShau) + + +## Thanks +- [Ashok Shau](https://github.com/AshokShau) for the project. +- [PaulSonOfLars](https://github.com/PaulSonOfLars) for the [GoTgBot](https://github.com/PaulSonOfLars/gotgbot) library and [Api](https://github.com/PaulSonOfLars/telegram-bot-api-spec/raw/main/api.json). diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 0000000..7adb774 --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,18 @@ +name: build + +on: [push, pull_request] + +jobs: + + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Set up Go + uses: actions/setup-go@v4 + with: + go-version: '1.23.0' + + - name: Build + run: go build -v ./... diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..cc70b0d --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +.idea +.env +*.exe diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..a259231 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 AshokShau + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/Telegram/config/config.go b/Telegram/config/config.go new file mode 100644 index 0000000..feb43f6 --- /dev/null +++ b/Telegram/config/config.go @@ -0,0 +1,27 @@ +package config + +import ( + "os" + "strconv" + + _ "github.com/joho/godotenv/autoload" +) + +var ( + Token string + OwnerId int64 + WebhookUrl string + Port string +) + +func init() { + Token = os.Getenv("TOKEN") + OwnerId = toInt64(os.Getenv("OWNER_ID")) + WebhookUrl = os.Getenv("WEBHOOK_URL") + Port = os.Getenv("PORT") +} + +func toInt64(str string) int64 { + val, _ := strconv.ParseInt(str, 10, 64) + return val +} diff --git a/Telegram/modules/inline.go b/Telegram/modules/inline.go new file mode 100644 index 0000000..1ffe746 --- /dev/null +++ b/Telegram/modules/inline.go @@ -0,0 +1,241 @@ +package modules + +import ( + "encoding/json" + "fmt" + "log" + "math/rand" + "net/http" + "strconv" + "strings" + "sync" + "time" + + "github.com/PaulSonOfLars/gotgbot/v2" + "github.com/PaulSonOfLars/gotgbot/v2/ext" +) + +// apiCache is a global cache for storing API methods and types. +var apiCache struct { + sync.RWMutex + Methods map[string]Method + Types map[string]Type +} + +// Method represents an API method with its details. +type Method struct { + Name string `json:"name"` + Description []string `json:"description"` + Href string `json:"href"` + Returns []string `json:"returns"` + Fields []Field `json:"fields,omitempty"` +} + +// Type represents an API type with its details. +type Type struct { + Name string `json:"name"` + Description []string `json:"description"` + Href string `json:"href"` + Fields []Field `json:"fields,omitempty"` +} + +// Field represents a field in an API method or type. +type Field struct { + Name string `json:"name"` + Types []string `json:"types"` + Required bool `json:"required"` + Description string `json:"description"` +} + +// fetchAPI fetches the API documentation from a remote source and updates the apiCache. +func fetchAPI() error { + client := &http.Client{Timeout: 10 * time.Second} + resp, err := client.Get("https://github.com/PaulSonOfLars/telegram-bot-api-spec/raw/main/api.json") + if err != nil { + return fmt.Errorf("failed to fetch API: %w", err) + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + return fmt.Errorf("unexpected status code: %d", resp.StatusCode) + } + + var apiDocs struct { + Methods map[string]Method `json:"methods"` + Types map[string]Type `json:"types"` + } + + if err := json.NewDecoder(resp.Body).Decode(&apiDocs); err != nil { + return fmt.Errorf("failed to decode API response: %w", err) + } + + apiCache.Lock() + apiCache.Methods = apiDocs.Methods + apiCache.Types = apiDocs.Types + apiCache.Unlock() + + return nil +} + +// StartAPICacheUpdater starts a goroutine that periodically updates the API cache. +func StartAPICacheUpdater(interval time.Duration) { + go func() { + for { + if err := fetchAPI(); err != nil { + log.Println("Error updating API documentation:", err) + } + time.Sleep(interval) + } + }() +} + +// inlineQueryHandler handles inline queries from the bot. +func inlineQueryHandler(bot *gotgbot.Bot, ctx *ext.Context) error { + query := strings.TrimSpace(ctx.InlineQuery.Query) + parts := strings.Fields(query) + + if len(parts) < 1 { + return sendEmptyQueryResponse(bot, ctx) + } + + kueri := strings.Join(parts, " ") + if strings.ToLower(parts[0]) == "botapi" { + kueri = strings.Join(parts[1:], " ") + } + + apiCache.RLock() + methods := apiCache.Methods + types := apiCache.Types + apiCache.RUnlock() + + results := searchAPI(kueri, methods, types) + + if len(results) == 0 { + return sendNoResultsResponse(bot, ctx, kueri) + } + + if len(results) > 50 { + results = results[:50] + } + + _, err := ctx.InlineQuery.Answer(bot, results, &gotgbot.AnswerInlineQueryOpts{IsPersonal: true}) + return err +} + +// sendEmptyQueryResponse sends a response for an empty inline query. +func sendEmptyQueryResponse(bot *gotgbot.Bot, ctx *ext.Context) error { + _, err := ctx.InlineQuery.Answer(bot, []gotgbot.InlineQueryResult{}, &gotgbot.AnswerInlineQueryOpts{ + IsPersonal: true, + CacheTime: 5, + Button: &gotgbot.InlineQueryResultsButton{ + Text: "Type '' to search!", + StartParameter: "start", + }, + }) + return err +} + +// searchAPI searches the API methods and types for the given query. +func searchAPI(query string, methods map[string]Method, types map[string]Type) []gotgbot.InlineQueryResult { + var results []gotgbot.InlineQueryResult + + for name, method := range methods { + if strings.Contains(strings.ToLower(name), strings.ToLower(query)) { + msg := buildMethodMessage(method) + results = append(results, createInlineResult(name, method.Href, msg, method.Href)) + } + } + + for name, typ := range types { + if strings.Contains(strings.ToLower(name), strings.ToLower(query)) { + msg := buildTypeMessage(typ) + results = append(results, createInlineResult(name, typ.Href, msg, typ.Href)) + } + } + + return results +} + +// sendNoResultsResponse sends a response when no results are found for the query. +func sendNoResultsResponse(bot *gotgbot.Bot, ctx *ext.Context, query string) error { + _, err := ctx.InlineQuery.Answer(bot, []gotgbot.InlineQueryResult{noResultsArticle(query)}, &gotgbot.AnswerInlineQueryOpts{ + IsPersonal: true, + CacheTime: 5, + }) + return err +} + +// buildMethodMessage builds a message string for a given API method. +func buildMethodMessage(method Method) string { + var msgBuilder strings.Builder + msgBuilder.WriteString(fmt.Sprintf("%s\n", method.Name)) + msgBuilder.WriteString(fmt.Sprintf("Description: %s\n\n", strings.Join(method.Description, ", "))) + msgBuilder.WriteString("Returns: " + strings.Join(method.Returns, ", ") + "\n") + + if len(method.Fields) > 0 { + msgBuilder.WriteString("Fields:\n") + for _, field := range method.Fields { + msgBuilder.WriteString(fmt.Sprintf("%s (%s) - Required: %t\n", field.Name, strings.Join(field.Types, ", "), field.Required)) + msgBuilder.WriteString(field.Description + "\n\n") + } + } + + return msgBuilder.String() +} + +// buildTypeMessage builds a message string for a given API type. +func buildTypeMessage(typ Type) string { + var msgBuilder strings.Builder + msgBuilder.WriteString(fmt.Sprintf("%s\n", typ.Name)) + msgBuilder.WriteString(fmt.Sprintf("Description: %s\n\n", strings.Join(typ.Description, ", "))) + + if len(typ.Fields) > 0 { + msgBuilder.WriteString("Fields:\n") + for _, field := range typ.Fields { + msgBuilder.WriteString(fmt.Sprintf("%s (%s) - Required: %t\n", field.Name, strings.Join(field.Types, ", "), field.Required)) + msgBuilder.WriteString(field.Description + "\n\n") + } + } + + return msgBuilder.String() +} + +// createInlineResult creates an inline query result for a given API method or type. +func createInlineResult(title, url, message, methodUrl string) gotgbot.InlineQueryResult { + return gotgbot.InlineQueryResultArticle{ + Id: strconv.Itoa(rand.Intn(100000)), + Title: title, + Url: url, + HideUrl: true, + InputMessageContent: gotgbot.InputTextMessageContent{ + MessageText: message, + ParseMode: gotgbot.ParseModeHTML, + }, + Description: "View more details", + ReplyMarkup: &gotgbot.InlineKeyboardMarkup{ + InlineKeyboard: [][]gotgbot.InlineKeyboardButton{ + {{Text: "Open Docs", Url: methodUrl}}, + {{Text: "Search Again", SwitchInlineQueryCurrentChat: &title}}, + }, + }, + } +} + +// noResultsArticle creates an inline query result indicating no results were found. +func noResultsArticle(query string) gotgbot.InlineQueryResult { + ok := "botapi" + return gotgbot.InlineQueryResultArticle{ + Id: "no_results", + Title: "No Results Found!", + InputMessageContent: gotgbot.InputTextMessageContent{ + MessageText: fmt.Sprintf("👋 Sorry, I couldn't find any results for '%s'. Try searching with a different keyword!", query), + ParseMode: gotgbot.ParseModeHTML, + }, + Description: "No results found for your query.", + ReplyMarkup: &gotgbot.InlineKeyboardMarkup{ + InlineKeyboard: [][]gotgbot.InlineKeyboardButton{ + {{Text: "Search Again", SwitchInlineQueryCurrentChat: &ok}}, + }, + }, + } +} diff --git a/Telegram/modules/loadModules.go b/Telegram/modules/loadModules.go new file mode 100644 index 0000000..0b38155 --- /dev/null +++ b/Telegram/modules/loadModules.go @@ -0,0 +1,29 @@ +package modules + +import ( + "github.com/AshokShau/BotApiDocs/Telegram/config" + "github.com/PaulSonOfLars/gotgbot/v2" + "github.com/PaulSonOfLars/gotgbot/v2/ext" + "github.com/PaulSonOfLars/gotgbot/v2/ext/handlers" + "github.com/PaulSonOfLars/gotgbot/v2/ext/handlers/filters/inlinequery" +) + +var Dispatcher = newDispatcher() + +// newDispatcher creates a new dispatcher and loads modules. +func newDispatcher() *ext.Dispatcher { + dispatcher := ext.NewDispatcher(&ext.DispatcherOpts{ + Error: func(b *gotgbot.Bot, ctx *ext.Context, err error) ext.DispatcherAction { + _, _ = b.SendMessage(config.OwnerId, "An error occurred: "+err.Error(), nil) + return ext.DispatcherActionNoop + }, + }) + + loadModules(dispatcher) + return dispatcher +} + +func loadModules(d *ext.Dispatcher) { + d.AddHandler(handlers.NewCommand("start", start)) + d.AddHandler(handlers.NewInlineQuery(inlinequery.All, inlineQueryHandler)) +} diff --git a/Telegram/modules/start.go b/Telegram/modules/start.go new file mode 100644 index 0000000..81a0678 --- /dev/null +++ b/Telegram/modules/start.go @@ -0,0 +1,21 @@ +package modules + +import ( + "fmt" + "github.com/PaulSonOfLars/gotgbot/v2" + "github.com/PaulSonOfLars/gotgbot/v2/ext" + "log" +) + +func start(b *gotgbot.Bot, ctx *ext.Context) error { + msg := ctx.EffectiveMessage + text := fmt.Sprintf("👋 Hello! I'm your handy Telegram Bot API assistant, built with GoTgBot.\n\n💡 Usage: @%s your_query - Quickly search for any method or type in the Telegram Bot API documentation.", b.User.Username) + + _, err := msg.Reply(b, text, &gotgbot.SendMessageOpts{ParseMode: "HTML"}) + if err != nil { + log.Printf("[start] Error sending message: %v", err) + return err + } + + return ext.EndGroups +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..7480e9a --- /dev/null +++ b/go.mod @@ -0,0 +1,8 @@ +module github.com/AshokShau/BotApiDocs + +go 1.23.1 + +require ( + github.com/PaulSonOfLars/gotgbot/v2 v2.0.0-rc.29 + github.com/joho/godotenv v1.5.1 +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..37615c8 --- /dev/null +++ b/go.sum @@ -0,0 +1,4 @@ +github.com/PaulSonOfLars/gotgbot/v2 v2.0.0-rc.29 h1:5/K8zgmoKnsegt6h9XvFIJAGxbHVWOEwSpjdjaySf6A= +github.com/PaulSonOfLars/gotgbot/v2 v2.0.0-rc.29/go.mod h1:kL1v4iIjlalwm3gCYGvF4NLa3hs+aKEfRkNJvj4aoDU= +github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0= +github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4= diff --git a/main.go b/main.go new file mode 100644 index 0000000..7ff3839 --- /dev/null +++ b/main.go @@ -0,0 +1,89 @@ +package main + +import ( + "fmt" + "github.com/AshokShau/BotApiDocs/Telegram/config" + "github.com/AshokShau/BotApiDocs/Telegram/modules" + "github.com/PaulSonOfLars/gotgbot/v2" + "github.com/PaulSonOfLars/gotgbot/v2/ext" + "log" + "time" +) + +const secretToken = "thisIsASecretToken" + +var allowedUpdates = []string{"message", "inline_query"} + +// initBot initializes the bot and updater with the provided token from the config. +// Returns the bot, updater, and an error if any. +func initBot() (*gotgbot.Bot, *ext.Updater, error) { + if config.Token == "" { + return nil, nil, fmt.Errorf("no token provided Add `TOKEN` to .env file") + } + + bot, err := gotgbot.NewBot(config.Token, nil) + if err != nil { + return nil, nil, fmt.Errorf("failed to create new bot: %w", err) + } + + updater := ext.NewUpdater(modules.Dispatcher, nil) + return bot, updater, nil +} + +// configureWebhook sets up the webhook for the bot using the provided URL and token from the config. +// Returns an error if the webhook setup fails. +func configureWebhook(bot *gotgbot.Bot, updater *ext.Updater) error { + if config.WebhookUrl == "" { + return fmt.Errorf("WEBHOOK_URL is not provided") + } + + _, err := bot.SetWebhook(config.WebhookUrl+config.Token, &gotgbot.SetWebhookOpts{ + MaxConnections: 40, + DropPendingUpdates: true, + AllowedUpdates: allowedUpdates, + SecretToken: secretToken, + }) + if err != nil { + return fmt.Errorf("failed to set webhook: %w", err) + } + + return updater.StartWebhook(bot, config.Token, ext.WebhookOpts{ + ListenAddr: "0.0.0.0:" + config.Port, + SecretToken: secretToken, + }) +} + +// startPolling starts polling for updates from the bot. +// Returns an error if polling fails. +func startPolling(bot *gotgbot.Bot, updater *ext.Updater) error { + return updater.StartPolling(bot, &ext.PollingOpts{ + DropPendingUpdates: true, + EnableWebhookDeletion: true, + GetUpdatesOpts: &gotgbot.GetUpdatesOpts{AllowedUpdates: allowedUpdates}, + }) +} + +// The main is the entry point of the application. +// It initializes the bot, configures the webhook or starts polling based on the configuration, +// and handles the bot's lifecycle. +func main() { + bot, updater, err := initBot() + if err != nil { + log.Fatalf("Initialization error: %s", err) + } + + mode := "Webhook" + if err = configureWebhook(bot, updater); err != nil { + log.Printf("Webhook configuration failed: %s", err) + mode = "Polling" + if err = startPolling(bot, updater); err != nil { + log.Fatalf("Polling start failed: %s", err) + } + } + // Start API cache updater with a 1-hour interval + go modules.StartAPICacheUpdater(1 * time.Hour) + log.Printf("Bot has been started as %s[%s] using %s", bot.FirstName, bot.Username, mode) + updater.Idle() + + log.Printf("Bot has been stopped") +} diff --git a/sample.env b/sample.env new file mode 100644 index 0000000..2214967 --- /dev/null +++ b/sample.env @@ -0,0 +1,2 @@ +TOKEN= +OWNER_ID=