Skip to content

Commit afd6066

Browse files
first commit
0 parents  commit afd6066

60 files changed

Lines changed: 5666 additions & 0 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

.gitignore

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
# If you prefer the allow list template instead of the deny list, see community template:
2+
# https://github.com/github/gitignore/blob/main/community/Golang/Go.AllowList.gitignore
3+
#
4+
# Binaries for programs and plugins
5+
*.exe
6+
*.exe~
7+
*.dll
8+
*.so
9+
*.dylib
10+
11+
test/
12+
13+
# Test binary, built with `go test -c`
14+
*.test
15+
16+
# Output of the go coverage tool, specifically when used with LiteIDE
17+
*.out
18+
19+
# Dependency directories (remove the comment below to include it)
20+
# vendor/
21+
22+
# Go workspace file
23+
go.work
24+
25+
# GoLand
26+
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
27+
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
28+
# and can be added to the global gitignore or merged into this file. For a more nuclear
29+
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
30+
.idea/
31+
32+
.vscode

LICENSE.txt

Lines changed: 392 additions & 0 deletions
Large diffs are not rendered by default.

README.md

Lines changed: 169 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,169 @@
1+
# MaxBot API Client (Go)
2+
3+
`maxbot-api-client-go` — это библиотека для интеграции с API MAX Bot. Этот проект предоставляет структурированный интерфейс для взаимодействия с конфигурациями бота, управления сообщениями, отправки медиафайлов и подписки на события через long-polling.
4+
5+
Для использования библиотеки потребуется получить токен бота в консоли разработчика MAX API.
6+
7+
## API
8+
9+
Документацию по REST API MAX можно найти по ссылке [https://dev.max.ru/docs-api]. Библиотека является оберткой для REST API, поэтому документация по указанной выше ссылке также применима к используемым здесь моделям и параметрам запроса.
10+
11+
## Поддержка
12+
13+
[![Support](https://img.shields.io/badge/support@green--api.com-D14836?style=for-the-badge&logo=gmail&logoColor=white)](mailto:support@green-api.com)
14+
[![Support](https://img.shields.io/badge/Telegram-2CA5E0?style=for-the-badge&logo=telegram&logoColor=white)](https://t.me/greenapi_support_ru_bot)
15+
[![Support](https://img.shields.io/badge/WhatsApp-25D366?style=for-the-badge&logo=whatsapp&logoColor=white)](https://wa.me/77780739095)
16+
17+
## Руководства и новости
18+
19+
[![Guides](https://img.shields.io/badge/YouTube-%23FF0000.svg?style=for-the-badge&logo=YouTube&logoColor=white)](https://www.youtube.com/@green-api)
20+
[![News](https://img.shields.io/badge/Telegram-2CA5E0?style=for-the-badge&logo=telegram&logoColor=white)](https://t.me/green_api)
21+
[![News](https://img.shields.io/badge/WhatsApp-25D366?style=for-the-badge&logo=whatsapp&logoColor=white)](https://whatsapp.com/channel/0029VaHUM5TBA1f7cG29nO1C)
22+
23+
24+
## Установка
25+
26+
**Убедитесь, что у вас установлена версия Go не ниже 1.20**
27+
28+
```shell
29+
go version
30+
```
31+
32+
**Создайте Go модуль, если он не создан:**
33+
34+
```
35+
go mod init ModuleName
36+
```
37+
38+
**Установите библиотеку:**
39+
40+
```bash
41+
go get github.com/green-api/maxbot-api-client-go
42+
```
43+
44+
**Импорт:**
45+
46+
```go
47+
import(
48+
"github.com/green-api/maxbot-api-client-go"
49+
)
50+
```
51+
52+
## Использование и примеры
53+
54+
**Как инициализировать клиент:**
55+
56+
```go
57+
bot, err := api.New(client.Config{
58+
BaseURL: "https://platform-api.max.ru",
59+
Token: "YOUR_BOT_TOKEN",
60+
})
61+
if err != nil {
62+
log.Fatal().Err(err).Msg("failed to init MAX API")
63+
}
64+
```
65+
66+
**Как получить информацию о боте:**
67+
68+
Ссылка на пример: [GetBot/main.go](./cmd/examples/GetBot/main.go)
69+
70+
```go
71+
response, err := bot.Bots.GetBot(context.Background())
72+
```
73+
74+
**Как отправить сообщение:**
75+
76+
Ссылка на пример: [SendMessage/main.go](./cmd/examples/SendMessage/main.go)
77+
78+
```go
79+
response, err := bot.Messages.SendMessage(context.Background(), models.SendMessageReq{
80+
UserID: 1234567890,
81+
Text: "Hello world!",
82+
})
83+
```
84+
85+
**Как легко отправить файл (по ссылке или локальный):**
86+
87+
Ссылка на пример: [SendFile/main.go](./cmd/examples/SendFile/main.go)
88+
89+
```go
90+
response, err := bot.Helpers.SendFile(context.Background(), models.SendFileReq{
91+
ChatID: exampleChatID,
92+
FileSource: "cmd/examples/assets/file.txt",
93+
})
94+
```
95+
96+
```go
97+
response, err := bot.Helpers.SendFile(context.Background(), models.SendFileReq{
98+
ChatID: exampleChatID,
99+
FileSource: "https://storage.yandexcloud.net/sw-prod-03-test/ChatBot/corgi.jpg",
100+
})
101+
```
102+
103+
**Как вручную загрузить файл (для кастомных вложений):**
104+
105+
Ссылка на пример: [UploadFile/main.go](./cmd/examples/UploadFile/main.go)
106+
107+
```go
108+
response, err := bot.Uploads.UploadFile(context.Background(), models.UploadFileReq{
109+
Type: models.UploadImage,
110+
FilePath: "/path/to/your/image.png",
111+
})
112+
```
113+
114+
**Как получить входящее уведомление:**
115+
116+
Ссылка на пример: [GetUpdates/main.go](./cmd/examples/GetUpdates/main.go)
117+
118+
```go
119+
response, err := bot.Subscriptions.GetUpdates(context.Background())
120+
```
121+
122+
---
123+
124+
## Список примеров
125+
126+
| Описание | Ссылка на пример |
127+
|--------------------------------------|--------------------------------------------------------------|
128+
| Как отправить сообщение | [SendMessage/main.go](./cmd/examples/SendMessage/main.go) |
129+
| Как получить информацию о боте | [GetBot/main.go](./cmd/examples/GetBot/main.go) |
130+
| Как отправить файл | [SendFile/main.go](./cmd/examples/SendFile/main.go) |
131+
| Как загрузить файл | [UploadFile/main.go](./cmd/examples/UploadFile/main.go) |
132+
| Как получить входящее уведомление | [GetUpdates/main.go](./cmd/examples/GetUpdates/main.go) |
133+
134+
135+
## Список всех методов библиотеки
136+
137+
| Метод API | Описание | Ссылка на документацию MAX | Ссылка на документацию библиотеки |
138+
|-----------------|-------------------------|------------------------------------------------|----------------------------------------------|
139+
| `Bots.GetBot` | Получает информацию о боте | [GetBot](https://dev.max.ru/docs-api/methods/GET/me) | [GetBot](./docs/bots/GetBot.md) |
140+
| `Bots.PatchBot` | Изменяет информацию о боте | | [PatchBot](./docs/bots/PatchBot.md) |
141+
| `Chats.GetChats` | Возвращает список групповых чатов, в которых участвовал бот | [GetChats](https://dev.max.ru/docs-api/methods/GET/chats) | [GetChats](./docs/chats/GetChats.md) |
142+
| `Chats.GetChat` | Возвращает информацию о групповом чате по его ID | [GetChat](https://dev.max.ru/docs-api/methods/GET/chats/-chatId-) | [GetChat](./docs/chats/GetChat.md) |
143+
| `Chats.EditChat` | Позволяет редактировать информацию о групповом чате | [EditChat](https://dev.max.ru/docs-api/methods/PATCH/chats/-chatId-) | [EditChat](./docs/chats/EditChat.md) |
144+
| `Chats.DeleteChat` | Удаляет групповой чат для всех участников | [DeleteChat](https://dev.max.ru/docs-api/methods/DELETE/chats/-chatId-) | [DeleteChat](./docs/chats/DeleteChat.md) |
145+
| `Chats.SendAction` | Позволяет отправлять следующие действия бота в групповой чат | [SendAction](https://dev.max.ru/docs-api/methods/POST/chats/-chatId-/actions) | [SendAction](./docs/chats/SendAction.md) |
146+
| `Chats.GetPinnedMessage` | Возвращает закрепленное сообщение в чате | [GetPinnedMessage](https://dev.max.ru/docs-api/methods/GET/chats/-chatId-/pin) | [GetPinnedMessage](./docs/chats/GetPinnedMessage.md) |
147+
| `Chats.PinMessage` | Закрепляет сообщение в групповом чате | [PinMessage](https://dev.max.ru/docs-api/methods/PUT/chats/-chatId-/pin) | [PinMessage](./docs/chats/PinMessage.md) |
148+
| `Chats.UnpinMessage` | Удаляет закрепленное сообщение в групповом чате | [UnpinMessage](https://dev.max.ru/docs-api/methods/DELETE/chats/-chatId-/pin) | [UnpinMessage](./docs/chats/UnpinMessage.md) |
149+
| `Chats.GetChatMembership` | Возвращает членство бота в групповом чате | [GetChatMembership](https://dev.max.ru/docs-api/methods/GET/chats/-chatId-/members/me) | [GetChatMembership](./docs/chats/GetChatMembership.md) |
150+
| `Chats.LeaveChat` | Удаляет бота из группового чата | [LeaveChat](https://dev.max.ru/docs-api/methods/DELETE/chats/-chatId-/members/me) | [LeaveChat](./docs/chats/LeaveChat.md) |
151+
| `Chats.GetChatAdmins` | Возвращает список всех администраторов группового чата | [GetChatAdmins](https://dev.max.ru/docs-api/methods/GET/chats/-chatId-/members/admins) | [GetChatAdmins](./docs/chats/GetChatAdmins.md) |
152+
| `Chats.SetChatAdmins` | Назначает участника группы администратором | [SetChatAdmins](https://dev.max.ru/docs-api/methods/POST/chats/-chatId-/members/admins) | [SetChatAdmins](./docs/chats/SetChatAdmins.md) |
153+
| `Chats.DeleteAdmin` | Отменяет права администратора пользователя в групповом чате | [DeleteAdmin](https://dev.max.ru/docs-api/methods/DELETE/chats/-chatId-/members/admins/-userId-) | [DeleteAdmin](./docs/chats/DeleteAdmin.md) |
154+
| `Chats.GetChatMembers` | Возвращает список участников группового чата | [GetChatMembers](https://dev.max.ru/docs-api/methods/GET/chats/-chatId-/members) | [GetChatMembers](./docs/chats/GetChatMembers.md) |
155+
| `Chats.AddMembers` | Добавляет участников в групповой чат | [AddMembers](https://dev.max.ru/docs-api/methods/POST/chats/-chatId-/members) | [AddMembers](./docs/chats/AddMembers.md) |
156+
| `Chats.DeleteMember` | Удаляет участника из группового чата | [DeleteMember](https://dev.max.ru/docs-api/methods/DELETE/chats/-chatId-/members) | [DeleteMember](./docs/chats/DeleteMember.md) |
157+
| `Subscriptions.GetSubscriptions` | Возвращает список подписок на уведомления веб-хуков | [GetSubscriptions](https://dev.max.ru/docs-api/methods/GET/subscriptions) | [GetSubscriptions](./docs/subscriptions/GetSubscriptions.md) |
158+
| `Subscriptions.Subscribe` | Настраивает доставку событий бота через веб-хук | [Subscribe](https://dev.max.ru/docs-api/methods/POST/subscriptions) | [Subscribe](./docs/subscriptions/Subscribe.md) |
159+
| `Subscriptions.Unsubscribe` | Отменяет подписку бота на получение обновлений через веб-хук | [Unsubscribe](https://dev.max.ru/docs-api/methods/DELETE/subscriptions) | [Unsubscribe](./docs/subscriptions/Unsubscribe.md)|
160+
| `Subscriptions.GetUpdates` | Получает входящие обновления | [GetUpdates](https://dev.max.ru/docs-api/methods/GET/updates) | [GetUpdates](./docs/subscriptions/GetUpdates.md) |
161+
| `Upload.UploadFile` | Загружает файл на серверы MAX для последующей передачи | [UploadFile](https://dev.max.ru/docs-api/methods/POST/uploads) | [UploadFile](./docs/upload/UploadFile.md) |
162+
| `Helpers.SendFile` | Упрощает отправку файлов, автоматически определяя URL или путь | | [SendFile](./docs/helpers/SendFile.md) |
163+
| `Messages.GetMessages` | Возвращает информацию о сообщении или массив сообщений из чата | [GetMessages](https://dev.max.ru/docs-api/methods/GET/messages) | [GetMessages](./docs/messages/GetMessages.md) |
164+
| `Messages.SendMessage` | Отправляет текстовое или медиа-сообщение указанному пользователю или в чат | [SendMessage](https://dev.max.ru/docs-api/methods/POST/messages) | [SendMessage](./docs/messages/SendMessage.md) |
165+
| `Messages.EditMessage` | Редактирует текст или медиафайл ранее отправленного сообщения | [EditMessage](https://dev.max.ru/docs-api/methods/PUT/messages) | [EditMessage](./docs/messages/EditMessage.md) |
166+
| `Messages.DeleteMessage` | Удаляет сообщение из чата | [DeleteMessage](https://dev.max.ru/docs-api/methods/DELETE/messages) | [DeleteMessage](./docs/messages/DeleteMessage.md) |
167+
| `Messages.GetMessage` | Извлекает содержимое и метаданные конкретного сообщения по его ID | [GetMessage](https://dev.max.ru/docs-api/methods/GET/messages/-messageId-) | [GetMessage](./docs/messages/GetMessage.md) |
168+
| `Messages.GetVideoInfo` | Возвращает подробную информацию о прикрепленном видео | [GetVideoInfo](https://dev.max.ru/docs-api/methods/GET/videos/-videoToken-) | [GetVideoInfo](./docs/messages/GetVideoInfo.md) |
169+
| `Messages.AnswerCallback` | Отправляет ответ после того, как пользователь нажмет кнопку | [AnswerCallback](https://dev.max.ru/docs-api/methods/POST/answers) | [AnswerCallback](./docs/messages/AnswerCallback.md)|

cmd/examples/GetBot/main.go

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package main
2+
3+
import (
4+
"context"
5+
6+
"github.com/rs/zerolog/log"
7+
8+
"github.com/green-api/maxbot-api-client-go/pkg/api"
9+
"github.com/green-api/maxbot-api-client-go/pkg/client"
10+
)
11+
12+
func main() {
13+
bot, err := api.New(client.Config{
14+
BaseURL: "https://platform-api.max.ru",
15+
Token: "YOUR_BOT_TOKEN",
16+
})
17+
if err != nil {
18+
log.Fatal().Err(err).Msg("failed to init MAX API")
19+
}
20+
21+
response, err := bot.Bots.GetBot(context.Background())
22+
if err != nil {
23+
log.Error().Err(err).Msg("GetBot error")
24+
return
25+
}
26+
log.Info().Interface("info", response).Msg("Bot info received")
27+
}

cmd/examples/GetUpdates/main.go

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package main
2+
3+
import (
4+
"context"
5+
6+
"github.com/rs/zerolog/log"
7+
8+
"github.com/green-api/maxbot-api-client-go/pkg/api"
9+
"github.com/green-api/maxbot-api-client-go/pkg/client"
10+
"github.com/green-api/maxbot-api-client-go/pkg/models"
11+
)
12+
13+
func main() {
14+
bot, err := api.New(client.Config{
15+
BaseURL: "https://platform-api.max.ru",
16+
Token: "YOUR_BOT_TOKEN",
17+
})
18+
if err != nil {
19+
log.Fatal().Err(err).Msg("failed to init MAX API")
20+
}
21+
22+
response, err := bot.Subscriptions.GetUpdates(context.Background(), &models.GetUpdatesReq{
23+
Limit: 10,
24+
Timeout: 10,
25+
Types: []models.UpdateType{
26+
"bot_added",
27+
"bot_removed",
28+
"bot_started",
29+
"bot_stopped",
30+
},
31+
})
32+
if err != nil {
33+
log.Error().Msgf("GetUpdates error: %v", err)
34+
}
35+
log.Info().Msgf("New update received: %v", response)
36+
}

cmd/examples/SendFile/main.go

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package main
2+
3+
import (
4+
"context"
5+
6+
"github.com/green-api/maxbot-api-client-go/pkg/api"
7+
"github.com/green-api/maxbot-api-client-go/pkg/client"
8+
"github.com/green-api/maxbot-api-client-go/pkg/models"
9+
"github.com/rs/zerolog/log"
10+
)
11+
12+
func main() {
13+
bot, err := api.New(client.Config{
14+
BaseURL: "https://platform-api.max.ru",
15+
Token: "YOUR_BOT_TOKEN",
16+
})
17+
if err != nil {
18+
log.Fatal().Err(err).Msg("failed to init MAX API")
19+
}
20+
21+
const exampleChatID int64 = 123456789 // recipient user ID
22+
23+
_, err = bot.Helpers.SendFile(context.Background(), models.SendFileReq{
24+
ChatID: exampleChatID,
25+
FileSource: "cmd/examples/assets/file.txt",
26+
})
27+
if err != nil {
28+
log.Error().Err(err).Msg("failed to send local file")
29+
return
30+
}
31+
32+
_, err = bot.Helpers.SendFile(context.Background(), models.SendFileReq{
33+
ChatID: exampleChatID,
34+
FileSource: "https://storage.yandexcloud.net/sw-prod-03-test/ChatBot/corgi.jpg",
35+
})
36+
if err != nil {
37+
log.Error().Err(err).Msg("failed to send file by URL")
38+
}
39+
}

cmd/examples/SendMessage/main.go

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
package main
2+
3+
import (
4+
"context"
5+
6+
"github.com/rs/zerolog/log"
7+
8+
"github.com/green-api/maxbot-api-client-go/pkg/api"
9+
"github.com/green-api/maxbot-api-client-go/pkg/client"
10+
"github.com/green-api/maxbot-api-client-go/pkg/models"
11+
)
12+
13+
func main() {
14+
bot, err := api.New(client.Config{
15+
BaseURL: "https://platform-api.max.ru",
16+
Token: "YOUR_BOT_TOKEN",
17+
})
18+
if err != nil {
19+
log.Fatal().Err(err).Msg("failed to init MAX API")
20+
}
21+
22+
const exampleUserID int64 = 123456789 // recipient user ID
23+
24+
_, err = bot.Messages.SendMessage(context.Background(), models.SendMessageReq{
25+
UserID: exampleUserID,
26+
Text: "Hello world!",
27+
})
28+
if err != nil {
29+
log.Error().Msgf("SendMessage error: %v", err)
30+
}
31+
log.Info().Msgf("SendMessage success!")
32+
}

cmd/examples/UploadFile/main.go

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
package main
2+
3+
import (
4+
"context"
5+
6+
"github.com/rs/zerolog/log"
7+
8+
"github.com/green-api/maxbot-api-client-go/pkg/api"
9+
"github.com/green-api/maxbot-api-client-go/pkg/client"
10+
"github.com/green-api/maxbot-api-client-go/pkg/models"
11+
)
12+
13+
func main() {
14+
bot, err := api.New(client.Config{
15+
BaseURL: "https://platform-api.max.ru",
16+
Token: "YOUR_BOT_TOKEN",
17+
})
18+
if err != nil {
19+
log.Fatal().Err(err).Msg("failed to init MAX API")
20+
}
21+
22+
const exampleUserID int64 = 123456789 // recipient user ID
23+
24+
file, err := bot.Uploads.UploadFile(context.Background(), models.UploadFileReq{
25+
Type: "image",
26+
FilePath: "cmd/examples/assets/file.png",
27+
})
28+
if err != nil {
29+
log.Error().Msgf("UploadFile error: %v", err)
30+
return
31+
}
32+
33+
if file.Token == "" {
34+
log.Warn().Msg("upload success, but file token is empty")
35+
return
36+
}
37+
38+
attachment := models.AttachImage(file.Token, "")
39+
_, err = bot.Messages.SendMessage(context.Background(), models.SendMessageReq{
40+
UserID: exampleUserID,
41+
Attachments: []models.Attachment{attachment},
42+
})
43+
if err != nil {
44+
log.Error().Msgf("Send File Message error: %v", err)
45+
}
46+
log.Info().Msg("File successfully sent to chat!")
47+
}

cmd/examples/assets/file.png

114 KB
Loading

cmd/examples/assets/file.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Sample file for upload testing

0 commit comments

Comments
 (0)