Files
Media-download-telegram-bot/internal/tg/api.go
T
MichilisandClaude Opus 5.5 6843053582 Phase 1: quick flow fixes
- One message per job: the status message is deleted once the file is
  sent, or shortened to "Sent." when Telegram keeps it.
- No reply quotes in private chats; groups keep them.
- Queue status only mentions the position when the wait is above
  QUEUE_NOTICE_THRESHOLD_SECONDS or somebody is ahead. Status edits are
  throttled to one per 2.5 s per message; a state that arrives too soon
  is shown later instead of dropped. The wait estimate is 0 with a free
  slot.
- Caption with title (uploader and date when generic), uploader,
  duration, a short source link without tracking parameters and an
  optional "via @bot" line (CAPTION_ATTRIBUTION). Uploaded videos get a
  320 px JPEG thumbnail; merged MP4s are written with faststart.
- Buttons under the result: Audio (MP3), Other quality, Thumbnail,
  Delete. Requester only in groups.
- Language resolved once per update and passed in the context. A
  fallback to English is logged as a bug; a test walks every screen in
  Spanish and Dutch. Language picker on the first /start.
- Sizes without a zero decimal ("50 MB").
- First link of a new user shows the card once and sets the default to
  "best that fits my limit".
- Errors offer the next step (Try again, Smaller quality, Upgrade, Open
  app); passing lookup failures are retried once.
- Up to MULTI_LINK_MAX links per message; a link sent a moment ago gets
  "already sent" with a Send again button.
- Mini App menu button, labelled per private chat in the user's
  language.
- Personal /settings in private chats with an "Add me to a group"
  button.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 20:08:58 +00:00

143 lines
5.4 KiB
Go

// Package tg holds the bot's view of the Telegram Bot API.
package tg
import (
"context"
"errors"
"net/http"
"strings"
"time"
"github.com/mymmrac/telego"
ta "github.com/mymmrac/telego/telegoapi"
)
// API is the subset of the Bot API the bot uses. *telego.Bot implements it.
// Keeping it narrow documents the surface and lets wrappers add rate
// limiting or metrics.
type API interface {
GetMe(ctx context.Context) (*telego.User, error)
SendMessage(ctx context.Context, params *telego.SendMessageParams) (*telego.Message, error)
SendPhoto(ctx context.Context, params *telego.SendPhotoParams) (*telego.Message, error)
SendVideo(ctx context.Context, params *telego.SendVideoParams) (*telego.Message, error)
SendAudio(ctx context.Context, params *telego.SendAudioParams) (*telego.Message, error)
SendDocument(ctx context.Context, params *telego.SendDocumentParams) (*telego.Message, error)
SendChatAction(ctx context.Context, params *telego.SendChatActionParams) error
EditMessageText(ctx context.Context, params *telego.EditMessageTextParams) (*telego.Message, error)
EditMessageCaption(ctx context.Context, params *telego.EditMessageCaptionParams) (*telego.Message, error)
DeleteMessage(ctx context.Context, params *telego.DeleteMessageParams) error
AnswerCallbackQuery(ctx context.Context, params *telego.AnswerCallbackQueryParams) error
SetMyCommands(ctx context.Context, params *telego.SetMyCommandsParams) error
DeleteMyCommands(ctx context.Context, params *telego.DeleteMyCommandsParams) error
SetMyName(ctx context.Context, params *telego.SetMyNameParams) error
SetMyDescription(ctx context.Context, params *telego.SetMyDescriptionParams) error
SetMyShortDescription(ctx context.Context, params *telego.SetMyShortDescriptionParams) error
SendWidget(ctx context.Context, params *telego.SendWidgetParams) (*telego.Message, error)
EditMessageWidgetData(ctx context.Context, params *telego.EditMessageWidgetDataParams) error
AnswerWidgetQuery(ctx context.Context, params *telego.AnswerWidgetQueryParams) error
GetChatMember(ctx context.Context, params *telego.GetChatMemberParams) (telego.ChatMember, error)
SetChatMenuButton(ctx context.Context, params *telego.SetChatMenuButtonParams) error
}
var _ API = (*telego.Bot)(nil)
// NewBot creates the telego client. net/http is used instead of the default
// fasthttp client because uploads are streamed and can run for minutes.
func NewBot(token, apiURL string) (*telego.Bot, error) {
opts := []telego.BotOption{
telego.WithDiscardLogger(), // telego logs full request URLs, which contain the token
telego.WithHTTPClient(&http.Client{
Transport: &http.Transport{
Proxy: http.ProxyFromEnvironment,
MaxIdleConns: 64,
MaxIdleConnsPerHost: 32,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 15 * time.Second,
ResponseHeaderTimeout: 0, // large uploads answer late
},
}),
}
if apiURL != "" {
opts = append(opts, telego.WithAPIServer(strings.TrimRight(apiURL, "/")))
}
return telego.NewBot(token, opts...)
}
// ErrorCode returns the Bot API error code of err, or 0.
func ErrorCode(err error) int {
var apiErr *ta.Error
if errors.As(err, &apiErr) {
return apiErr.ErrorCode
}
return 0
}
// Description returns the Bot API error description of err in lower case,
// or "".
func Description(err error) string {
var apiErr *ta.Error
if errors.As(err, &apiErr) {
return strings.ToLower(apiErr.Description)
}
return ""
}
// IsNotModified reports the harmless error Telegram returns when an edit
// does not change anything.
func IsNotModified(err error) bool {
return strings.Contains(Description(err), "message is not modified")
}
// IsMessageGone reports that the target message no longer exists or can no
// longer be edited.
func IsMessageGone(err error) bool {
d := Description(err)
return strings.Contains(d, "message to edit not found") ||
strings.Contains(d, "message can't be edited") ||
strings.Contains(d, "message to delete not found")
}
// IsBlocked reports that the bot can no longer write to the chat.
func IsBlocked(err error) bool {
if ErrorCode(err) == 403 {
return true
}
d := Description(err)
return strings.Contains(d, "chat not found") || strings.Contains(d, "bot was blocked") ||
strings.Contains(d, "user is deactivated") || strings.Contains(d, "bot was kicked")
}
// IsFileTooBig reports that Telegram refused an upload for its size.
func IsFileTooBig(err error) bool {
return ErrorCode(err) == 413 || strings.Contains(Description(err), "too large") ||
strings.Contains(Description(err), "too big")
}
// RetryAfter returns the flood wait Telegram asked for, or 0.
func RetryAfter(err error) time.Duration {
var apiErr *ta.Error
if errors.As(err, &apiErr) && apiErr.Parameters != nil && apiErr.Parameters.RetryAfter > 0 {
return time.Duration(apiErr.Parameters.RetryAfter) * time.Second
}
return 0
}
// IsBadFileID reports that Telegram no longer accepts a file_id: it was
// issued for another bot, the file was removed, or the reference expired.
// The cache treats this as "layer 1 is gone" and falls back.
func IsBadFileID(err error) bool {
if ErrorCode(err) != 400 {
return false
}
d := Description(err)
for _, needle := range []string{
"wrong file identifier", "wrong remote file", "file reference", "invalid file",
"wrong file_id", "file_id", "wrong type of the web page content", "file is temporarily unavailable",
} {
if strings.Contains(d, needle) {
return true
}
}
return false
}