copy from 537c005

This commit is contained in:
Кобелев Андрей Андреевич
2022-06-03 11:47:26 +03:00
commit f86a67eb8f
36 changed files with 10747 additions and 0 deletions

View File

@ -0,0 +1,109 @@
# Getting Started
This library is designed as a simple wrapper around the Telegram Bot API.
It's encouraged to read [Telegram's docs][telegram-docs] first to get an
understanding of what Bots are capable of doing. They also provide some good
approaches to solve common problems.
[telegram-docs]: https://core.telegram.org/bots
## Installing
```bash
go get -u github.com/go-telegram-bot-api/telegram-bot-api/v5
```
## A Simple Bot
To walk through the basics, let's create a simple echo bot that replies to your
messages repeating what you said. Make sure you get an API token from
[@Botfather][botfather] before continuing.
Let's start by constructing a new [BotAPI][bot-api-docs].
[botfather]: https://t.me/Botfather
[bot-api-docs]: https://pkg.go.dev/github.com/go-telegram-bot-api/telegram-bot-api/v5?tab=doc#BotAPI
```go
package main
import (
"os"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
)
func main() {
bot, err := tgbotapi.NewBotAPI(os.Getenv("TELEGRAM_APITOKEN"))
if err != nil {
panic(err)
}
bot.Debug = true
}
```
Instead of typing the API token directly into the file, we're using
environment variables. This makes it easy to configure our Bot to use the right
account and prevents us from leaking our real token into the world. Anyone with
your token can send and receive messages from your Bot!
We've also set `bot.Debug = true` in order to get more information about the
requests being sent to Telegram. If you run the example above, you'll see
information about a request to the [`getMe`][get-me] endpoint. The library
automatically calls this to ensure your token is working as expected. It also
fills in the `Self` field in your `BotAPI` struct with information about the
Bot.
Now that we've connected to Telegram, let's start getting updates and doing
things. We can add this code in right after the line enabling debug mode.
[get-me]: https://core.telegram.org/bots/api#getme
```go
// Create a new UpdateConfig struct with an offset of 0. Offsets are used
// to make sure Telegram knows we've handled previous values and we don't
// need them repeated.
updateConfig := tgbotapi.NewUpdate(0)
// Tell Telegram we should wait up to 30 seconds on each request for an
// update. This way we can get information just as quickly as making many
// frequent requests without having to send nearly as many.
updateConfig.Timeout = 30
// Start polling Telegram for updates.
updates := bot.GetUpdatesChan(updateConfig)
// Let's go through each update that we're getting from Telegram.
for update := range updates {
// Telegram can send many types of updates depending on what your Bot
// is up to. We only want to look at messages for now, so we can
// discard any other updates.
if update.Message == nil {
continue
}
// Now that we know we've gotten a new message, we can construct a
// reply! We'll take the Chat ID and Text from the incoming message
// and use it to create a new message.
msg := tgbotapi.NewMessage(update.Message.Chat.ID, update.Message.Text)
// We'll also say that this message is a reply to the previous message.
// For any other specifications than Chat ID or Text, you'll need to
// set fields on the `MessageConfig`.
msg.ReplyToMessageID = update.Message.MessageID
// Okay, we're sending our message off! We don't care about the message
// we just sent, so we'll discard it.
if _, err := bot.Send(msg); err != nil {
// Note that panics are a bad way to handle errors. Telegram can
// have service outages or network errors, you should retry sending
// messages or more gracefully handle failures.
panic(err)
}
}
```
Congradulations! You've made your very own bot!
Now that you've got some of the basics down, we can start talking about how the
library is structured and more advanced features.

View File

