Compare commits
2 Commits
v1.0.0-bet
...
v1.0.0-bet
| Author | SHA1 | Date | |
|---|---|---|---|
|
e4203e8fc0
|
|||
|
c179a3f5f0
|
21
README.md
21
README.md
@@ -124,15 +124,21 @@ func myHandler(ctx *laniakea.MsgContext, db *MyDB) {
|
|||||||
|
|
||||||
Provides access to the incoming message and useful reply methods:
|
Provides access to the incoming message and useful reply methods:
|
||||||
|
|
||||||
- `Answer(text string)`: Sends a plain text message, automatically escaping MarkdownV2.
|
- `Answer(text string) *AnswerMessage`: Sends a message with parse_mode none.
|
||||||
- `AnswerMarkdown(text string)`: Sends a message formatted with MarkdownV2 (you handle escaping).
|
- `AnswerMarkdown(text string) *AnswerMessage`: Sends a message formatted with MarkdownV2 (you handle escaping).
|
||||||
- `AnswerText(text string)`: Sends a message with no parse_mode.
|
- `Keyboard(text string, keyboard *InlineKeyboard) *AnswerMessage`: Sends a message with parse_mode none and inline keyboard.
|
||||||
- `SendChatAction(action string)`: Sends a "typing", "uploading photo", etc., action.
|
- `KeyboardMarkdown(text string, keyboard *InlineKeyboard) *AnswerMessage`: Sends a message formatted with MarkdownV2 (you handle escaping) and inline keyboard.
|
||||||
|
- `AnswerPhoto(photoId, text string) *AnswerMessage`: Sends a message with photo with parse_mode none.
|
||||||
|
- `AnswerPhotoMarkdown(photoId, text string) *AnswerMessage`: Sends a message formatted with MarkdownV2 (you handle escaping) with.
|
||||||
|
- `EditCallback(text string)`: Edits message with parse_mode none after clicking inline button.
|
||||||
|
- `EditCallbackMarkdown(text string)`: Edits a message formatted with MarkdownV2 (you handle escaping) after clicking inline button.
|
||||||
|
- `SendChatAction(action string)`: Sends a “typing”, “uploading photo”, etc., action.
|
||||||
- Fields: `Text`, `Args`, `From`, `Chat`, `Msg`, etc.
|
- Fields: `Text`, `Args`, `From`, `Chat`, `Msg`, etc.
|
||||||
|
- And more methods and fields!
|
||||||
|
|
||||||
### Database Context
|
### Database Context
|
||||||
|
|
||||||
The `T` in `NewBot[T]` is a powerful feature. You can pass any type (like a database connection pool) and it will be available in every command and middleware handler.
|
The `T` in `NewBot[T]` is a powerful feature. You can pass any type (like a database connection pool), and it will be available in every command and middleware handler.
|
||||||
|
|
||||||
```go
|
```go
|
||||||
type MyDB struct { /* ... */ }
|
type MyDB struct { /* ... */ }
|
||||||
@@ -185,16 +191,15 @@ func adminOnlyMiddleware(ctx *laniakea.MsgContext, db *MyDB) bool {
|
|||||||
|
|
||||||
### Important Notes
|
### Important Notes
|
||||||
- Middleware can modify the MsgContext (e.g., add custom fields) before the command runs.
|
- Middleware can modify the MsgContext (e.g., add custom fields) before the command runs.
|
||||||
- If you need to run code after a command, you can call it from within the command itself or use a defer statement inside the middleware that wraps the next call (more advanced).
|
|
||||||
|
|
||||||
## ⚙️ Advanced Configuration
|
## ⚙️ Advanced Configuration
|
||||||
- **Inline Keyboards**: Build keyboards using laniakea.NewKeyboard() and AddRow().
|
- **Inline Keyboards**: Build keyboards using laniakea.NewKeyboard().
|
||||||
- **Rate Limiting**: Pass a configured utils.RateLimiter via BotOpts to handle Telegram's rate limits gracefully.
|
- **Rate Limiting**: Pass a configured utils.RateLimiter via BotOpts to handle Telegram's rate limits gracefully.
|
||||||
- **Custom HTTP Client**: Provide your own http.Client in BotOpts for fine-tuned control.
|
- **Custom HTTP Client**: Provide your own http.Client in BotOpts for fine-tuned control.
|
||||||
|
|
||||||
## 📝 License
|
## 📝 License
|
||||||
|
|
||||||
This project is licensed under the GNU General Public License v3.0 - see the [LICENSE](LICENSE) file for details.
|
This project is licensed under the GNU General Public License v3.0 — see the [LICENSE](LICENSE) file for details.
|
||||||
|
|
||||||
## 📚 Learn More
|
## 📚 Learn More
|
||||||
[GoDoc](https://pkg.go.dev/git.nix13.pw/scuroneko/laniakea)
|
[GoDoc](https://pkg.go.dev/git.nix13.pw/scuroneko/laniakea)
|
||||||
|
|||||||
13
README_RU.md
13
README_RU.md
@@ -124,11 +124,17 @@ func myHandler(ctx *laniakea.MsgContext, db *MyDB) {
|
|||||||
### Контекст сообщения (MsgContext)
|
### Контекст сообщения (MsgContext)
|
||||||
Предоставляет доступ к входящему сообщению и полезные методы для ответа:
|
Предоставляет доступ к входящему сообщению и полезные методы для ответа:
|
||||||
|
|
||||||
- `Answer(text string)`: Отправляет обычный текст, автоматически экранируя MarkdownV2.
|
- `Answer(text string)`: Отправляет сообщение с parse_mode none.
|
||||||
- `AnswerMarkdown(text string)`: Отправляет сообщение, отформатированное MarkdownV2 (экранирование на вашей стороне).
|
- `AnswerMarkdown(text string)`: Отправляет сообщение, отформатированное MarkdownV2 (экранирование на вашей стороне).
|
||||||
- `AnswerText(text string)`: Отправляет сообщение без parse_mode.
|
- `Keyboard(text string, keyboard *InlineKeyboard) *AnswerMessage`: Отправляет сообщение с parse_mode none и Inline клавиатурой.
|
||||||
|
- `KeyboardMarkdown(text string, keyboard *InlineKeyboard) *AnswerMessage`: Отправляет сообщение, отформатированное MarkdownV2 (экранирование на вашей стороне), и Inline клавиатурой.
|
||||||
|
- `AnswerPhoto(photoId, text string) *AnswerMessage`: Отправляет фотографию с подписью и parse_mode none.
|
||||||
|
- `AnswerPhotoMarkdown(photoId, text string) *AnswerMessage`: Отправляет фотографию с подписью, отформатированной MarkdownV2 (экранирование на вашей стороне).
|
||||||
|
- `EditCallback(text string)`: Редактирует сообщение, форматируя его в MarkdownV2 (экранирование на вашей стороне), после нажатия Inline кнопки.
|
||||||
|
- `EditCallbackMarkdown(text string)`: Редактирует сообщение с parse_mode none после нажатия Inline кнопки.
|
||||||
- `SendChatAction(action string)`: Отправляет действие "печатает", "загружает фото" и т.д.
|
- `SendChatAction(action string)`: Отправляет действие "печатает", "загружает фото" и т.д.
|
||||||
- Поля: `Text`, `Args`, `From`, `Chat`, `Msg` и другие.
|
- Поля: `Text`, `Args`, `From`, `Chat`, `Msg` и другие.
|
||||||
|
- И много других методов и полей!
|
||||||
|
|
||||||
### Контекст базы данных (Database Context)
|
### Контекст базы данных (Database Context)
|
||||||
Параметр типа `T` в `NewBot[T]` — мощная функция. Вы можете передать любой тип (например, пул соединений с БД), и он будет доступен в каждом обработчике команды и中间件.
|
Параметр типа `T` в `NewBot[T]` — мощная функция. Вы можете передать любой тип (например, пул соединений с БД), и он будет доступен в каждом обработчике команды и中间件.
|
||||||
@@ -184,10 +190,9 @@ func adminOnlyMiddleware(ctx *laniakea.MsgContext, db *MyDB) bool {
|
|||||||
|
|
||||||
### Важные замечания
|
### Важные замечания
|
||||||
- Middleware может изменять MsgContext (например, добавлять пользовательские поля) перед запуском команды.
|
- Middleware может изменять MsgContext (например, добавлять пользовательские поля) перед запуском команды.
|
||||||
- Если нужно выполнить код после команды, это можно сделать внутри самой команды или использовать отложенный вызов (defer) в middleware, который оборачивает следующий вызов (более продвинутый подход).
|
|
||||||
|
|
||||||
## ⚙️ Расширенная настройка
|
## ⚙️ Расширенная настройка
|
||||||
**Инлайн-клавиатуры**: Создавайте клавиатуры с помощью laniakea.NewKeyboard() и AddRow().
|
**Инлайн-клавиатуры**: Создавайте клавиатуры с помощью laniakea.NewKeyboard().
|
||||||
**Ограничение запросов**: Передайте настроенный utils.RateLimiter через BotOpts для корректной обработки лимитов Telegram.
|
**Ограничение запросов**: Передайте настроенный utils.RateLimiter через BotOpts для корректной обработки лимитов Telegram.
|
||||||
**Пользовательский HTTP-клиент**: Предоставьте свой http.Client в BotOpts для точного контроля.
|
**Пользовательский HTTP-клиент**: Предоставьте свой http.Client в BotOpts для точного контроля.
|
||||||
|
|
||||||
|
|||||||
1
bot.go
1
bot.go
@@ -257,6 +257,7 @@ func NewBot[T any](opts *BotOpts) *Bot[T] {
|
|||||||
bot := &Bot[T]{
|
bot := &Bot[T]{
|
||||||
updateOffset: 0,
|
updateOffset: 0,
|
||||||
errorTemplate: "%s",
|
errorTemplate: "%s",
|
||||||
|
payloadType: BotPayloadBase64,
|
||||||
updateQueue: updateQueue,
|
updateQueue: updateQueue,
|
||||||
api: api,
|
api: api,
|
||||||
uploader: uploader,
|
uploader: uploader,
|
||||||
|
|||||||
@@ -1,7 +0,0 @@
|
|||||||
TG_TOKEN=
|
|
||||||
PREFIXES=/;!
|
|
||||||
DEBUG=true
|
|
||||||
USE_REQ_LOG=true
|
|
||||||
WRITE_TO_FILE=false
|
|
||||||
USE_TEST_SERVER=true
|
|
||||||
API_URL=http://127.0.0.1:8081
|
|
||||||
@@ -1,30 +0,0 @@
|
|||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"log"
|
|
||||||
|
|
||||||
"git.nix13.pw/scuroneko/laniakea"
|
|
||||||
)
|
|
||||||
|
|
||||||
func echo(ctx *laniakea.MsgContext, db *laniakea.NoDB) {
|
|
||||||
ctx.Answer(ctx.Text) // User input WITHOUT command
|
|
||||||
}
|
|
||||||
|
|
||||||
func main() {
|
|
||||||
opts := &laniakea.BotOpts{Token: "TOKEN"}
|
|
||||||
bot := laniakea.NewBot[laniakea.NoDB](opts)
|
|
||||||
defer bot.Close()
|
|
||||||
|
|
||||||
p := laniakea.NewPlugin[laniakea.NoDB]("ping")
|
|
||||||
p.AddCommand(p.NewCommand(echo, "echo"))
|
|
||||||
p.AddCommand(p.NewCommand(func(ctx *laniakea.MsgContext, db *laniakea.NoDB) {
|
|
||||||
ctx.Answer("Pong")
|
|
||||||
}, "ping"))
|
|
||||||
|
|
||||||
bot = bot.ErrorTemplate("Error\n\n%s").AddPlugins(p)
|
|
||||||
|
|
||||||
if err := bot.AutoGenerateCommands(); err != nil {
|
|
||||||
log.Println(err)
|
|
||||||
}
|
|
||||||
bot.Run()
|
|
||||||
}
|
|
||||||
@@ -1,20 +0,0 @@
|
|||||||
module example/basic
|
|
||||||
|
|
||||||
go 1.26.1
|
|
||||||
|
|
||||||
require git.nix13.pw/scuroneko/laniakea v1.0.0-beta.14
|
|
||||||
|
|
||||||
replace (
|
|
||||||
git.nix13.pw/scuroneko/laniakea v1.0.0-beta.14 => ../../
|
|
||||||
)
|
|
||||||
|
|
||||||
require (
|
|
||||||
git.nix13.pw/scuroneko/extypes v1.2.1 // indirect
|
|
||||||
git.nix13.pw/scuroneko/slog v1.0.2 // indirect
|
|
||||||
github.com/alitto/pond/v2 v2.7.0 // indirect
|
|
||||||
github.com/fatih/color v1.18.0 // indirect
|
|
||||||
github.com/mattn/go-colorable v0.1.14 // indirect
|
|
||||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
|
||||||
golang.org/x/sys v0.42.0 // indirect
|
|
||||||
golang.org/x/time v0.15.0 // indirect
|
|
||||||
)
|
|
||||||
@@ -1,19 +0,0 @@
|
|||||||
git.nix13.pw/scuroneko/extypes v1.2.1 h1:IYrOjnWKL2EAuJYtYNa+luB1vBe6paE8VY/YD+5/RpQ=
|
|
||||||
git.nix13.pw/scuroneko/extypes v1.2.1/go.mod h1:uZVs8Yo3RrYAG9dMad6qR6lsYY67t+459D9c65QAYAw=
|
|
||||||
git.nix13.pw/scuroneko/laniakea v1.0.0-beta.13 h1:mRVxYh7CNrm8ccob+u6XxLzZRbs1fLNRg/nXaXY78yw=
|
|
||||||
git.nix13.pw/scuroneko/laniakea v1.0.0-beta.13/go.mod h1:M8jwm195hzAl9bj9Bkl95WfHmWvuBX6micsdtOs/gmE=
|
|
||||||
git.nix13.pw/scuroneko/slog v1.0.2 h1:vZyUROygxC2d5FJHUQM/30xFEHY1JT/aweDZXA4rm2g=
|
|
||||||
git.nix13.pw/scuroneko/slog v1.0.2/go.mod h1:3Qm2wzkR5KjwOponMfG7TcGSDjmYaFqRAmLvSPTuWJI=
|
|
||||||
github.com/alitto/pond/v2 v2.7.0 h1:c76L+yN916m/DRXjGCeUBHHu92uWnh/g1bwVk4zyyXg=
|
|
||||||
github.com/alitto/pond/v2 v2.7.0/go.mod h1:xkjYEgQ05RSpWdfSd1nM3OVv7TBhLdy7rMp3+2Nq+yE=
|
|
||||||
github.com/fatih/color v1.18.0 h1:S8gINlzdQ840/4pfAwic/ZE0djQEH3wM94VfqLTZcOM=
|
|
||||||
github.com/fatih/color v1.18.0/go.mod h1:4FelSpRwEGDpQ12mAdzqdOukCy4u8WUtOY6lkT/6HfU=
|
|
||||||
github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE=
|
|
||||||
github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
|
|
||||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
|
||||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
|
||||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
|
||||||
golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo=
|
|
||||||
golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
|
||||||
golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U=
|
|
||||||
golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno=
|
|
||||||
14
handler.go
14
handler.go
@@ -148,13 +148,6 @@ func encodeBase64Payload(d CallbackData) (string, error) {
|
|||||||
base64.StdEncoding.Encode(dst, []byte(data))
|
base64.StdEncoding.Encode(dst, []byte(data))
|
||||||
return string(dst), nil
|
return string(dst), nil
|
||||||
}
|
}
|
||||||
func decodeBase64Payload(s string) (CallbackData, error) {
|
|
||||||
b, err := base64.StdEncoding.DecodeString(s)
|
|
||||||
if err != nil {
|
|
||||||
return CallbackData{}, err
|
|
||||||
}
|
|
||||||
return decodeJsonPayload(string(b))
|
|
||||||
}
|
|
||||||
|
|
||||||
// func encodePayload(payloadType BotPayloadType, d CallbackData) (string, error) {
|
// func encodePayload(payloadType BotPayloadType, d CallbackData) (string, error) {
|
||||||
// switch payloadType {
|
// switch payloadType {
|
||||||
@@ -165,6 +158,13 @@ func decodeBase64Payload(s string) (CallbackData, error) {
|
|||||||
// }
|
// }
|
||||||
// return "", ErrInvalidPayloadType
|
// return "", ErrInvalidPayloadType
|
||||||
// }
|
// }
|
||||||
|
func decodeBase64Payload(s string) (CallbackData, error) {
|
||||||
|
b, err := base64.StdEncoding.DecodeString(s)
|
||||||
|
if err != nil {
|
||||||
|
return CallbackData{}, err
|
||||||
|
}
|
||||||
|
return decodeJsonPayload(string(b))
|
||||||
|
}
|
||||||
func decodePayload(payloadType BotPayloadType, s string) (CallbackData, error) {
|
func decodePayload(payloadType BotPayloadType, s string) (CallbackData, error) {
|
||||||
switch payloadType {
|
switch payloadType {
|
||||||
case BotPayloadBase64:
|
case BotPayloadBase64:
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
package utils
|
package utils
|
||||||
|
|
||||||
const (
|
const (
|
||||||
VersionString = "1.0.0-beta.15"
|
VersionString = "1.0.0-beta.17"
|
||||||
VersionMajor = 1
|
VersionMajor = 1
|
||||||
VersionMinor = 0
|
VersionMinor = 0
|
||||||
VersionPatch = 0
|
VersionPatch = 0
|
||||||
VersionBeta = 15
|
VersionBeta = 17
|
||||||
)
|
)
|
||||||
|
|||||||
Reference in New Issue
Block a user