@ -0,0 +1,68 @@
# Files
Telegram supports specifying files in many different formats. In order to
accommodate them all, there are multiple structs and type aliases required.
All of these types implement the `RequestFileData` interface.
| Type | Description |
| ------------ | ------------------------------------------------------------------------- |
| `FilePath` | A local path to a file |
| `FileID` | Existing file ID on Telegram's servers |
| `FileURL` | URL to file, must be served with expected MIME type |
| `FileReader` | Use an `io.Reader` to provide a file. Lazily read to save memory. |
| `FileBytes` | `[]byte` containing file data. Prefer to use `FileReader` to save memory. |
## `FilePath`
A path to a local file.
```go
file := tgbotapi.FilePath("tests/image.jpg")
```
## `FileID`
An ID previously uploaded to Telegram. IDs may only be reused by the same bot
that received them. Additionally, thumbnail IDs cannot be reused.
```go
file := tgbotapi.FileID("AgACAgIAAxkDAALesF8dCjAAAa_…")
```
## `FileURL`
A URL to an existing resource. It must be served with a correct MIME type to
work as expected.
```go
file := tgbotapi.FileURL("https://i.imgur.com/unQLJIb.jpg")
```
## `FileReader`
Use an `io.Reader` to provide file contents as needed. Requires a filename for
the virtual file.
```go
var reader io.Reader
file := tgbotapi.FileReader{
Name: "image.jpg",
Reader: reader,
}
```
## `FileBytes`
Use a `[]byte` to provide file contents. Generally try to avoid this as it
results in high memory usage. Also requires a filename for the virtual file.
```go
var data []byte
file := tgbotapi.FileBytes{
Name: "image.jpg",
Bytes: data,
}
```

View File

@ -0,0 +1,56 @@
# Important Notes
The Telegram Bot API has a few potentially unanticipated behaviors. Here are a
few of them. If any behavior was surprising to you, please feel free to open a
pull request!
## Callback Queries
- Every callback query must be answered, even if there is nothing to display to
the user. Failure to do so will show a loading icon on the keyboard until the
operation times out.
## ChatMemberUpdated
- In order to receive `ChatMember` updates, you must explicitly add
`UpdateTypeChatMember` to your `AllowedUpdates` when getting updates or
setting your webhook.
## Entities use UTF16
- When extracting text entities using offsets and lengths, characters can appear
to be in incorrect positions. This is because Telegram uses UTF16 lengths
while Golang uses UTF8. It's possible to convert between the two, see
[issue #231][issue-231] for more details.
[issue-231]: https://github.com/go-telegram-bot-api/telegram-bot-api/issues/231
## GetUpdatesChan
- This method is very basic and likely unsuitable for production use. Consider
creating your own implementation instead, as it's very simple to replicate.
- This method only allows your bot to process one update at a time. You can
spawn goroutines to handle updates concurrently or switch to webhooks instead.
Webhooks are suggested for high traffic bots.
## Nil Updates
- At most one of the fields in an `Update` will be set to a non-nil value. When
evaluating updates, you must make sure you check that the field is not nil
before trying to access any of it's fields.
## Privacy Mode
- By default, bots only get updates directly addressed to them. If you need to
get all messages, you must disable privacy mode with Botfather. Bots already
added to groups will need to be removed and readded for the changes to take
effect. You can read more on the [Telegram Bot API docs][api-docs].
[api-docs]: https://core.telegram.org/bots/faq#what-messages-will-my-bot-get
## User and Chat ID size
- These types require up to 52 significant bits to store correctly, making a
64-bit integer type required in most languages. They are already `int64` types
in this library, but make sure you use correct types when saving them to a
database or passing them to another language.

View File

@ -0,0 +1,37 @@
# Library Structure
This library is generally broken into three components you need to understand.
## Configs
Configs are collections of fields related to a single request. For example, if
one wanted to use the `sendMessage` endpoint, you could use the `MessageConfig`
struct to configure the request. There is a one-to-one relationship between
Telegram endpoints and configs. They generally have the naming pattern of
removing the `send` prefix and they all end with the `Config` suffix. They
generally implement the `Chattable` interface. If they can send files, they
implement the `Fileable` interface.
## Helpers
Helpers are easier ways of constructing common Configs. Instead of having to
create a `MessageConfig` struct and remember to set the `ChatID` and `Text`,
you can use the `NewMessage` helper method. It takes the two required parameters
for the request to succeed. You can then set fields on the resulting
`MessageConfig` after it's creation. They are generally named the same as
method names except with `send` replaced with `New`.
## Methods
Methods are used to send Configs after they are constructed. Generally,
`Request` is the lowest level method you'll have to call. It accepts a
`Chattable` parameter and knows how to upload files if needed. It returns an
`APIResponse`, the most general return type from the Bot API. This method is
called for any endpoint that doesn't have a more specific return type. For
example, `setWebhook` only returns `true` or an error. Other methods may have
more specific return types. The `getFile` endpoint returns a `File`. Almost
every other method returns a `Message`, which you can use `Send` to obtain.
There's lower level methods such as `MakeRequest` which require an endpoint and
parameters instead of accepting configs. These are primarily used internally.
If you find yourself having to use them, please open an issue.