commit ac7cae8fa70e246edcc463af81ee3425abde95bd Author: Lukasz Raczylo Date: Sat May 9 13:09:27 2026 +0100 Initial release of go-telegram A fully-generated, strongly-typed Go client for the Telegram Bot API. * 176 methods + 301 types generated from Bot API v10.0 * 1408 auto-generated tests (8 scenarios per method) * Typed unions throughout — no 'any' in the public surface * Pluggable HTTP transport and JSON codec (default goccy/go-json) * Built-in retry middleware honouring Telegram's retry_after * Generic dispatcher with filters and conversation handlers * Self-verifying codegen pipeline (regen → audit → emit → run tests) * 14 example bots covering common patterns diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..5478281 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,274 @@ +name: ci + +on: + push: + branches: [main] + pull_request: + workflow_dispatch: + inputs: + dry-run-release: + description: "Compute release version, do not tag or release" + type: boolean + default: false + +permissions: + contents: write + pull-requests: read + packages: write + +# Cancel any in-flight CI runs for the same branch when a new push lands. +concurrency: + group: ci-${{ github.ref }} + cancel-in-progress: true + +jobs: + vet: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-go@v5 + with: + go-version: '1.25.x' + check-latest: true + - uses: actions/cache@v4 + with: + path: | + ~/go/pkg/mod + ~/.cache/go-build + key: ${{ runner.os }}-go-1.25-${{ hashFiles('**/go.sum') }} + - run: go vet ./... + + staticcheck: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-go@v5 + with: + go-version: '1.25.x' + check-latest: true + - uses: actions/cache@v4 + with: + path: | + ~/go/pkg/mod + ~/.cache/go-build + key: ${{ runner.os }}-go-1.25-${{ hashFiles('**/go.sum') }} + - run: go install honnef.co/go/tools/cmd/staticcheck@v0.7.0 + - run: staticcheck ./... + + govulncheck: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-go@v5 + with: + go-version: '1.25.x' + check-latest: true + - uses: actions/cache@v4 + with: + path: | + ~/go/pkg/mod + ~/.cache/go-build + key: ${{ runner.os }}-go-1.25-${{ hashFiles('**/go.sum') }} + - run: go install golang.org/x/vuln/cmd/govulncheck@latest + - run: govulncheck ./... + + gosec: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-go@v5 + with: + go-version: '1.25.x' + check-latest: true + - uses: actions/cache@v4 + with: + path: | + ~/go/pkg/mod + ~/.cache/go-build + key: ${{ runner.os }}-go-1.25-${{ hashFiles('**/go.sum') }} + - run: go install github.com/securego/gosec/v2/cmd/gosec@latest + # G404: math/rand/v2 jitter in transport/backoff.go — intentional (not crypto) + # G304: os.ReadFile from CLI flag variable — intentional (tool, not server) + # G306: 0o644 on generated doc artifacts in cmd/scrape — intentional + # G204: git subprocess in cmd/audit uses CLI flag path — intentional (operator tool) + # G706: log.Printf with values from Telegram/env in examples — illustrative, + # library users are expected to sanitise before logging in production + - run: gosec -quiet -exclude=G404,G304,G306,G204,G706 -exclude-dir=testdata ./... + + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-go@v5 + with: + go-version: '1.25.x' + check-latest: true + - uses: actions/cache@v4 + with: + path: | + ~/go/pkg/mod + ~/.cache/go-build + key: ${{ runner.os }}-go-1.25-${{ hashFiles('**/go.sum') }} + - run: go test -race -coverprofile=coverage.out ./... + - name: Build all examples + run: go build ./examples/... + - uses: actions/upload-artifact@v4 + with: + name: coverage + path: coverage.out + + codegen-clean: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-go@v5 + with: + go-version: '1.25.x' + check-latest: true + - uses: actions/cache@v4 + with: + path: | + ~/go/pkg/mod + ~/.cache/go-build + key: ${{ runner.os }}-go-1.25-${{ hashFiles('**/go.sum') }} + - name: Regenerate against pinned snapshot + run: make regen-from-fixture + - name: Assert clean diff + run: git diff --exit-code internal/spec/api.json api/ + + audit: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 # need history for drift comparison + - uses: actions/setup-go@v5 + with: + go-version: '1.25.x' + check-latest: true + - uses: actions/cache@v4 + with: + path: | + ~/go/pkg/mod + ~/.cache/go-build + key: ${{ runner.os }}-go-1.25-${{ hashFiles('**/go.sum') }} + - name: Audit fallbacks + run: make audit + - name: Audit drift vs base + # On PRs: compare against the merge base (origin/). + # On push to main: compare against the parent commit. + # Drift is informational; doesn't fail CI. + run: | + if [ "${{ github.event_name }}" = "pull_request" ]; then + BASE="origin/${{ github.base_ref }}" + else + BASE="HEAD~1" + fi + echo "Drift base: $BASE" + go run ./cmd/audit -ir internal/spec/api.json -drift -against "$BASE" || true + + # Aggregate gate — depends on every check above. Used as a single + # required status check in branch protection AND as a dependency for the + # release job below. + ci-success: + runs-on: ubuntu-latest + needs: [vet, staticcheck, govulncheck, gosec, test, codegen-clean, audit] + if: always() + steps: + - name: All checks passed + if: ${{ !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') }} + run: echo "ci-success" + - name: At least one check failed + if: ${{ contains(needs.*.result, 'failure') || contains(needs.*.result, 'cancelled') }} + run: | + echo "Failed/cancelled jobs:" + echo '${{ toJSON(needs) }}' + exit 1 + + # Auto-release fires on every clean push to main (and on manual + # workflow_dispatch for testing). Computes next SemVer from commit + # history via lukaszraczylo/semver-generator, dual-tags + # (v + bot-api-v), runs GoReleaser. + release: + needs: ci-success + if: | + (github.event_name == 'push' && github.ref == 'refs/heads/main') || + github.event_name == 'workflow_dispatch' + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - uses: actions/setup-go@v5 + with: + go-version: '1.25.x' + check-latest: true + + # Action interface from + # https://github.com/lukaszraczylo/semver-generator/blob/main/action.yml + # Inputs: repository_local: true (use already-cloned repo) + # existing: true (respect existing tags as base) + # Output: semantic_version (bare version string, no "v" prefix) + - name: Compute next SemVer + id: semver + uses: lukaszraczylo/semver-generator@v1 + with: + repository_local: true + existing: true + config_file: .semver.yaml + + - name: Read Bot API version + id: api_version + run: | + VERSION=$(python3 -c 'import json; print(json.load(open("internal/spec/api.json"))["version"])') + if [ -z "$VERSION" ] || [ "$VERSION" = "null" ]; then + echo "tag=" >> "$GITHUB_OUTPUT" + else + echo "tag=bot-api-v${VERSION}" >> "$GITHUB_OUTPUT" + fi + echo "version=$VERSION" >> "$GITHUB_OUTPUT" + + - name: Dry-run summary + if: github.event_name == 'workflow_dispatch' && inputs.dry-run-release == true + run: | + echo "Would release: v${{ steps.semver.outputs.semantic_version }}" + if [ -n "${{ steps.api_version.outputs.tag }}" ]; then + echo "Would also tag: ${{ steps.api_version.outputs.tag }} (Bot API ${{ steps.api_version.outputs.version }})" + fi + echo "Skipping tag + release (dry-run)." + + - name: Tag library + bot-api versions + if: github.event_name != 'workflow_dispatch' || inputs.dry-run-release == false + env: + LIB_TAG: v${{ steps.semver.outputs.semantic_version }} + API_TAG: ${{ steps.api_version.outputs.tag }} + API_VER: ${{ steps.api_version.outputs.version }} + run: | + git config user.name "github-actions[bot]" + git config user.email "github-actions[bot]@users.noreply.github.com" + git tag -a "$LIB_TAG" -m "Release $LIB_TAG" + git push origin "$LIB_TAG" + + if [ -n "$API_TAG" ]; then + # Force-update the bot-api tag so it always points at the latest + # release that supports that API version. + if git rev-parse "$API_TAG" >/dev/null 2>&1; then + git tag -f -a "$API_TAG" -m "go-telegram release $LIB_TAG (Bot API $API_VER)" + git push -f origin "$API_TAG" + else + git tag -a "$API_TAG" -m "go-telegram release $LIB_TAG (Bot API $API_VER)" + git push origin "$API_TAG" + fi + fi + + - name: Run GoReleaser + if: github.event_name != 'workflow_dispatch' || inputs.dry-run-release == false + uses: goreleaser/goreleaser-action@v6 + with: + distribution: goreleaser + version: '~> v2' + args: release --clean + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + BOT_API_VERSION: ${{ steps.api_version.outputs.version }} diff --git a/.github/workflows/regen.yml b/.github/workflows/regen.yml new file mode 100644 index 0000000..4a561ca --- /dev/null +++ b/.github/workflows/regen.yml @@ -0,0 +1,118 @@ +name: regen + +on: + schedule: + - cron: "0 6 * * 1" # Monday 06:00 UTC + workflow_dispatch: {} + +permissions: + contents: write + pull-requests: write + +jobs: + regen: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 # full history so audit -drift can compare against main + + - name: Set up Go + uses: actions/setup-go@v5 + with: + go-version: '1.25.x' + check-latest: true + + - name: Capture latest snapshot + id: snapshot + run: | + DATE=$(date +%Y-%m-%d) + DEST="testdata/html/snapshot_${DATE}.html" + curl -fsSL --user-agent "go-telegram codegen scraper" \ + https://core.telegram.org/bots/api > "$DEST" + ln -sf "snapshot_${DATE}.html" testdata/html/latest.html + echo "date=$DATE" >> $GITHUB_OUTPUT + echo "dest=$DEST" >> $GITHUB_OUTPUT + + - name: Regenerate (scrape + emit, with clean-generated) + # `make regen` depends on `clean-generated`, which sweeps any orphan + # api/*.gen.go files left behind by removed/renamed methods. + run: make regen + + - name: Audit fallbacks + id: audit + run: | + set +e + OUT=$(make audit 2>&1) + STATUS=$? + set -e + echo "$OUT" + { + echo 'output<> $GITHUB_OUTPUT + echo "status=$STATUS" >> $GITHUB_OUTPUT + # Don't fail the workflow on fallbacks — surface them in the PR body so + # the reviewer can extend overrides.json or fix scraper patterns. + + - name: Audit drift vs main + id: drift + run: | + set +e + DRIFT=$(go run ./cmd/audit -ir internal/spec/api.json -drift -against origin/main 2>&1) + set -e + echo "$DRIFT" + { + echo 'output<> $GITHUB_OUTPUT + + - name: Run tests + run: go test -race ./... + + - name: Detect changes + id: diff + run: | + git status --porcelain + if git diff --quiet internal/spec/api.json api/ testdata/html/; then + echo "no_changes=true" >> $GITHUB_OUTPUT + fi + + - name: Read API version + if: steps.diff.outputs.no_changes != 'true' + id: meta + run: | + VERSION=$(python3 -c 'import json; print(json.load(open("internal/spec/api.json")).get("version", "unknown"))') + echo "version=$VERSION" >> $GITHUB_OUTPUT + + - name: Open PR + if: steps.diff.outputs.no_changes != 'true' + uses: peter-evans/create-pull-request@v7 + with: + token: ${{ secrets.GITHUB_TOKEN }} + commit-message: | + chore(api): regenerate from Telegram Bot API v${{ steps.meta.outputs.version }} + branch: regen/api-v${{ steps.meta.outputs.version }} + title: "chore(api): regenerate from Telegram Bot API v${{ steps.meta.outputs.version }}" + labels: automated, api-update + body: | + Automated regeneration from `https://core.telegram.org/bots/api`. + + **API version:** v${{ steps.meta.outputs.version }} + **Snapshot date:** ${{ steps.snapshot.outputs.date }} + + ## Audit (fallbacks) + ``` + ${{ steps.audit.outputs.output }} + ``` + + ## Drift vs `main` + ``` + ${{ steps.drift.outputs.output }} + ``` + + Inspect the IR diff (`internal/spec/api.json`) for added/changed/removed methods. + + CI must pass before merge. Auto-merge: enable when satisfied with the diff. diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..0257a3a --- /dev/null +++ b/.gitignore @@ -0,0 +1,45 @@ +# Binaries +/bin/ +*.exe +*.dll +*.so +*.dylib + +# Test artifacts +*.test +*.out +coverage.out +coverage.html + +# IDE +.idea/ +.vscode/ +*.swp +*~ + +# OS +.DS_Store + +# Local env +.env +.env.local + +# Stray binaries at repo root from `go build ./cmd/...` or `go run` artefacts. +# Listed explicitly (not via /* glob) so source dirs are never accidentally ignored. +/echo +/webhook +/genapi +/scrape +/audit +/callback +/conversation +/files +/inline +/middleware +/stateful +/admin +/moderation +/pagination +/payments +/polls +/welcome diff --git a/.golangci.yml b/.golangci.yml new file mode 100644 index 0000000..ac7b3e4 --- /dev/null +++ b/.golangci.yml @@ -0,0 +1,72 @@ +version: "2" + +linters: + default: none + enable: + - govet + - staticcheck + - unused + - errcheck + - gosec + + settings: + unused: + field-writes-are-uses: true + post-statements-are-reads: true + exported-is-used: true + exported-fields-are-used: true + + govet: + enable-all: true + disable: + - fieldalignment # Field order is intentional per project spec; alignment not enforced. + + staticcheck: + checks: ["all"] + + exclusions: + presets: + - common-false-positives + rules: + - path: _test\.go + linters: + - unused + - errcheck + - path: \.pb\.go$ + linters: + - all + - path: transport/backoff\.go + linters: + - gosec + text: "G404" # math/rand/v2 acceptable for jitter + - path: cmd/scrape/ + linters: + - gosec + text: "G306" # 0o644 intentional: output files are world-readable docs artifacts + - path: cmd/audit/ + linters: + - gosec + text: "G204" # git subprocess with CLI flag path — intentional operator tool + - path: cmd/audit/.*_test\.go + linters: + - gosec + text: "G302" # test helper sets 0o755 on fake git binary — executable permission intentional + +formatters: + enable: + - gofmt + settings: + gofmt: + simplify: true + +run: + timeout: 5m + tests: true + modules-download-mode: readonly + +output: + formats: + text: + path: stdout + colors: true + sort-results: true diff --git a/.goreleaser.yaml b/.goreleaser.yaml new file mode 100644 index 0000000..91b01e9 --- /dev/null +++ b/.goreleaser.yaml @@ -0,0 +1,121 @@ +# Documentation: https://goreleaser.com +version: 2 + +project_name: go-telegram + +before: + hooks: + - go mod tidy + +builds: + - id: scrape + main: ./cmd/scrape + binary: tg-scrape + env: + - CGO_ENABLED=0 + goos: + - linux + - darwin + - windows + goarch: + - amd64 + - arm64 + ldflags: + - -s -w -X main.version={{.Version}} -X main.commit={{.Commit}} + + - id: genapi + main: ./cmd/genapi + binary: tg-genapi + env: + - CGO_ENABLED=0 + goos: + - linux + - darwin + - windows + goarch: + - amd64 + - arm64 + ldflags: + - -s -w -X main.version={{.Version}} -X main.commit={{.Commit}} + + - id: audit + main: ./cmd/audit + binary: tg-audit + env: + - CGO_ENABLED=0 + goos: + - linux + - darwin + - windows + goarch: + - amd64 + - arm64 + ldflags: + - -s -w -X main.version={{.Version}} -X main.commit={{.Commit}} + +archives: + - id: default + formats: [tar.gz] + name_template: >- + {{ .ProjectName }}_{{ .Version }}_ + {{- title .Os }}_ + {{- if eq .Arch "amd64" }}x86_64 + {{- else if eq .Arch "386" }}i386 + {{- else }}{{ .Arch }}{{ end }} + format_overrides: + - goos: windows + formats: [zip] + files: + - LICENSE + - README.md + - CHANGELOG.md + +checksum: + name_template: 'checksums.txt' + +snapshot: + version_template: '{{ incpatch .Version }}-next' + +changelog: + sort: asc + use: github + groups: + - title: Features + regexp: '^.*?feat(\(.+\))?:.+$' + order: 0 + - title: Bug fixes + regexp: '^.*?fix(\(.+\))?:.+$' + order: 1 + - title: Documentation + regexp: '^.*?docs(\(.+\))?:.+$' + order: 2 + - title: Other + order: 999 + filters: + exclude: + - '^chore:' + - '^test:' + - '^style:' + - 'merge conflict' + - Merge pull request + - Merge remote-tracking branch + - Merge branch + - go mod tidy + +release: + github: + owner: lukaszraczylo + name: go-telegram + prerelease: auto + mode: replace + header: | + ## go-telegram {{ .Tag }} + + Released on {{ .Date }} for Telegram Bot API regeneration tooling. + Built against **Bot API {{ envOrDefault "BOT_API_VERSION" "(unspecified)" }}**. + + The library itself ships via `go get github.com/lukaszraczylo/go-telegram@{{ .Tag }}`. + Binaries below are the codegen tools (`tg-scrape`, `tg-genapi`, `tg-audit`) + for users who want to vendor regen tooling. + footer: | + **Full changelog**: https://github.com/lukaszraczylo/go-telegram/compare/{{ .PreviousTag }}...{{ .Tag }} diff --git a/.semver.yaml b/.semver.yaml new file mode 100644 index 0000000..52e3a8b --- /dev/null +++ b/.semver.yaml @@ -0,0 +1,43 @@ +# Configuration for lukaszraczylo/semver-generator. +# Reference: https://github.com/lukaszraczylo/semver-generator +# +# Word matching is fuzzy + case-insensitive. The keywords below mirror +# Conventional Commits prefixes used in this repo's git history. + +version: 1 + +# Respect existing v* tags as the version baseline. semver-generator finds +# the highest existing tag and bumps from there. +force: + existing: true + +# Skip merge commits and machine-generated traffic that would otherwise +# spuriously bump the version. +blacklist: + - "Merge branch" + - "Merge pull request" + - "Merge remote-tracking branch" + - "go mod tidy" + +# Strip the auto-generated bot-api-vX.Y tag prefix when scanning existing +# tags — those are markers that point at library releases, not version +# sources themselves. +tag_prefixes: + - "bot-api-" + +wording: + patch: + - "fix" + - "chore" + - "docs" + - "test" + - "style" + - "refactor" + - "build" + - "ci" + - "perf" + minor: + - "feat" + major: + - "breaking" + - "BREAKING CHANGE" diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..9fbacda --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,56 @@ +# Changelog + +All notable changes to this project will be documented in this file. The format follows [Keep a Changelog](https://keepachangelog.com/) and this project adheres to [Semantic Versioning](https://semver.org/). + +## [Unreleased] + +## [1.0.0] - 2026-05-09 + +Initial public release. Built against Telegram Bot API v10.0 (176 methods, 301 types). + +### Library surface +- `client.Bot` with pluggable `HTTPDoer`, `Codec` (default `github.com/goccy/go-json`), and `Logger` interfaces. +- Generic `client.Call[Req, Resp]` and `client.CallRaw[Req]` helpers — every API method funnels through one of these. +- `client.RetryDoer` middleware — exponential backoff with jitter; honours Telegram's `retry_after`; replays request bodies across attempts. Configurable via `RetryOption` functions (`WithMaxAttempts`, `WithBase`, `WithMax`, `WithFactor`, `WithJitter`). +- Typed errors: `*APIError` (sentinel-mapped: `ErrUnauthorized`, `ErrForbidden`, `ErrTooManyRequests`, `ErrChatNotFound`, `ErrMessageNotModified`, `ErrBadRequest`, `ErrUserNotFound`, `ErrMessageNotFound`), `*NetworkError`, `*ParseError`. Bot tokens redacted from error messages. + +### Update delivery +- `transport.LongPoller` — getUpdates loop with `ExponentialBackoff`, retry-after honouring, graceful shutdown via `Stop`. +- `transport.WebhookServer` — `http.Handler` + `ListenAndServe`; secret-token verification (constant-time); 1 MiB body cap; in-flight handler tracking via `WaitGroup`. + +### Dispatcher +- Generic `dispatch.Handler[T]` and `dispatch.Middleware[T]`. +- 21 typed handler registrations: `OnCommand`, `OnText`, `OnCallback`, `OnInlineQuery`, `OnEditedMessage`, `OnChannelPost`, `OnEditedChannelPost`, `OnMyChatMember`, `OnChatMember`, `OnChatJoinRequest`, `OnPreCheckoutQuery`, `OnShippingQuery`, `OnPoll`, `OnPollAnswer`, `OnChosenInlineResult`, `OnMessageReaction`, `OnMessageReactionCount`, `OnChatBoost`, `OnRemovedChatBoost`, `OnBusinessConnection`, `OnPurchasedPaidMedia`. Filter variants available for message, callback, inline-query, chat-member, chat-join-request, and pre-checkout-query types. +- Composable filters in `dispatch/filters/{message,callback,inline,chatmember,chatjoinrequest,precheckoutquery}` packages with `And`/`Or`/`Not`/`All`/`Any` combinators and 20+ filter helpers. +- `dispatch/conversation` — multi-step state machines with `Storage` interface (`MemoryStorage` default), pluggable `KeyStrategy` (`KeyByUser`, `KeyByChat`, `KeyByUserAndChat`), entry/state/exit/fallback steps, `AllowReEntry`. `Next(state)` and `End()` sentinel errors drive transitions. `Conversation.Dispatch` integrates as middleware via `router.Use`. +- Per-update goroutine pool (default 50; configurable via `WithMaxConcurrency`). Pass `0` for serial dispatch. +- Handler groups with `EndGroups`/`ContinueGroups` flow control. +- `NamedHandlers[T]` for runtime registration and replacement. +- Panic-recovery middleware + automatic handler-error logging registered by default. + +### Generated API +- Full Bot API v10.0 surface in `api/*.gen.go` — 176 methods, 301 types, regenerated from a committed HTML snapshot of `core.telegram.org/bots/api`. +- Strongly typed unions: `ChatID` (Integer-or-String), `*InputFile` (InputFile-or-String), `MessageOrBool` (Message-or-True returns). +- 13 discriminated unions with auto-decode: `ChatMember`, `MessageOrigin`, `ReactionType`, `PaidMedia`, `BackgroundType`, `BackgroundFill`, `ChatBoostSource`, `RevenueWithdrawalState`, `TransactionPartner`, `MenuButton`, `OwnedGift`, `StoryAreaType`, `MaybeInaccessibleMessage`. Parent structs containing union-typed fields auto-decode via generated `UnmarshalJSON`. +- Sealed-interface return types use `client.CallRaw` + `Unmarshal` dispatch (e.g., `GetChatMember` returns `ChatMember` interface, decoded into the correct concrete variant). + +### Runtime helpers +- `api.MeCache` — concurrent-safe `getMe` cache; zero-value safe. +- `api.DownloadFile` / `api.DownloadFileByPath` — fetch file contents from the Telegram CDN. +- `(*Message).GetSender()` — unifies `From`, `SenderChat`, and anonymous-admin fields into a `*Sender`. + +### Codegen pipeline (`cmd/scrape`, `cmd/genapi`, `cmd/audit`) +- Two-stage codegen: HTML → IR (`internal/spec/api.json`) → Go. +- `internal/spec/overrides.json` pins specific method returns/field types when scraper regex does not match a particular doc phrasing. +- `cmd/audit` reports any-typed fields, fallback `bool` returns, and signature drift vs HEAD's IR. Exit codes: 0 clean, 1 fallback, 2 drift, 3 invalid. +- `make regen` is self-verifying: clean → scrape → audit → emit (code + 1428 tests) → run tests. +- Auto-generated tests cover 8 scenarios per method (1428 total): Success, APIError 429, NetworkError, ParseError, ContextCanceled, MissingRequiredFields (400 + ErrBadRequest), Forbidden (403 + ErrForbidden), ServerError (500 + IsRetryable). + +### Tooling +- `.github/workflows/ci.yml` — Go matrix 1.23/1.24, vet, staticcheck, govulncheck, gosec, race tests, codegen-clean check, audit + drift detection. +- `.github/workflows/regen.yml` — weekly cron + workflow_dispatch; scrapes live API, regenerates, runs tests, opens auto-PR with audit summary in body. +- `.github/workflows/release.yml` — semver-generator-driven version bump; dual tagging (library SemVer + `bot-api-v` marker); GoReleaser. +- `.goreleaser.yaml` — ships `tg-scrape`, `tg-genapi`, `tg-audit` binaries for Linux/macOS/Windows × amd64/arm64. + +### Examples (14) +echo, webhook, callback, conversation, files, inline, middleware, stateful, welcome, moderation, polls, payments, pagination, admin. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..6f46e10 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,71 @@ +# Contributing + +Thanks for your interest in go-telegram. The library mixes hand-written and generated code; this guide explains how to update each. + +## Project layout + +- **`client/`** — hand-written Bot client, generic Call helper, error taxonomy, retry middleware. Stable; rarely changes. +- **`transport/`** — long-poll and webhook updaters. Hand-written. +- **`dispatch/`** — typed router with command/text/callback matchers. Hand-written. +- **`api/`** — generated types and method wrappers (`*.gen.go`) plus runtime helpers (`runtime.go`, `download.go`, `me.go`). +- **`internal/spec/`** — IR types + the committed `api.json` snapshot of the Telegram Bot API. +- **`cmd/scrape/`** — HTML scraper that produces `internal/spec/api.json`. +- **`cmd/genapi/`** — emitter that consumes `api.json` and renders `api/*.gen.go`. + +## Workflows + +### Updating to a newer Telegram Bot API version + +```bash +make snapshot # fetch latest HTML from core.telegram.org +make regen # scrape + emit +go test -race ./... # verify +``` + +If the live page introduces a phrasing the scraper doesn't recognise, you'll see methods falling back to `bool` returns or struct fields typed `any`. Check the audit script in `cmd/scrape/method_test.go` and add new patterns to `cmd/scrape/method.go` and / or `cmd/scrape/table.go`. Then `go test -update ./cmd/scrape/...` to refresh the small-fixture golden, and re-run `make regen`. + +### Adding a new union for auto-decode + +If Telegram introduces a new discriminated union type (similar to `ChatMember`): + +1. Add an entry to `knownDiscriminators` in `cmd/genapi/emitter.go`. +2. Run `make regen`. +3. The emitter will produce `UnmarshalXxx` for the union and per-struct `UnmarshalJSON` for any field referencing it. + +### Updating runtime helpers + +Edit `api/runtime.go`, `api/download.go`, `api/me.go`, or any of `client/*.go`, `transport/*.go`, `dispatch/*.go`. Add tests for new functionality. CI runs `go test -race ./...`, `go vet`, `staticcheck`, and the codegen-clean check (which asserts the committed `api/` matches what the pipeline produces from the committed snapshot). + +### Conventions + +- Doc comments on every exported symbol — generated types carry verbatim Telegram prose. +- No `//nolint` directives anywhere; if the linter complains, fix the code or update `.golangci.yml`. +- No reordering of struct fields for `fieldalignment` — JSON field order tracks the spec for diff readability. +- TDD where practical: failing test, then implementation, then commit. +- Conventional Commits style for messages: `feat(...):`, `fix(...):`, `docs(...):`, `chore(...):`, `refactor(...):`, `test(...):`. + +## Running locally + +```bash +make test # unit tests +make test-race # with race detector (CI default) +make lint # vet + staticcheck +make integration # live API smoke tests (requires TELEGRAM_BOT_TOKEN) +``` + +The codegen tooling in `cmd/scrape` pulls `golang.org/x/net/html`. The runtime library packages depend only on the standard library plus `stretchr/testify` (test-only). + +## Releasing + +1. Bump version in `CHANGELOG.md`. +2. Tag with `git tag -a v0.x.0 -m "summary"` (no leading 'v' alone — use the full SemVer triple). +3. `git push --tags`. + +(There is no GoReleaser config yet; releases are tag-only and `go install` works against tags.) + +## Reporting issues + +File issues on the GitHub repository with: +- The Telegram Bot API method involved (if applicable). +- A minimal reproduction (mocked HTTP transport is fine). +- The library version (`go list -m github.com/lukaszraczylo/go-telegram`). diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..745270f --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Lukasz Raczylo + +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/Makefile b/Makefile new file mode 100644 index 0000000..2e3d9fc --- /dev/null +++ b/Makefile @@ -0,0 +1,76 @@ +.PHONY: test test-race lint vet integration regen snapshot regen-from-fixture test-update-golden clean clean-generated audit audit-drift help + +GO ?= go + +help: + @echo "Targets:" + @echo " test - run unit tests" + @echo " test-race - run unit tests with race detector" + @echo " lint - go vet + staticcheck" + @echo " integration - run integration suite (requires TELEGRAM_BOT_TOKEN)" + @echo " snapshot - capture HTML snapshot from live API (Plan 2)" + @echo " regen - regenerate api/ from latest snapshot (Plan 2)" + @echo " regen-from-fixture - deterministic regen from pinned fixture (Plan 2)" + @echo " test-update-golden - refresh golden test fixtures (Plan 2)" + @echo " audit - report any-typed/bool fallbacks in current IR" + @echo " audit-drift - audit + compare against HEAD's IR for signature changes" + @echo " clean-generated - delete generated api/*.gen.go and internal/spec/api.json" + @echo " clean - clean-generated + transient artefacts (binaries, coverage)" + +test: + $(GO) test ./... + +test-race: + $(GO) test -race ./... + +vet: + $(GO) vet ./... + +lint: vet + @which staticcheck > /dev/null || (echo "install staticcheck: go install honnef.co/go/tools/cmd/staticcheck@latest" && exit 1) + staticcheck ./... + +integration: + $(GO) test -tags=integration -v ./test/integration/... + +SCRAPE_INPUT ?= testdata/html/snapshot_2026-05-08.html +SCRAPE_OUTPUT ?= internal/spec/api.json + +snapshot: + ./scripts/snapshot.sh + +regen: clean-generated + $(GO) run ./cmd/scrape -input testdata/html/latest.html -output $(SCRAPE_OUTPUT) + $(GO) run ./cmd/audit -ir $(SCRAPE_OUTPUT) + $(GO) run ./cmd/genapi -input $(SCRAPE_OUTPUT) -outdir api + $(GO) test ./api/... + +regen-from-fixture: clean-generated + $(GO) run ./cmd/scrape -input $(SCRAPE_INPUT) -output $(SCRAPE_OUTPUT) + $(GO) run ./cmd/audit -ir $(SCRAPE_OUTPUT) + $(GO) run ./cmd/genapi -input $(SCRAPE_OUTPUT) -outdir api + $(GO) test ./api/... + +audit: + $(GO) run ./cmd/audit -ir $(SCRAPE_OUTPUT) + +audit-drift: + $(GO) run ./cmd/audit -ir $(SCRAPE_OUTPUT) -drift + +test-update-golden: + $(GO) test -run TestEmit -update ./cmd/genapi/... + $(GO) test -run TestScrape -update ./cmd/scrape/... + +# clean-generated removes ONLY codegen output. Source code (cmd/scrape, +# cmd/genapi, runtime helpers) is untouched. Run before regen to avoid +# orphan files lingering when the IR shrinks (renamed/removed methods). +clean-generated: + rm -f api/*.gen.go api/*_gen_test.go + rm -f internal/spec/api.json + +# clean removes generated output AND transient artefacts (binaries +# accidentally left at repo root, coverage reports). Source code is +# never touched. +clean: clean-generated + rm -f coverage.out coverage.html + rm -f echo webhook genapi scrape callback files inline conversation middleware stateful diff --git a/README.md b/README.md new file mode 100644 index 0000000..0860085 --- /dev/null +++ b/README.md @@ -0,0 +1,333 @@ +# go-telegram + +> A fully-generated, strongly-typed Go client for the Telegram Bot API — no `any`, no guessing. + +[![CI](https://github.com/lukaszraczylo/go-telegram/actions/workflows/ci.yml/badge.svg)](https://github.com/lukaszraczylo/go-telegram/actions/workflows/ci.yml) +[![Go Reference](https://pkg.go.dev/badge/github.com/lukaszraczylo/go-telegram.svg)](https://pkg.go.dev/github.com/lukaszraczylo/go-telegram) +[![Go Version](https://img.shields.io/github/go-mod/go-version/lukaszraczylo/go-telegram)](go.mod) +[![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE) + +> Bot API **v10.0** · 176 methods · 301 types · 1428 auto-generated tests + +Most Telegram bot libraries expose Telegram's "Integer or String" fields as `interface{}` or `any`. Every union type in go-telegram is a real Go type with compile-time safety and auto-decoding. The entire API surface is code-generated from a committed HTML snapshot of the live Telegram docs — regenerating picks up new Bot API versions in one command, with a self-verifying pipeline that catches regressions before they ship. + +```go +bot := client.New(os.Getenv("TELEGRAM_BOT_TOKEN"), + client.WithHTTPClient(client.NewRetryDoer(client.NewDefaultHTTPDoer())), +) + +router := dispatch.New(bot) +router.OnCommand("/start", func(c *dispatch.Context, m *api.Message) error { + _, err := api.SendMessage(c.Ctx, c.Bot, &api.SendMessageParams{ + ChatID: api.ChatIDFromInt(m.Chat.ID), + Text: "Hello! Send me anything to echo.", + }) + return err +}) +router.OnText(`.+`, func(c *dispatch.Context, m *api.Message) error { + _, err := api.SendMessage(c.Ctx, c.Bot, &api.SendMessageParams{ + ChatID: api.ChatIDFromInt(m.Chat.ID), + Text: m.Text, + ReplyParameters: &api.ReplyParameters{MessageID: m.MessageID}, + }) + return err +}) + +ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) +defer stop() +router.Run(ctx, transport.NewLongPoller(bot)) +``` + +## Why go-telegram + +| Feature | What it means for you | +|---|---| +| **Typed unions** | `ChatID`, `MessageOrBool`, `InputFile`, and 13 discriminated-union interfaces give you `switch v.(type)` instead of runtime panics | +| **Full Bot API v10.0** | 176 methods and 301 types — all generated, none hand-written, nothing missing | +| **Self-verifying codegen** | `make snapshot && make regen` regenerates everything and runs 1428 tests; any regression fails the pipeline | +| **Pluggable transport + codec** | `HTTPDoer` and `Codec` are one-method interfaces — swap in fasthttp, sonic, or your test fake without forking | +| **Retry middleware** | `RetryDoer` honours Telegram's `retry_after`, backs off on 5xx, replays request bodies | +| **Composable dispatcher** | Per-update goroutine pool (default 50), filter combinators (`And`/`Or`/`Not`), conversation state machines, named handlers | + +## Quickstart + +```bash +go get github.com/lukaszraczylo/go-telegram +``` + +Full echo bot — long-poll, graceful shutdown, retry on 429: + +```go +package main + +import ( + "context" + "fmt" + "log" + "os" + "os/signal" + "syscall" + + "github.com/lukaszraczylo/go-telegram/api" + "github.com/lukaszraczylo/go-telegram/client" + "github.com/lukaszraczylo/go-telegram/dispatch" + "github.com/lukaszraczylo/go-telegram/transport" +) + +func main() { + token := os.Getenv("TELEGRAM_BOT_TOKEN") + if token == "" { + log.Fatal("TELEGRAM_BOT_TOKEN required") + } + + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + + bot := client.New(token, + client.WithHTTPClient(client.NewRetryDoer(client.NewDefaultHTTPDoer())), + ) + + router := dispatch.New(bot) + router.OnCommand("/start", func(c *dispatch.Context, m *api.Message) error { + _, err := api.SendMessage(c.Ctx, c.Bot, &api.SendMessageParams{ + ChatID: api.ChatIDFromInt(m.Chat.ID), + Text: fmt.Sprintf("Hello %s! Send me anything.", m.From.FirstName), + }) + return err + }) + router.OnText(`.+`, func(c *dispatch.Context, m *api.Message) error { + _, err := api.SendMessage(c.Ctx, c.Bot, &api.SendMessageParams{ + ChatID: api.ChatIDFromInt(m.Chat.ID), + Text: m.Text, + ReplyParameters: &api.ReplyParameters{MessageID: m.MessageID}, + }) + return err + }) + + if err := router.Run(ctx, transport.NewLongPoller(bot)); err != nil && err != context.Canceled { + log.Printf("router exited: %v", err) + } +} +``` + +## Examples + +Run any example: `TELEGRAM_BOT_TOKEN=xxx go run ./examples/` + +| Category | Example | What it shows | +|---|---|---| +| **Basics** | [`echo`](examples/echo) | Long-poll echo bot | +| | [`webhook`](examples/webhook) | Webhook server with secret-token verification | +| | [`files`](examples/files) | Upload and download cycle | +| | [`inline`](examples/inline) | Inline-mode results | +| **Conversations & state** | [`conversation`](examples/conversation) | Multi-step state machine with `/cancel` exit | +| | [`stateful`](examples/stateful) | Per-user state via closures | +| | [`callback`](examples/callback) | Inline keyboards and callback query handling | +| | [`pagination`](examples/pagination) | Multi-page inline keyboard | +| **Group management** | [`welcome`](examples/welcome) | Greet new chat members | +| | [`moderation`](examples/moderation) | Kick/ban/mute/warn with permission checks | +| | [`admin`](examples/admin) | Auth middleware allowlist | +| **Advanced** | [`middleware`](examples/middleware) | `Use` chains | +| | [`polls`](examples/polls) | `sendPoll` and answer tally | +| | [`payments`](examples/payments) | Invoice → pre-checkout → success | + +## Concepts + +
+Bot client and pluggable transport + +`client.New` accepts functional options: + +```go +bot := client.New(token, + client.WithHTTPClient(doer), // any HTTPDoer (one-method interface) + client.WithCodec(myCodec), // any Codec (Marshal + Unmarshal) + client.WithLogger(myLogger), + client.WithBaseURL("https://..."), // proxy or local Bot API server +) +``` + +`HTTPDoer` is `Do(*http.Request) (*http.Response, error)` — a plain `*http.Client` satisfies it. +`Codec` is `Marshal(any) ([]byte, error)` + `Unmarshal([]byte, any) error` — the default wraps `goccy/go-json`. + +Every API call goes through `client.Call[Req, Resp]`; per-method generated functions are thin wrappers. + +
+ +
+Typed unions — no any + +Telegram's docs describe many fields as "Integer or String" or "one of N types". go-telegram turns every one of these into a concrete Go type. + +```go +// ChatID: construct from int64 or @username +chatID := api.ChatIDFromInt(123456789) +chatID := api.ChatIDFromString("@mychannel") + +// Discriminated unions — 13 interfaces with auto-decode via generated UnmarshalJSON +for _, u := range updates { + if u.MyChatMember == nil { + continue + } + switch v := u.MyChatMember.OldChatMember.(type) { + case *api.ChatMemberOwner: + log.Println("was owner") + case *api.ChatMemberAdministrator: + log.Printf("was admin: can_post=%v", v.CanPostMessages) + } +} +``` + +Full union list: `ChatMember`, `MessageOrigin`, `ReactionType`, `PaidMedia`, `BackgroundType`, `BackgroundFill`, `ChatBoostSource`, `RevenueWithdrawalState`, `TransactionPartner`, `MenuButton`, `OwnedGift`, `StoryAreaType`, `MaybeInaccessibleMessage`, plus `ChatID`, `MessageOrBool`, and `InputFile`. + +
+ +
+Dispatcher, filters, and conversations + +The router dispatches each update in its own goroutine (semaphore-bounded, default 50): + +```go +r := dispatch.New(bot, dispatch.WithMaxConcurrency(50)) + +r.OnCommand("/start", handler) +r.OnText(`^hi (\w+)`, handler) +r.OnCallback(`^like:\d+`, handler) +r.OnInlineQuery(handler) +r.OnMyChatMember(handler) +// + 20 more typed On* methods +``` + +**Composable filters** — each update type has its own filter package: + +```go +import "github.com/lukaszraczylo/go-telegram/dispatch/filters/message" + +r.OnMessageFilter( + message.Command("/admin").And(message.IsReply()), + handler, +) +``` + +Filter packages: `message`, `callback`, `inline`, `chatmember`, `chatjoinrequest`, `precheckoutquery`. Combinators: `And`, `Or`, `Not`, `All`, `Any`. + +**Conversation state machines** — multi-step flows with pluggable storage: + +```go +conv := &conversation.Conversation{ + EntryPoints: []conversation.Step{{ + Filter: dispatch.FilterFunc(func(c *dispatch.Context, u *api.Update) bool { + return u.Message != nil && u.Message.Text == "/start" + }), + Handler: func(c *dispatch.Context, u *api.Update) error { + // send prompt, advance state + return conversation.Next("await_name") + }, + }}, + States: map[conversation.State][]conversation.Step{ + "await_name": {{ + Handler: func(c *dispatch.Context, u *api.Update) error { + return conversation.End() + }, + }}, + }, +} +router.Use(conv.Dispatch) +``` + +Key strategies: `KeyByUser`, `KeyByChat`, `KeyByUserAndChat` (default). Default storage: `MemoryStorage` (in-process, concurrency-safe). Implement the `Storage` interface for Redis or any other backend. + +
+ +
+Errors and retry middleware + +Wrap the default HTTP doer with `RetryDoer` for production: + +```go +bot := client.New(token, + client.WithHTTPClient( + client.NewRetryDoer( + client.NewDefaultHTTPDoer(), + client.WithMaxAttempts(5), + client.WithBaseBackoff(500*time.Millisecond), + ), + ), +) +``` + +`RetryDoer` retries on 429, 5xx, and transient network errors. On a 429 it reads `retry_after` from Telegram's response body and waits exactly that long — overriding any backoff calculation. Request bodies are buffered and replayed across attempts. + +Sentinel errors for `errors.Is` checks: `client.ErrForbidden`, `client.ErrNotFound`, `client.ErrUnauthorized`. + +
+ +
+Handler groups and named handlers + +Priority-ordered groups with flow control signals: + +```go +// Group 0 runs first — return EndGroups to stop, ContinueGroups to continue +r.Group(0).OnText(`.*`, authMiddleware) +r.Group(1).OnText(`.*`, businessHandler) +``` + +Named handlers — register and replace at runtime: + +```go +named := dispatch.NewNamedHandlers[*api.Message]() +named.Set("main", myHandler) +r.OnCommand("/cmd", named.Handler()) +// later: named.Set("main", updatedHandler) +``` + +
+ +## Codegen pipeline + +The full API surface in `api/*.gen.go` is generated from a committed HTML snapshot of `core.telegram.org/bots/api`: + +```bash +make snapshot # fetch and commit latest HTML from core.telegram.org +make regen # scrape → audit → emit Go code → run generated tests +go test -race ./... +``` + +`make regen` is self-verifying. The audit tool (`cmd/audit`) checks: + +- `any`-typed fields or returns that escaped the union machinery +- Methods returning `bool` not on the approved list (`internal/spec/overrides.json`) +- Signature drift vs HEAD's IR (added/removed/changed return types) + +Exit codes: 0 clean · 1 fallback · 2 drift · 3 invalid. CI runs the audit on every PR. A weekly `regen.yml` workflow opens a PR with regenerated code and the audit summary in the body. + +To track a new Bot API release: run `make snapshot && make regen`, review the audit output, update `internal/spec/overrides.json` for any newly unparseable methods, and submit a PR. + +## Testing + +Mock the one-method `HTTPDoer` interface to test handlers in isolation — no test server needed: + +```go +type fakeDoer struct{ body string } +func (f fakeDoer) Do(*http.Request) (*http.Response, error) { + return &http.Response{ + StatusCode: 200, + Body: io.NopCloser(strings.NewReader(f.body)), + }, nil +} + +bot := client.New("token", client.WithHTTPClient(fakeDoer{ + body: `{"ok":true,"result":{"message_id":1,"date":0,"chat":{"id":1,"type":"private"}}}`, +})) +``` + +The library's own generated test suite (`api/methods_gen_test.go`) covers 176 methods × 8 scenarios each: Success, APIError, NetworkError, ParseError, ContextCanceled, MissingRequiredFields, Forbidden, ServerError. + +## Contributing + +See [CONTRIBUTING.md](CONTRIBUTING.md). + +## License + +MIT diff --git a/api/download.go b/api/download.go new file mode 100644 index 0000000..4f98d6d --- /dev/null +++ b/api/download.go @@ -0,0 +1,57 @@ +package api + +import ( + "context" + "fmt" + "io" + "net/http" + + "github.com/lukaszraczylo/go-telegram/client" +) + +// DownloadFile fetches the contents of a Telegram-hosted file given a +// previously-uploaded file_id. It calls GetFile to resolve the file's +// download path, then issues an HTTP GET to the file CDN endpoint. +// +// The returned io.ReadCloser must be closed by the caller. The size of +// the file is reported via *File.FileSize when known. +// +// For files larger than 20 MB, Telegram requires a self-hosted Bot API +// server (default api.telegram.org has a 20 MB limit on getFile). +func DownloadFile(ctx context.Context, b *client.Bot, fileID string) (io.ReadCloser, *File, error) { + f, err := GetFile(ctx, b, &GetFileParams{FileID: fileID}) + if err != nil { + return nil, nil, fmt.Errorf("getFile: %w", err) + } + if f == nil || f.FilePath == "" { + return nil, f, fmt.Errorf("telegram: file %q has no download path", fileID) + } + rc, err := DownloadFileByPath(ctx, b, f.FilePath) + if err != nil { + return nil, f, err + } + return rc, f, nil +} + +// DownloadFileByPath fetches a file by its file_path (typically obtained +// from a prior File response). Useful when the caller already has a +// *File and wants to skip the GetFile round-trip. +func DownloadFileByPath(ctx context.Context, b *client.Bot, filePath string) (io.ReadCloser, error) { + url := fmt.Sprintf("%s/file/bot%s/%s", b.BaseURL(), b.Token(), filePath) + req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) + if err != nil { + return nil, err + } + resp, err := b.HTTP().Do(req) + if err != nil { + if ctxErr := ctx.Err(); ctxErr != nil { + return nil, ctxErr + } + return nil, fmt.Errorf("download: %w", err) + } + if resp.StatusCode != http.StatusOK { + _ = resp.Body.Close() + return nil, fmt.Errorf("download: HTTP %d", resp.StatusCode) + } + return resp.Body, nil +} diff --git a/api/download_test.go b/api/download_test.go new file mode 100644 index 0000000..5109a92 --- /dev/null +++ b/api/download_test.go @@ -0,0 +1,80 @@ +package api + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/lukaszraczylo/go-telegram/client" + "github.com/stretchr/testify/require" +) + +func TestDownloadFile_HappyPath(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + case strings.HasSuffix(r.URL.Path, "/getFile"): + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"ok":true,"result":{"file_id":"abc","file_unique_id":"u","file_size":11,"file_path":"documents/hello.txt"}}`)) + case strings.HasPrefix(r.URL.Path, "/file/bot"): + _, _ = w.Write([]byte("hello world")) + default: + http.NotFound(w, r) + } + })) + t.Cleanup(srv.Close) + + bot := client.New("123:abc", client.WithBaseURL(srv.URL)) + rc, file, err := DownloadFile(context.Background(), bot, "abc") + require.NoError(t, err) + defer rc.Close() + require.Equal(t, "documents/hello.txt", file.FilePath) + body, err := io.ReadAll(rc) + require.NoError(t, err) + require.Equal(t, "hello world", string(body)) +} + +func TestDownloadFile_GetFileFailure(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"ok":false,"error_code":400,"description":"Bad Request: invalid file_id"}`)) + })) + t.Cleanup(srv.Close) + + bot := client.New("t", client.WithBaseURL(srv.URL)) + _, _, err := DownloadFile(context.Background(), bot, "bad") + require.Error(t, err) + require.Contains(t, err.Error(), "getFile") +} + +func TestDownloadFile_NoFilePath(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + // result without file_path + _, _ = w.Write([]byte(`{"ok":true,"result":{"file_id":"abc","file_unique_id":"u"}}`)) + })) + t.Cleanup(srv.Close) + + bot := client.New("t", client.WithBaseURL(srv.URL)) + _, _, err := DownloadFile(context.Background(), bot, "abc") + require.Error(t, err) + require.Contains(t, err.Error(), "no download path") +} + +func TestDownloadFileByPath_HTTPError(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if strings.HasPrefix(r.URL.Path, "/file/bot") { + w.WriteHeader(http.StatusForbidden) + return + } + http.NotFound(w, r) + })) + t.Cleanup(srv.Close) + + bot := client.New("t", client.WithBaseURL(srv.URL)) + _, err := DownloadFileByPath(context.Background(), bot, "secret/file") + require.Error(t, err) + require.Contains(t, err.Error(), "403") +} diff --git a/api/enums.gen.go b/api/enums.gen.go new file mode 100644 index 0000000..0484394 --- /dev/null +++ b/api/enums.gen.go @@ -0,0 +1,60 @@ +// Code generated by cmd/genapi. DO NOT EDIT. + +//go:build !ignore_autogenerated + +package api + +// ParseMode controls how Telegram interprets formatting in message text. +type ParseMode string + +const ( + ParseModeMarkdown ParseMode = "Markdown" // legacy + ParseModeMarkdownV2 ParseMode = "MarkdownV2" + ParseModeHTML ParseMode = "HTML" +) + +// ChatType is the type of a Telegram chat. +type ChatType string + +const ( + ChatTypePrivate ChatType = "private" + ChatTypeGroup ChatType = "group" + ChatTypeSupergroup ChatType = "supergroup" + ChatTypeChannel ChatType = "channel" +) + +// UpdateType identifies an Update payload variant. Used by allowed_updates +// in getUpdates / setWebhook. +type UpdateType string + +const ( + UpdateMessage UpdateType = "message" + UpdateEditedMessage UpdateType = "edited_message" + UpdateChannelPost UpdateType = "channel_post" + UpdateEditedChannelPost UpdateType = "edited_channel_post" + UpdateCallbackQuery UpdateType = "callback_query" + UpdateInlineQuery UpdateType = "inline_query" +) + +// MessageEntityType is the kind of an entity (mention, hashtag, command, ...). +type MessageEntityType string + +const ( + EntityMention MessageEntityType = "mention" + EntityHashtag MessageEntityType = "hashtag" + EntityCashtag MessageEntityType = "cashtag" + EntityBotCommand MessageEntityType = "bot_command" + EntityURL MessageEntityType = "url" + EntityEmail MessageEntityType = "email" + EntityPhoneNumber MessageEntityType = "phone_number" + EntityBold MessageEntityType = "bold" + EntityItalic MessageEntityType = "italic" + EntityUnderline MessageEntityType = "underline" + EntityStrike MessageEntityType = "strikethrough" + EntitySpoiler MessageEntityType = "spoiler" + EntityCode MessageEntityType = "code" + EntityPre MessageEntityType = "pre" + EntityTextLink MessageEntityType = "text_link" + EntityTextMention MessageEntityType = "text_mention" + EntityCustomEmoji MessageEntityType = "custom_emoji" +) diff --git a/api/me.go b/api/me.go new file mode 100644 index 0000000..58c1803 --- /dev/null +++ b/api/me.go @@ -0,0 +1,50 @@ +package api + +import ( + "context" + "sync" + + "github.com/lukaszraczylo/go-telegram/client" +) + +// MeCache caches the result of GetMe across calls. Construct one per +// Bot and call Get to retrieve the cached User on subsequent invocations. +// +// var meCache api.MeCache +// me, err := meCache.Get(ctx, bot) +// +// MeCache is safe for concurrent use. +type MeCache struct { + mu sync.Mutex + cached *User +} + +// Get returns the User from a cached GetMe call. If the cache is empty, +// it calls GetMe and populates the cache on success. +func (c *MeCache) Get(ctx context.Context, b *client.Bot) (*User, error) { + c.mu.Lock() + if c.cached != nil { + u := c.cached + c.mu.Unlock() + return u, nil + } + c.mu.Unlock() + + u, err := GetMe(ctx, b, &GetMeParams{}) + if err != nil { + return nil, err + } + + c.mu.Lock() + c.cached = u + c.mu.Unlock() + return u, nil +} + +// Reset clears the cache. Useful in tests or after the bot's identity +// is known to have changed (very rare). +func (c *MeCache) Reset() { + c.mu.Lock() + c.cached = nil + c.mu.Unlock() +} diff --git a/api/me_test.go b/api/me_test.go new file mode 100644 index 0000000..e3c3e3b --- /dev/null +++ b/api/me_test.go @@ -0,0 +1,58 @@ +package api + +import ( + "context" + "net/http" + "strings" + "sync/atomic" + "testing" + + "github.com/lukaszraczylo/go-telegram/client" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" +) + +func TestMeCache_FetchesOnce(t *testing.T) { + m := &mockDoer{} + var calls atomic.Int32 + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + if strings.HasSuffix(r.URL.Path, "/getMe") { + calls.Add(1) + return true + } + return false + })).Return(newJSONResp(200, `{"ok":true,"result":{"id":1,"is_bot":true,"first_name":"echo","username":"echo_bot"}}`), nil) + + bot := client.New("t", client.WithHTTPClient(m)) + var cache MeCache + + me1, err := cache.Get(context.Background(), bot) + require.NoError(t, err) + require.Equal(t, "echo_bot", me1.Username) + + me2, err := cache.Get(context.Background(), bot) + require.NoError(t, err) + require.Same(t, me1, me2) + require.Equal(t, int32(1), calls.Load(), "should fetch only once") +} + +func TestMeCache_Reset(t *testing.T) { + var calls atomic.Int32 + m := &mockDoer{} + m.On("Do", mock.Anything).Run(func(args mock.Arguments) { + calls.Add(1) + }).Return(newJSONResp(200, `{"ok":true,"result":{"id":1,"is_bot":true,"first_name":"echo","username":"echo_bot"}}`), nil).Once() + m.On("Do", mock.Anything).Run(func(args mock.Arguments) { + calls.Add(1) + }).Return(newJSONResp(200, `{"ok":true,"result":{"id":1,"is_bot":true,"first_name":"echo","username":"echo_bot"}}`), nil).Once() + + bot := client.New("t", client.WithHTTPClient(m)) + var cache MeCache + + _, err := cache.Get(context.Background(), bot) + require.NoError(t, err) + cache.Reset() + _, err = cache.Get(context.Background(), bot) + require.NoError(t, err) + require.Equal(t, int32(2), calls.Load()) +} diff --git a/api/methods.gen.go b/api/methods.gen.go new file mode 100644 index 0000000..e8f5a7f --- /dev/null +++ b/api/methods.gen.go @@ -0,0 +1,5145 @@ +// Code generated by cmd/genapi. DO NOT EDIT. + +//go:build !ignore_autogenerated + +package api + +import ( + "context" + "github.com/goccy/go-json" + "strconv" + + "github.com/lukaszraczylo/go-telegram/client" +) + +var _ = strconv.Itoa // keep import for multipart helpers +var _ = json.Marshal // keep import for complex multipart fields + +// GetUpdatesParams is the parameter set for GetUpdates. +// +// Use this method to receive incoming updates using long polling (wiki). Returns an Array of Update objects. +// Notes1. This method will not work if an outgoing webhook is set up.2. In order to avoid getting duplicate updates, recalculate offset after each server response. +type GetUpdatesParams struct { + // Identifier of the first update to be returned. Must be greater by one than the highest among the identifiers of previously received updates. By default, updates starting with the earliest unconfirmed update are returned. An update is considered confirmed as soon as getUpdates is called with an offset higher than its update_id. The negative offset can be specified to retrieve updates starting from -offset update from the end of the updates queue. All previous updates will be forgotten. + Offset *int64 `json:"offset,omitempty"` + // Limits the number of updates to be retrieved. Values between 1-100 are accepted. Defaults to 100. + Limit *int64 `json:"limit,omitempty"` + // Timeout in seconds for long polling. Defaults to 0, i.e. usual short polling. Should be positive, short polling should be used for testing purposes only. + Timeout *int64 `json:"timeout,omitempty"` + // A JSON-serialized list of the update types you want your bot to receive. For example, specify ["message", "edited_channel_post", "callback_query"] to only receive updates of these types. See Update for a complete list of available update types. Specify an empty list to receive all update types except chat_member, message_reaction, and message_reaction_count (default). If not specified, the previous setting will be used.Please note that this parameter doesn't affect updates created before the call to getUpdates, so unwanted updates may be received for a short period of time. + AllowedUpdates []string `json:"allowed_updates,omitempty"` +} + +// GetUpdates calls the getUpdates Telegram Bot API method. +// +// Use this method to receive incoming updates using long polling (wiki). Returns an Array of Update objects. +// Notes1. This method will not work if an outgoing webhook is set up.2. In order to avoid getting duplicate updates, recalculate offset after each server response. +func GetUpdates(ctx context.Context, b *client.Bot, p *GetUpdatesParams) ([]Update, error) { + return client.Call[*GetUpdatesParams, []Update](ctx, b, "getUpdates", p) +} + +// SetWebhookParams is the parameter set for SetWebhook. +// +// Use this method to specify a URL and receive incoming updates via an outgoing webhook. Whenever there is an update for the bot, we will send an HTTPS POST request to the specified URL, containing a JSON-serialized Update. In case of an unsuccessful request (a request with response HTTP status code different from 2XY), we will repeat the request and give up after a reasonable amount of attempts. Returns True on success. +// If you'd like to make sure that the webhook was set by you, you can specify secret data in the parameter secret_token. If specified, the request will contain a header “X-Telegram-Bot-Api-Secret-Token” with the secret token as content. +// Notes1. You will not be able to receive updates using getUpdates for as long as an outgoing webhook is set up.2. To use a self-signed certificate, you need to upload your public key certificate using certificate parameter. Please upload as InputFile, sending a String will not work.3. Ports currently supported for webhooks: 443, 80, 88, 8443. +// If you're having any trouble setting up webhooks, please check out this amazing guide to webhooks. +type SetWebhookParams struct { + // HTTPS URL to send updates to. Use an empty string to remove webhook integration + URL string `json:"url"` + // Upload your public key certificate so that the root certificate in use can be checked. See our self-signed guide for details. + Certificate *InputFile `json:"certificate,omitempty"` + // The fixed IP address which will be used to send webhook requests instead of the IP address resolved through DNS + IPAddress string `json:"ip_address,omitempty"` + // The maximum allowed number of simultaneous HTTPS connections to the webhook for update delivery, 1-100. Defaults to 40. Use lower values to limit the load on your bot's server, and higher values to increase your bot's throughput. + MaxConnections *int64 `json:"max_connections,omitempty"` + // A JSON-serialized list of the update types you want your bot to receive. For example, specify ["message", "edited_channel_post", "callback_query"] to only receive updates of these types. See Update for a complete list of available update types. Specify an empty list to receive all update types except chat_member, message_reaction, and message_reaction_count (default). If not specified, the previous setting will be used.Please note that this parameter doesn't affect updates created before the call to the setWebhook, so unwanted updates may be received for a short period of time. + AllowedUpdates []string `json:"allowed_updates,omitempty"` + // Pass True to drop all pending updates + DropPendingUpdates *bool `json:"drop_pending_updates,omitempty"` + // A secret token to be sent in a header “X-Telegram-Bot-Api-Secret-Token” in every webhook request, 1-256 characters. Only characters A-Z, a-z, 0-9, _ and - are allowed. The header is useful to ensure that the request comes from a webhook set by you. + SecretToken string `json:"secret_token,omitempty"` +} + +// HasFile reports whether a multipart upload is required. +func (p *SetWebhookParams) HasFile() bool { + if p.Certificate != nil && p.Certificate.IsLocalUpload() { + return true + } + return false +} + +// MultipartFields returns the non-file fields used in the multipart body. +func (p *SetWebhookParams) MultipartFields() map[string]string { + out := map[string]string{} + out["url"] = p.URL + if p.IPAddress != "" { + out["ip_address"] = p.IPAddress + } + if p.MaxConnections != nil { + out["max_connections"] = strconv.FormatInt(*p.MaxConnections, 10) + } + if p.AllowedUpdates != nil { + if b, _ := json.Marshal(p.AllowedUpdates); len(b) > 0 { + out["allowed_updates"] = string(b) + } + } + if p.DropPendingUpdates != nil { + out["drop_pending_updates"] = strconv.FormatBool(*p.DropPendingUpdates) + } + if p.SecretToken != "" { + out["secret_token"] = p.SecretToken + } + return out +} + +// MultipartFiles returns the file parts. +func (p *SetWebhookParams) MultipartFiles() []client.MultipartFile { + var files []client.MultipartFile + if p.Certificate != nil && p.Certificate.IsLocalUpload() { + name := p.Certificate.Filename + if name == "" { + name = "certificate" + } + files = append(files, client.MultipartFile{FieldName: "certificate", Filename: name, Reader: p.Certificate.Reader}) + } + return files +} + +// SetWebhook calls the setWebhook Telegram Bot API method. +// +// Use this method to specify a URL and receive incoming updates via an outgoing webhook. Whenever there is an update for the bot, we will send an HTTPS POST request to the specified URL, containing a JSON-serialized Update. In case of an unsuccessful request (a request with response HTTP status code different from 2XY), we will repeat the request and give up after a reasonable amount of attempts. Returns True on success. +// If you'd like to make sure that the webhook was set by you, you can specify secret data in the parameter secret_token. If specified, the request will contain a header “X-Telegram-Bot-Api-Secret-Token” with the secret token as content. +// Notes1. You will not be able to receive updates using getUpdates for as long as an outgoing webhook is set up.2. To use a self-signed certificate, you need to upload your public key certificate using certificate parameter. Please upload as InputFile, sending a String will not work.3. Ports currently supported for webhooks: 443, 80, 88, 8443. +// If you're having any trouble setting up webhooks, please check out this amazing guide to webhooks. +func SetWebhook(ctx context.Context, b *client.Bot, p *SetWebhookParams) (bool, error) { + return client.Call[*SetWebhookParams, bool](ctx, b, "setWebhook", p) +} + +// DeleteWebhookParams is the parameter set for DeleteWebhook. +// +// Use this method to remove webhook integration if you decide to switch back to getUpdates. Returns True on success. +type DeleteWebhookParams struct { + // Pass True to drop all pending updates + DropPendingUpdates *bool `json:"drop_pending_updates,omitempty"` +} + +// DeleteWebhook calls the deleteWebhook Telegram Bot API method. +// +// Use this method to remove webhook integration if you decide to switch back to getUpdates. Returns True on success. +func DeleteWebhook(ctx context.Context, b *client.Bot, p *DeleteWebhookParams) (bool, error) { + return client.Call[*DeleteWebhookParams, bool](ctx, b, "deleteWebhook", p) +} + +// GetWebhookInfoParams is the parameter set for GetWebhookInfo. +// +// Use this method to get current webhook status. Requires no parameters. On success, returns a WebhookInfo object. If the bot is using getUpdates, will return an object with the url field empty. +type GetWebhookInfoParams struct { +} + +// GetWebhookInfo calls the getWebhookInfo Telegram Bot API method. +// +// Use this method to get current webhook status. Requires no parameters. On success, returns a WebhookInfo object. If the bot is using getUpdates, will return an object with the url field empty. +func GetWebhookInfo(ctx context.Context, b *client.Bot, p *GetWebhookInfoParams) (*WebhookInfo, error) { + return client.Call[*GetWebhookInfoParams, *WebhookInfo](ctx, b, "getWebhookInfo", p) +} + +// GetMeParams is the parameter set for GetMe. +// +// A simple method for testing your bot's authentication token. Requires no parameters. Returns basic information about the bot in form of a User object. +type GetMeParams struct { +} + +// GetMe calls the getMe Telegram Bot API method. +// +// A simple method for testing your bot's authentication token. Requires no parameters. Returns basic information about the bot in form of a User object. +func GetMe(ctx context.Context, b *client.Bot, p *GetMeParams) (*User, error) { + return client.Call[*GetMeParams, *User](ctx, b, "getMe", p) +} + +// LogOutParams is the parameter set for LogOut. +// +// Use this method to log out from the cloud Bot API server before launching the bot locally. You must log out the bot before running it locally, otherwise there is no guarantee that the bot will receive updates. After a successful call, you can immediately log in on a local server, but will not be able to log in back to the cloud Bot API server for 10 minutes. Returns True on success. Requires no parameters. +type LogOutParams struct { +} + +// LogOut calls the logOut Telegram Bot API method. +// +// Use this method to log out from the cloud Bot API server before launching the bot locally. You must log out the bot before running it locally, otherwise there is no guarantee that the bot will receive updates. After a successful call, you can immediately log in on a local server, but will not be able to log in back to the cloud Bot API server for 10 minutes. Returns True on success. Requires no parameters. +func LogOut(ctx context.Context, b *client.Bot, p *LogOutParams) (bool, error) { + return client.Call[*LogOutParams, bool](ctx, b, "logOut", p) +} + +// CloseParams is the parameter set for Close. +// +// Use this method to close the bot instance before moving it from one local server to another. You need to delete the webhook before calling this method to ensure that the bot isn't launched again after server restart. The method will return error 429 in the first 10 minutes after the bot is launched. Returns True on success. Requires no parameters. +type CloseParams struct { +} + +// Close calls the close Telegram Bot API method. +// +// Use this method to close the bot instance before moving it from one local server to another. You need to delete the webhook before calling this method to ensure that the bot isn't launched again after server restart. The method will return error 429 in the first 10 minutes after the bot is launched. Returns True on success. Requires no parameters. +func Close(ctx context.Context, b *client.Bot, p *CloseParams) (bool, error) { + return client.Call[*CloseParams, bool](ctx, b, "close", p) +} + +// SendMessageParams is the parameter set for SendMessage. +// +// Use this method to send text messages. On success, the sent Message is returned. +type SendMessageParams struct { + // Unique identifier of the business connection on behalf of which the message will be sent + BusinessConnectionID string `json:"business_connection_id,omitempty"` + // Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username + ChatID ChatID `json:"chat_id"` + // Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only + MessageThreadID *int64 `json:"message_thread_id,omitempty"` + // Identifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat + DirectMessagesTopicID *int64 `json:"direct_messages_topic_id,omitempty"` + // Text of the message to be sent, 1-4096 characters after entities parsing + Text string `json:"text"` + // Mode for parsing entities in the message text. See formatting options for more details. + ParseMode string `json:"parse_mode,omitempty"` + // A JSON-serialized list of special entities that appear in message text, which can be specified instead of parse_mode + Entities []MessageEntity `json:"entities,omitempty"` + // Link preview generation options for the message + LinkPreviewOptions *LinkPreviewOptions `json:"link_preview_options,omitempty"` + // Sends the message silently. Users will receive a notification with no sound. + DisableNotification *bool `json:"disable_notification,omitempty"` + // Protects the contents of the sent message from forwarding and saving + ProtectContent *bool `json:"protect_content,omitempty"` + // Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance. + AllowPaidBroadcast *bool `json:"allow_paid_broadcast,omitempty"` + // Unique identifier of the message effect to be added to the message; for private chats only + MessageEffectID string `json:"message_effect_id,omitempty"` + // A JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined. + SuggestedPostParameters *SuggestedPostParameters `json:"suggested_post_parameters,omitempty"` + // Description of the message to reply to + ReplyParameters *ReplyParameters `json:"reply_parameters,omitempty"` + // Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user + ReplyMarkup any `json:"reply_markup,omitempty"` +} + +// SendMessage calls the sendMessage Telegram Bot API method. +// +// Use this method to send text messages. On success, the sent Message is returned. +func SendMessage(ctx context.Context, b *client.Bot, p *SendMessageParams) (*Message, error) { + return client.Call[*SendMessageParams, *Message](ctx, b, "sendMessage", p) +} + +// ForwardMessageParams is the parameter set for ForwardMessage. +// +// Use this method to forward messages of any kind. Service messages and messages with protected content can't be forwarded. On success, the sent Message is returned. +type ForwardMessageParams struct { + // Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username + ChatID ChatID `json:"chat_id"` + // Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only + MessageThreadID *int64 `json:"message_thread_id,omitempty"` + // Identifier of the direct messages topic to which the message will be forwarded; required if the message is forwarded to a direct messages chat + DirectMessagesTopicID *int64 `json:"direct_messages_topic_id,omitempty"` + // Unique identifier for the chat where the original message was sent (or username of the target bot, supergroup or channel in the format @username) + FromChatID ChatID `json:"from_chat_id"` + // New start timestamp for the forwarded video in the message + VideoStartTimestamp *int64 `json:"video_start_timestamp,omitempty"` + // Sends the message silently. Users will receive a notification with no sound. + DisableNotification *bool `json:"disable_notification,omitempty"` + // Protects the contents of the forwarded message from forwarding and saving + ProtectContent *bool `json:"protect_content,omitempty"` + // Unique identifier of the message effect to be added to the message; only available when forwarding to private chats + MessageEffectID string `json:"message_effect_id,omitempty"` + // A JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only + SuggestedPostParameters *SuggestedPostParameters `json:"suggested_post_parameters,omitempty"` + // Message identifier in the chat specified in from_chat_id + MessageID int64 `json:"message_id"` +} + +// ForwardMessage calls the forwardMessage Telegram Bot API method. +// +// Use this method to forward messages of any kind. Service messages and messages with protected content can't be forwarded. On success, the sent Message is returned. +func ForwardMessage(ctx context.Context, b *client.Bot, p *ForwardMessageParams) (*Message, error) { + return client.Call[*ForwardMessageParams, *Message](ctx, b, "forwardMessage", p) +} + +// ForwardMessagesParams is the parameter set for ForwardMessages. +// +// Use this method to forward multiple messages of any kind. If some of the specified messages can't be found or forwarded, they are skipped. Service messages and messages with protected content can't be forwarded. Album grouping is kept for forwarded messages. On success, an array of MessageId of the sent messages is returned. +type ForwardMessagesParams struct { + // Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username + ChatID ChatID `json:"chat_id"` + // Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only + MessageThreadID *int64 `json:"message_thread_id,omitempty"` + // Identifier of the direct messages topic to which the messages will be forwarded; required if the messages are forwarded to a direct messages chat + DirectMessagesTopicID *int64 `json:"direct_messages_topic_id,omitempty"` + // Unique identifier for the chat where the original messages were sent (or username of the target bot, supergroup or channel in the format @username) + FromChatID ChatID `json:"from_chat_id"` + // A JSON-serialized list of 1-100 identifiers of messages in the chat from_chat_id to forward. The identifiers must be specified in a strictly increasing order. + MessageIds []int64 `json:"message_ids"` + // Sends the messages silently. Users will receive a notification with no sound. + DisableNotification *bool `json:"disable_notification,omitempty"` + // Protects the contents of the forwarded messages from forwarding and saving + ProtectContent *bool `json:"protect_content,omitempty"` +} + +// ForwardMessages calls the forwardMessages Telegram Bot API method. +// +// Use this method to forward multiple messages of any kind. If some of the specified messages can't be found or forwarded, they are skipped. Service messages and messages with protected content can't be forwarded. Album grouping is kept for forwarded messages. On success, an array of MessageId of the sent messages is returned. +func ForwardMessages(ctx context.Context, b *client.Bot, p *ForwardMessagesParams) ([]MessageId, error) { + return client.Call[*ForwardMessagesParams, []MessageId](ctx, b, "forwardMessages", p) +} + +// CopyMessageParams is the parameter set for CopyMessage. +// +// Use this method to copy messages of any kind. Service messages, paid media messages, giveaway messages, giveaway winners messages, and invoice messages can't be copied. A quiz poll can be copied only if the value of the field correct_option_id is known to the bot. The method is analogous to the method forwardMessage, but the copied message doesn't have a link to the original message. Returns the MessageId of the sent message on success. +type CopyMessageParams struct { + // Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username + ChatID ChatID `json:"chat_id"` + // Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only + MessageThreadID *int64 `json:"message_thread_id,omitempty"` + // Identifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat + DirectMessagesTopicID *int64 `json:"direct_messages_topic_id,omitempty"` + // Unique identifier for the chat where the original message was sent (or username of the target bot, supergroup or channel in the format @username) + FromChatID ChatID `json:"from_chat_id"` + // Message identifier in the chat specified in from_chat_id + MessageID int64 `json:"message_id"` + // New start timestamp for the copied video in the message + VideoStartTimestamp *int64 `json:"video_start_timestamp,omitempty"` + // New caption for media, 0-1024 characters after entities parsing. If not specified, the original caption is kept + Caption string `json:"caption,omitempty"` + // Mode for parsing entities in the new caption. See formatting options for more details. + ParseMode string `json:"parse_mode,omitempty"` + // A JSON-serialized list of special entities that appear in the new caption, which can be specified instead of parse_mode + CaptionEntities []MessageEntity `json:"caption_entities,omitempty"` + // Pass True, if the caption must be shown above the message media. Ignored if a new caption isn't specified. + ShowCaptionAboveMedia *bool `json:"show_caption_above_media,omitempty"` + // Sends the message silently. Users will receive a notification with no sound. + DisableNotification *bool `json:"disable_notification,omitempty"` + // Protects the contents of the sent message from forwarding and saving + ProtectContent *bool `json:"protect_content,omitempty"` + // Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance. + AllowPaidBroadcast *bool `json:"allow_paid_broadcast,omitempty"` + // Unique identifier of the message effect to be added to the message; only available when copying to private chats + MessageEffectID string `json:"message_effect_id,omitempty"` + // A JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined. + SuggestedPostParameters *SuggestedPostParameters `json:"suggested_post_parameters,omitempty"` + // Description of the message to reply to + ReplyParameters *ReplyParameters `json:"reply_parameters,omitempty"` + // Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user + ReplyMarkup any `json:"reply_markup,omitempty"` +} + +// CopyMessage calls the copyMessage Telegram Bot API method. +// +// Use this method to copy messages of any kind. Service messages, paid media messages, giveaway messages, giveaway winners messages, and invoice messages can't be copied. A quiz poll can be copied only if the value of the field correct_option_id is known to the bot. The method is analogous to the method forwardMessage, but the copied message doesn't have a link to the original message. Returns the MessageId of the sent message on success. +func CopyMessage(ctx context.Context, b *client.Bot, p *CopyMessageParams) (*MessageId, error) { + return client.Call[*CopyMessageParams, *MessageId](ctx, b, "copyMessage", p) +} + +// CopyMessagesParams is the parameter set for CopyMessages. +// +// Use this method to copy messages of any kind. If some of the specified messages can't be found or copied, they are skipped. Service messages, paid media messages, giveaway messages, giveaway winners messages, and invoice messages can't be copied. A quiz poll can be copied only if the value of the field correct_option_id is known to the bot. The method is analogous to the method forwardMessages, but the copied messages don't have a link to the original message. Album grouping is kept for copied messages. On success, an array of MessageId of the sent messages is returned. +type CopyMessagesParams struct { + // Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username + ChatID ChatID `json:"chat_id"` + // Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only + MessageThreadID *int64 `json:"message_thread_id,omitempty"` + // Identifier of the direct messages topic to which the messages will be sent; required if the messages are sent to a direct messages chat + DirectMessagesTopicID *int64 `json:"direct_messages_topic_id,omitempty"` + // Unique identifier for the chat where the original messages were sent (or username of the target bot, supergroup or channel in the format @username) + FromChatID ChatID `json:"from_chat_id"` + // A JSON-serialized list of 1-100 identifiers of messages in the chat from_chat_id to copy. The identifiers must be specified in a strictly increasing order. + MessageIds []int64 `json:"message_ids"` + // Sends the messages silently. Users will receive a notification with no sound. + DisableNotification *bool `json:"disable_notification,omitempty"` + // Protects the contents of the sent messages from forwarding and saving + ProtectContent *bool `json:"protect_content,omitempty"` + // Pass True to copy the messages without their captions + RemoveCaption *bool `json:"remove_caption,omitempty"` +} + +// CopyMessages calls the copyMessages Telegram Bot API method. +// +// Use this method to copy messages of any kind. If some of the specified messages can't be found or copied, they are skipped. Service messages, paid media messages, giveaway messages, giveaway winners messages, and invoice messages can't be copied. A quiz poll can be copied only if the value of the field correct_option_id is known to the bot. The method is analogous to the method forwardMessages, but the copied messages don't have a link to the original message. Album grouping is kept for copied messages. On success, an array of MessageId of the sent messages is returned. +func CopyMessages(ctx context.Context, b *client.Bot, p *CopyMessagesParams) ([]MessageId, error) { + return client.Call[*CopyMessagesParams, []MessageId](ctx, b, "copyMessages", p) +} + +// SendPhotoParams is the parameter set for SendPhoto. +// +// Use this method to send photos. On success, the sent Message is returned. +type SendPhotoParams struct { + // Unique identifier of the business connection on behalf of which the message will be sent + BusinessConnectionID string `json:"business_connection_id,omitempty"` + // Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username + ChatID ChatID `json:"chat_id"` + // Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only + MessageThreadID *int64 `json:"message_thread_id,omitempty"` + // Identifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat + DirectMessagesTopicID *int64 `json:"direct_messages_topic_id,omitempty"` + // Photo to send. Pass a file_id as String to send a photo that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a photo from the Internet, or upload a new photo using multipart/form-data. The photo must be at most 10 MB in size. The photo's width and height must not exceed 10000 in total. Width and height ratio must be at most 20. More information on Sending Files » + Photo *InputFile `json:"photo"` + // Photo caption (may also be used when resending photos by file_id), 0-1024 characters after entities parsing + Caption string `json:"caption,omitempty"` + // Mode for parsing entities in the photo caption. See formatting options for more details. + ParseMode string `json:"parse_mode,omitempty"` + // A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode + CaptionEntities []MessageEntity `json:"caption_entities,omitempty"` + // Pass True, if the caption must be shown above the message media + ShowCaptionAboveMedia *bool `json:"show_caption_above_media,omitempty"` + // Pass True if the photo needs to be covered with a spoiler animation + HasSpoiler *bool `json:"has_spoiler,omitempty"` + // Sends the message silently. Users will receive a notification with no sound. + DisableNotification *bool `json:"disable_notification,omitempty"` + // Protects the contents of the sent message from forwarding and saving + ProtectContent *bool `json:"protect_content,omitempty"` + // Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance. + AllowPaidBroadcast *bool `json:"allow_paid_broadcast,omitempty"` + // Unique identifier of the message effect to be added to the message; for private chats only + MessageEffectID string `json:"message_effect_id,omitempty"` + // A JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined. + SuggestedPostParameters *SuggestedPostParameters `json:"suggested_post_parameters,omitempty"` + // Description of the message to reply to + ReplyParameters *ReplyParameters `json:"reply_parameters,omitempty"` + // Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user + ReplyMarkup any `json:"reply_markup,omitempty"` +} + +// HasFile reports whether a multipart upload is required. +func (p *SendPhotoParams) HasFile() bool { + if p.Photo != nil && p.Photo.IsLocalUpload() { + return true + } + return false +} + +// MultipartFields returns the non-file fields used in the multipart body. +func (p *SendPhotoParams) MultipartFields() map[string]string { + out := map[string]string{} + if p.BusinessConnectionID != "" { + out["business_connection_id"] = p.BusinessConnectionID + } + out["chat_id"] = p.ChatID.String() + if p.MessageThreadID != nil { + out["message_thread_id"] = strconv.FormatInt(*p.MessageThreadID, 10) + } + if p.DirectMessagesTopicID != nil { + out["direct_messages_topic_id"] = strconv.FormatInt(*p.DirectMessagesTopicID, 10) + } + if p.Caption != "" { + out["caption"] = p.Caption + } + if p.ParseMode != "" { + out["parse_mode"] = p.ParseMode + } + if p.CaptionEntities != nil { + if b, _ := json.Marshal(p.CaptionEntities); len(b) > 0 { + out["caption_entities"] = string(b) + } + } + if p.ShowCaptionAboveMedia != nil { + out["show_caption_above_media"] = strconv.FormatBool(*p.ShowCaptionAboveMedia) + } + if p.HasSpoiler != nil { + out["has_spoiler"] = strconv.FormatBool(*p.HasSpoiler) + } + if p.DisableNotification != nil { + out["disable_notification"] = strconv.FormatBool(*p.DisableNotification) + } + if p.ProtectContent != nil { + out["protect_content"] = strconv.FormatBool(*p.ProtectContent) + } + if p.AllowPaidBroadcast != nil { + out["allow_paid_broadcast"] = strconv.FormatBool(*p.AllowPaidBroadcast) + } + if p.MessageEffectID != "" { + out["message_effect_id"] = p.MessageEffectID + } + if p.SuggestedPostParameters != nil { + if b, _ := json.Marshal(p.SuggestedPostParameters); len(b) > 0 { + out["suggested_post_parameters"] = string(b) + } + } + if p.ReplyParameters != nil { + if b, _ := json.Marshal(p.ReplyParameters); len(b) > 0 { + out["reply_parameters"] = string(b) + } + } + if p.ReplyMarkup != nil { + if b, _ := json.Marshal(p.ReplyMarkup); len(b) > 0 && string(b) != "null" { + out["reply_markup"] = string(b) + } + } + return out +} + +// MultipartFiles returns the file parts. +func (p *SendPhotoParams) MultipartFiles() []client.MultipartFile { + var files []client.MultipartFile + if p.Photo != nil && p.Photo.IsLocalUpload() { + name := p.Photo.Filename + if name == "" { + name = "photo" + } + files = append(files, client.MultipartFile{FieldName: "photo", Filename: name, Reader: p.Photo.Reader}) + } + return files +} + +// SendPhoto calls the sendPhoto Telegram Bot API method. +// +// Use this method to send photos. On success, the sent Message is returned. +func SendPhoto(ctx context.Context, b *client.Bot, p *SendPhotoParams) (*Message, error) { + return client.Call[*SendPhotoParams, *Message](ctx, b, "sendPhoto", p) +} + +// SendLivePhotoParams is the parameter set for SendLivePhoto. +// +// Use this method to send live photos. On success, the sent Message is returned. +type SendLivePhotoParams struct { + // Unique identifier of the business connection on behalf of which the message will be sent + BusinessConnectionID string `json:"business_connection_id,omitempty"` + // Unique identifier for the target chat or username of the target channel (in the format @channelusername) + ChatID ChatID `json:"chat_id"` + // Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only + MessageThreadID *int64 `json:"message_thread_id,omitempty"` + // Identifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat + DirectMessagesTopicID *int64 `json:"direct_messages_topic_id,omitempty"` + // Live photo video to send. The video must be no longer than 10 seconds and must not exceed 10 MB in size. Pass a file_id as String to send a video that exists on the Telegram servers (recommended) or upload a new video using multipart/form-data. More information on Sending Files ». Sending live photos by a URL is currently unsupported. + LivePhoto *InputFile `json:"live_photo"` + // The static photo to send. Pass a file_id as String to send a photo that exists on the Telegram servers (recommended) or upload a new video using multipart/form-data. More information on Sending Files ». Sending live photos by a URL is currently unsupported. + Photo *InputFile `json:"photo"` + // Video caption (may also be used when resending videos by file_id), 0-1024 characters after entities parsing + Caption string `json:"caption,omitempty"` + // Mode for parsing entities in the video caption. See formatting options for more details. + ParseMode string `json:"parse_mode,omitempty"` + // A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode + CaptionEntities []MessageEntity `json:"caption_entities,omitempty"` + // Pass True, if the caption must be shown above the message media + ShowCaptionAboveMedia *bool `json:"show_caption_above_media,omitempty"` + // Pass True if the video needs to be covered with a spoiler animation + HasSpoiler *bool `json:"has_spoiler,omitempty"` + // Sends the message silently. Users will receive a notification with no sound. + DisableNotification *bool `json:"disable_notification,omitempty"` + // Protects the contents of the sent message from forwarding and saving + ProtectContent *bool `json:"protect_content,omitempty"` + // Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance. + AllowPaidBroadcast *bool `json:"allow_paid_broadcast,omitempty"` + // Unique identifier of the message effect to be added to the message; for private chats only + MessageEffectID string `json:"message_effect_id,omitempty"` + // A JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined. + SuggestedPostParameters *SuggestedPostParameters `json:"suggested_post_parameters,omitempty"` + // Description of the message to reply to + ReplyParameters *ReplyParameters `json:"reply_parameters,omitempty"` + // Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user. + ReplyMarkup any `json:"reply_markup,omitempty"` +} + +// HasFile reports whether a multipart upload is required. +func (p *SendLivePhotoParams) HasFile() bool { + if p.LivePhoto != nil && p.LivePhoto.IsLocalUpload() { + return true + } + if p.Photo != nil && p.Photo.IsLocalUpload() { + return true + } + return false +} + +// MultipartFields returns the non-file fields used in the multipart body. +func (p *SendLivePhotoParams) MultipartFields() map[string]string { + out := map[string]string{} + if p.BusinessConnectionID != "" { + out["business_connection_id"] = p.BusinessConnectionID + } + out["chat_id"] = p.ChatID.String() + if p.MessageThreadID != nil { + out["message_thread_id"] = strconv.FormatInt(*p.MessageThreadID, 10) + } + if p.DirectMessagesTopicID != nil { + out["direct_messages_topic_id"] = strconv.FormatInt(*p.DirectMessagesTopicID, 10) + } + if p.Caption != "" { + out["caption"] = p.Caption + } + if p.ParseMode != "" { + out["parse_mode"] = p.ParseMode + } + if p.CaptionEntities != nil { + if b, _ := json.Marshal(p.CaptionEntities); len(b) > 0 { + out["caption_entities"] = string(b) + } + } + if p.ShowCaptionAboveMedia != nil { + out["show_caption_above_media"] = strconv.FormatBool(*p.ShowCaptionAboveMedia) + } + if p.HasSpoiler != nil { + out["has_spoiler"] = strconv.FormatBool(*p.HasSpoiler) + } + if p.DisableNotification != nil { + out["disable_notification"] = strconv.FormatBool(*p.DisableNotification) + } + if p.ProtectContent != nil { + out["protect_content"] = strconv.FormatBool(*p.ProtectContent) + } + if p.AllowPaidBroadcast != nil { + out["allow_paid_broadcast"] = strconv.FormatBool(*p.AllowPaidBroadcast) + } + if p.MessageEffectID != "" { + out["message_effect_id"] = p.MessageEffectID + } + if p.SuggestedPostParameters != nil { + if b, _ := json.Marshal(p.SuggestedPostParameters); len(b) > 0 { + out["suggested_post_parameters"] = string(b) + } + } + if p.ReplyParameters != nil { + if b, _ := json.Marshal(p.ReplyParameters); len(b) > 0 { + out["reply_parameters"] = string(b) + } + } + if p.ReplyMarkup != nil { + if b, _ := json.Marshal(p.ReplyMarkup); len(b) > 0 && string(b) != "null" { + out["reply_markup"] = string(b) + } + } + return out +} + +// MultipartFiles returns the file parts. +func (p *SendLivePhotoParams) MultipartFiles() []client.MultipartFile { + var files []client.MultipartFile + if p.LivePhoto != nil && p.LivePhoto.IsLocalUpload() { + name := p.LivePhoto.Filename + if name == "" { + name = "live_photo" + } + files = append(files, client.MultipartFile{FieldName: "live_photo", Filename: name, Reader: p.LivePhoto.Reader}) + } + if p.Photo != nil && p.Photo.IsLocalUpload() { + name := p.Photo.Filename + if name == "" { + name = "photo" + } + files = append(files, client.MultipartFile{FieldName: "photo", Filename: name, Reader: p.Photo.Reader}) + } + return files +} + +// SendLivePhoto calls the sendLivePhoto Telegram Bot API method. +// +// Use this method to send live photos. On success, the sent Message is returned. +func SendLivePhoto(ctx context.Context, b *client.Bot, p *SendLivePhotoParams) (*Message, error) { + return client.Call[*SendLivePhotoParams, *Message](ctx, b, "sendLivePhoto", p) +} + +// SendAudioParams is the parameter set for SendAudio. +// +// Use this method to send audio files, if you want Telegram clients to display them in the music player. Your audio must be in the .MP3 or .M4A format. On success, the sent Message is returned. Bots can currently send audio files of up to 50 MB in size, this limit may be changed in the future. +// For sending voice messages, use the sendVoice method instead. +type SendAudioParams struct { + // Unique identifier of the business connection on behalf of which the message will be sent + BusinessConnectionID string `json:"business_connection_id,omitempty"` + // Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username + ChatID ChatID `json:"chat_id"` + // Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only + MessageThreadID *int64 `json:"message_thread_id,omitempty"` + // Identifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat + DirectMessagesTopicID *int64 `json:"direct_messages_topic_id,omitempty"` + // Audio file to send. Pass a file_id as String to send an audio file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an audio file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files » + Audio *InputFile `json:"audio"` + // Audio caption, 0-1024 characters after entities parsing + Caption string `json:"caption,omitempty"` + // Mode for parsing entities in the audio caption. See formatting options for more details. + ParseMode string `json:"parse_mode,omitempty"` + // A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode + CaptionEntities []MessageEntity `json:"caption_entities,omitempty"` + // Duration of the audio in seconds + Duration *int64 `json:"duration,omitempty"` + // Performer + Performer string `json:"performer,omitempty"` + // Track name + Title string `json:"title,omitempty"` + // Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://” if the thumbnail was uploaded using multipart/form-data under . More information on Sending Files » + Thumbnail *InputFile `json:"thumbnail,omitempty"` + // Sends the message silently. Users will receive a notification with no sound. + DisableNotification *bool `json:"disable_notification,omitempty"` + // Protects the contents of the sent message from forwarding and saving + ProtectContent *bool `json:"protect_content,omitempty"` + // Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance. + AllowPaidBroadcast *bool `json:"allow_paid_broadcast,omitempty"` + // Unique identifier of the message effect to be added to the message; for private chats only + MessageEffectID string `json:"message_effect_id,omitempty"` + // A JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined. + SuggestedPostParameters *SuggestedPostParameters `json:"suggested_post_parameters,omitempty"` + // Description of the message to reply to + ReplyParameters *ReplyParameters `json:"reply_parameters,omitempty"` + // Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user + ReplyMarkup any `json:"reply_markup,omitempty"` +} + +// HasFile reports whether a multipart upload is required. +func (p *SendAudioParams) HasFile() bool { + if p.Audio != nil && p.Audio.IsLocalUpload() { + return true + } + if p.Thumbnail != nil && p.Thumbnail.IsLocalUpload() { + return true + } + return false +} + +// MultipartFields returns the non-file fields used in the multipart body. +func (p *SendAudioParams) MultipartFields() map[string]string { + out := map[string]string{} + if p.BusinessConnectionID != "" { + out["business_connection_id"] = p.BusinessConnectionID + } + out["chat_id"] = p.ChatID.String() + if p.MessageThreadID != nil { + out["message_thread_id"] = strconv.FormatInt(*p.MessageThreadID, 10) + } + if p.DirectMessagesTopicID != nil { + out["direct_messages_topic_id"] = strconv.FormatInt(*p.DirectMessagesTopicID, 10) + } + if p.Caption != "" { + out["caption"] = p.Caption + } + if p.ParseMode != "" { + out["parse_mode"] = p.ParseMode + } + if p.CaptionEntities != nil { + if b, _ := json.Marshal(p.CaptionEntities); len(b) > 0 { + out["caption_entities"] = string(b) + } + } + if p.Duration != nil { + out["duration"] = strconv.FormatInt(*p.Duration, 10) + } + if p.Performer != "" { + out["performer"] = p.Performer + } + if p.Title != "" { + out["title"] = p.Title + } + if p.DisableNotification != nil { + out["disable_notification"] = strconv.FormatBool(*p.DisableNotification) + } + if p.ProtectContent != nil { + out["protect_content"] = strconv.FormatBool(*p.ProtectContent) + } + if p.AllowPaidBroadcast != nil { + out["allow_paid_broadcast"] = strconv.FormatBool(*p.AllowPaidBroadcast) + } + if p.MessageEffectID != "" { + out["message_effect_id"] = p.MessageEffectID + } + if p.SuggestedPostParameters != nil { + if b, _ := json.Marshal(p.SuggestedPostParameters); len(b) > 0 { + out["suggested_post_parameters"] = string(b) + } + } + if p.ReplyParameters != nil { + if b, _ := json.Marshal(p.ReplyParameters); len(b) > 0 { + out["reply_parameters"] = string(b) + } + } + if p.ReplyMarkup != nil { + if b, _ := json.Marshal(p.ReplyMarkup); len(b) > 0 && string(b) != "null" { + out["reply_markup"] = string(b) + } + } + return out +} + +// MultipartFiles returns the file parts. +func (p *SendAudioParams) MultipartFiles() []client.MultipartFile { + var files []client.MultipartFile + if p.Audio != nil && p.Audio.IsLocalUpload() { + name := p.Audio.Filename + if name == "" { + name = "audio" + } + files = append(files, client.MultipartFile{FieldName: "audio", Filename: name, Reader: p.Audio.Reader}) + } + if p.Thumbnail != nil && p.Thumbnail.IsLocalUpload() { + name := p.Thumbnail.Filename + if name == "" { + name = "thumbnail" + } + files = append(files, client.MultipartFile{FieldName: "thumbnail", Filename: name, Reader: p.Thumbnail.Reader}) + } + return files +} + +// SendAudio calls the sendAudio Telegram Bot API method. +// +// Use this method to send audio files, if you want Telegram clients to display them in the music player. Your audio must be in the .MP3 or .M4A format. On success, the sent Message is returned. Bots can currently send audio files of up to 50 MB in size, this limit may be changed in the future. +// For sending voice messages, use the sendVoice method instead. +func SendAudio(ctx context.Context, b *client.Bot, p *SendAudioParams) (*Message, error) { + return client.Call[*SendAudioParams, *Message](ctx, b, "sendAudio", p) +} + +// SendDocumentParams is the parameter set for SendDocument. +// +// Use this method to send general files. On success, the sent Message is returned. Bots can currently send files of any type of up to 50 MB in size, this limit may be changed in the future. +type SendDocumentParams struct { + // Unique identifier of the business connection on behalf of which the message will be sent + BusinessConnectionID string `json:"business_connection_id,omitempty"` + // Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username + ChatID ChatID `json:"chat_id"` + // Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only + MessageThreadID *int64 `json:"message_thread_id,omitempty"` + // Identifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat + DirectMessagesTopicID *int64 `json:"direct_messages_topic_id,omitempty"` + // File to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files » + Document *InputFile `json:"document"` + // Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://” if the thumbnail was uploaded using multipart/form-data under . More information on Sending Files » + Thumbnail *InputFile `json:"thumbnail,omitempty"` + // Document caption (may also be used when resending documents by file_id), 0-1024 characters after entities parsing + Caption string `json:"caption,omitempty"` + // Mode for parsing entities in the document caption. See formatting options for more details. + ParseMode string `json:"parse_mode,omitempty"` + // A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode + CaptionEntities []MessageEntity `json:"caption_entities,omitempty"` + // Disables automatic server-side content type detection for files uploaded using multipart/form-data + DisableContentTypeDetection *bool `json:"disable_content_type_detection,omitempty"` + // Sends the message silently. Users will receive a notification with no sound. + DisableNotification *bool `json:"disable_notification,omitempty"` + // Protects the contents of the sent message from forwarding and saving + ProtectContent *bool `json:"protect_content,omitempty"` + // Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance. + AllowPaidBroadcast *bool `json:"allow_paid_broadcast,omitempty"` + // Unique identifier of the message effect to be added to the message; for private chats only + MessageEffectID string `json:"message_effect_id,omitempty"` + // A JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined. + SuggestedPostParameters *SuggestedPostParameters `json:"suggested_post_parameters,omitempty"` + // Description of the message to reply to + ReplyParameters *ReplyParameters `json:"reply_parameters,omitempty"` + // Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user + ReplyMarkup any `json:"reply_markup,omitempty"` +} + +// HasFile reports whether a multipart upload is required. +func (p *SendDocumentParams) HasFile() bool { + if p.Document != nil && p.Document.IsLocalUpload() { + return true + } + if p.Thumbnail != nil && p.Thumbnail.IsLocalUpload() { + return true + } + return false +} + +// MultipartFields returns the non-file fields used in the multipart body. +func (p *SendDocumentParams) MultipartFields() map[string]string { + out := map[string]string{} + if p.BusinessConnectionID != "" { + out["business_connection_id"] = p.BusinessConnectionID + } + out["chat_id"] = p.ChatID.String() + if p.MessageThreadID != nil { + out["message_thread_id"] = strconv.FormatInt(*p.MessageThreadID, 10) + } + if p.DirectMessagesTopicID != nil { + out["direct_messages_topic_id"] = strconv.FormatInt(*p.DirectMessagesTopicID, 10) + } + if p.Caption != "" { + out["caption"] = p.Caption + } + if p.ParseMode != "" { + out["parse_mode"] = p.ParseMode + } + if p.CaptionEntities != nil { + if b, _ := json.Marshal(p.CaptionEntities); len(b) > 0 { + out["caption_entities"] = string(b) + } + } + if p.DisableContentTypeDetection != nil { + out["disable_content_type_detection"] = strconv.FormatBool(*p.DisableContentTypeDetection) + } + if p.DisableNotification != nil { + out["disable_notification"] = strconv.FormatBool(*p.DisableNotification) + } + if p.ProtectContent != nil { + out["protect_content"] = strconv.FormatBool(*p.ProtectContent) + } + if p.AllowPaidBroadcast != nil { + out["allow_paid_broadcast"] = strconv.FormatBool(*p.AllowPaidBroadcast) + } + if p.MessageEffectID != "" { + out["message_effect_id"] = p.MessageEffectID + } + if p.SuggestedPostParameters != nil { + if b, _ := json.Marshal(p.SuggestedPostParameters); len(b) > 0 { + out["suggested_post_parameters"] = string(b) + } + } + if p.ReplyParameters != nil { + if b, _ := json.Marshal(p.ReplyParameters); len(b) > 0 { + out["reply_parameters"] = string(b) + } + } + if p.ReplyMarkup != nil { + if b, _ := json.Marshal(p.ReplyMarkup); len(b) > 0 && string(b) != "null" { + out["reply_markup"] = string(b) + } + } + return out +} + +// MultipartFiles returns the file parts. +func (p *SendDocumentParams) MultipartFiles() []client.MultipartFile { + var files []client.MultipartFile + if p.Document != nil && p.Document.IsLocalUpload() { + name := p.Document.Filename + if name == "" { + name = "document" + } + files = append(files, client.MultipartFile{FieldName: "document", Filename: name, Reader: p.Document.Reader}) + } + if p.Thumbnail != nil && p.Thumbnail.IsLocalUpload() { + name := p.Thumbnail.Filename + if name == "" { + name = "thumbnail" + } + files = append(files, client.MultipartFile{FieldName: "thumbnail", Filename: name, Reader: p.Thumbnail.Reader}) + } + return files +} + +// SendDocument calls the sendDocument Telegram Bot API method. +// +// Use this method to send general files. On success, the sent Message is returned. Bots can currently send files of any type of up to 50 MB in size, this limit may be changed in the future. +func SendDocument(ctx context.Context, b *client.Bot, p *SendDocumentParams) (*Message, error) { + return client.Call[*SendDocumentParams, *Message](ctx, b, "sendDocument", p) +} + +// SendVideoParams is the parameter set for SendVideo. +// +// Use this method to send video files, Telegram clients support MPEG4 videos (other formats may be sent as Document). On success, the sent Message is returned. Bots can currently send video files of up to 50 MB in size, this limit may be changed in the future. +type SendVideoParams struct { + // Unique identifier of the business connection on behalf of which the message will be sent + BusinessConnectionID string `json:"business_connection_id,omitempty"` + // Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username + ChatID ChatID `json:"chat_id"` + // Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only + MessageThreadID *int64 `json:"message_thread_id,omitempty"` + // Identifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat + DirectMessagesTopicID *int64 `json:"direct_messages_topic_id,omitempty"` + // Video to send. Pass a file_id as String to send a video that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a video from the Internet, or upload a new video using multipart/form-data. More information on Sending Files » + Video *InputFile `json:"video"` + // Duration of sent video in seconds + Duration *int64 `json:"duration,omitempty"` + // Video width + Width *int64 `json:"width,omitempty"` + // Video height + Height *int64 `json:"height,omitempty"` + // Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://” if the thumbnail was uploaded using multipart/form-data under . More information on Sending Files » + Thumbnail *InputFile `json:"thumbnail,omitempty"` + // Cover for the video in the message. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet, or pass “attach://” to upload a new one using multipart/form-data under name. More information on Sending Files » + Cover *InputFile `json:"cover,omitempty"` + // Start timestamp for the video in the message + StartTimestamp *int64 `json:"start_timestamp,omitempty"` + // Video caption (may also be used when resending videos by file_id), 0-1024 characters after entities parsing + Caption string `json:"caption,omitempty"` + // Mode for parsing entities in the video caption. See formatting options for more details. + ParseMode string `json:"parse_mode,omitempty"` + // A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode + CaptionEntities []MessageEntity `json:"caption_entities,omitempty"` + // Pass True, if the caption must be shown above the message media + ShowCaptionAboveMedia *bool `json:"show_caption_above_media,omitempty"` + // Pass True if the video needs to be covered with a spoiler animation + HasSpoiler *bool `json:"has_spoiler,omitempty"` + // Pass True if the uploaded video is suitable for streaming + SupportsStreaming *bool `json:"supports_streaming,omitempty"` + // Sends the message silently. Users will receive a notification with no sound. + DisableNotification *bool `json:"disable_notification,omitempty"` + // Protects the contents of the sent message from forwarding and saving + ProtectContent *bool `json:"protect_content,omitempty"` + // Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance. + AllowPaidBroadcast *bool `json:"allow_paid_broadcast,omitempty"` + // Unique identifier of the message effect to be added to the message; for private chats only + MessageEffectID string `json:"message_effect_id,omitempty"` + // A JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined. + SuggestedPostParameters *SuggestedPostParameters `json:"suggested_post_parameters,omitempty"` + // Description of the message to reply to + ReplyParameters *ReplyParameters `json:"reply_parameters,omitempty"` + // Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user + ReplyMarkup any `json:"reply_markup,omitempty"` +} + +// HasFile reports whether a multipart upload is required. +func (p *SendVideoParams) HasFile() bool { + if p.Video != nil && p.Video.IsLocalUpload() { + return true + } + if p.Thumbnail != nil && p.Thumbnail.IsLocalUpload() { + return true + } + if p.Cover != nil && p.Cover.IsLocalUpload() { + return true + } + return false +} + +// MultipartFields returns the non-file fields used in the multipart body. +func (p *SendVideoParams) MultipartFields() map[string]string { + out := map[string]string{} + if p.BusinessConnectionID != "" { + out["business_connection_id"] = p.BusinessConnectionID + } + out["chat_id"] = p.ChatID.String() + if p.MessageThreadID != nil { + out["message_thread_id"] = strconv.FormatInt(*p.MessageThreadID, 10) + } + if p.DirectMessagesTopicID != nil { + out["direct_messages_topic_id"] = strconv.FormatInt(*p.DirectMessagesTopicID, 10) + } + if p.Duration != nil { + out["duration"] = strconv.FormatInt(*p.Duration, 10) + } + if p.Width != nil { + out["width"] = strconv.FormatInt(*p.Width, 10) + } + if p.Height != nil { + out["height"] = strconv.FormatInt(*p.Height, 10) + } + if p.StartTimestamp != nil { + out["start_timestamp"] = strconv.FormatInt(*p.StartTimestamp, 10) + } + if p.Caption != "" { + out["caption"] = p.Caption + } + if p.ParseMode != "" { + out["parse_mode"] = p.ParseMode + } + if p.CaptionEntities != nil { + if b, _ := json.Marshal(p.CaptionEntities); len(b) > 0 { + out["caption_entities"] = string(b) + } + } + if p.ShowCaptionAboveMedia != nil { + out["show_caption_above_media"] = strconv.FormatBool(*p.ShowCaptionAboveMedia) + } + if p.HasSpoiler != nil { + out["has_spoiler"] = strconv.FormatBool(*p.HasSpoiler) + } + if p.SupportsStreaming != nil { + out["supports_streaming"] = strconv.FormatBool(*p.SupportsStreaming) + } + if p.DisableNotification != nil { + out["disable_notification"] = strconv.FormatBool(*p.DisableNotification) + } + if p.ProtectContent != nil { + out["protect_content"] = strconv.FormatBool(*p.ProtectContent) + } + if p.AllowPaidBroadcast != nil { + out["allow_paid_broadcast"] = strconv.FormatBool(*p.AllowPaidBroadcast) + } + if p.MessageEffectID != "" { + out["message_effect_id"] = p.MessageEffectID + } + if p.SuggestedPostParameters != nil { + if b, _ := json.Marshal(p.SuggestedPostParameters); len(b) > 0 { + out["suggested_post_parameters"] = string(b) + } + } + if p.ReplyParameters != nil { + if b, _ := json.Marshal(p.ReplyParameters); len(b) > 0 { + out["reply_parameters"] = string(b) + } + } + if p.ReplyMarkup != nil { + if b, _ := json.Marshal(p.ReplyMarkup); len(b) > 0 && string(b) != "null" { + out["reply_markup"] = string(b) + } + } + return out +} + +// MultipartFiles returns the file parts. +func (p *SendVideoParams) MultipartFiles() []client.MultipartFile { + var files []client.MultipartFile + if p.Video != nil && p.Video.IsLocalUpload() { + name := p.Video.Filename + if name == "" { + name = "video" + } + files = append(files, client.MultipartFile{FieldName: "video", Filename: name, Reader: p.Video.Reader}) + } + if p.Thumbnail != nil && p.Thumbnail.IsLocalUpload() { + name := p.Thumbnail.Filename + if name == "" { + name = "thumbnail" + } + files = append(files, client.MultipartFile{FieldName: "thumbnail", Filename: name, Reader: p.Thumbnail.Reader}) + } + if p.Cover != nil && p.Cover.IsLocalUpload() { + name := p.Cover.Filename + if name == "" { + name = "cover" + } + files = append(files, client.MultipartFile{FieldName: "cover", Filename: name, Reader: p.Cover.Reader}) + } + return files +} + +// SendVideo calls the sendVideo Telegram Bot API method. +// +// Use this method to send video files, Telegram clients support MPEG4 videos (other formats may be sent as Document). On success, the sent Message is returned. Bots can currently send video files of up to 50 MB in size, this limit may be changed in the future. +func SendVideo(ctx context.Context, b *client.Bot, p *SendVideoParams) (*Message, error) { + return client.Call[*SendVideoParams, *Message](ctx, b, "sendVideo", p) +} + +// SendAnimationParams is the parameter set for SendAnimation. +// +// Use this method to send animation files (GIF or H.264/MPEG-4 AVC video without sound). On success, the sent Message is returned. Bots can currently send animation files of up to 50 MB in size, this limit may be changed in the future. +type SendAnimationParams struct { + // Unique identifier of the business connection on behalf of which the message will be sent + BusinessConnectionID string `json:"business_connection_id,omitempty"` + // Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username + ChatID ChatID `json:"chat_id"` + // Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only + MessageThreadID *int64 `json:"message_thread_id,omitempty"` + // Identifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat + DirectMessagesTopicID *int64 `json:"direct_messages_topic_id,omitempty"` + // Animation to send. Pass a file_id as String to send an animation that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an animation from the Internet, or upload a new animation using multipart/form-data. More information on Sending Files » + Animation *InputFile `json:"animation"` + // Duration of sent animation in seconds + Duration *int64 `json:"duration,omitempty"` + // Animation width + Width *int64 `json:"width,omitempty"` + // Animation height + Height *int64 `json:"height,omitempty"` + // Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://” if the thumbnail was uploaded using multipart/form-data under . More information on Sending Files » + Thumbnail *InputFile `json:"thumbnail,omitempty"` + // Animation caption (may also be used when resending animation by file_id), 0-1024 characters after entities parsing + Caption string `json:"caption,omitempty"` + // Mode for parsing entities in the animation caption. See formatting options for more details. + ParseMode string `json:"parse_mode,omitempty"` + // A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode + CaptionEntities []MessageEntity `json:"caption_entities,omitempty"` + // Pass True, if the caption must be shown above the message media + ShowCaptionAboveMedia *bool `json:"show_caption_above_media,omitempty"` + // Pass True if the animation needs to be covered with a spoiler animation + HasSpoiler *bool `json:"has_spoiler,omitempty"` + // Sends the message silently. Users will receive a notification with no sound. + DisableNotification *bool `json:"disable_notification,omitempty"` + // Protects the contents of the sent message from forwarding and saving + ProtectContent *bool `json:"protect_content,omitempty"` + // Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance. + AllowPaidBroadcast *bool `json:"allow_paid_broadcast,omitempty"` + // Unique identifier of the message effect to be added to the message; for private chats only + MessageEffectID string `json:"message_effect_id,omitempty"` + // A JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined. + SuggestedPostParameters *SuggestedPostParameters `json:"suggested_post_parameters,omitempty"` + // Description of the message to reply to + ReplyParameters *ReplyParameters `json:"reply_parameters,omitempty"` + // Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user + ReplyMarkup any `json:"reply_markup,omitempty"` +} + +// HasFile reports whether a multipart upload is required. +func (p *SendAnimationParams) HasFile() bool { + if p.Animation != nil && p.Animation.IsLocalUpload() { + return true + } + if p.Thumbnail != nil && p.Thumbnail.IsLocalUpload() { + return true + } + return false +} + +// MultipartFields returns the non-file fields used in the multipart body. +func (p *SendAnimationParams) MultipartFields() map[string]string { + out := map[string]string{} + if p.BusinessConnectionID != "" { + out["business_connection_id"] = p.BusinessConnectionID + } + out["chat_id"] = p.ChatID.String() + if p.MessageThreadID != nil { + out["message_thread_id"] = strconv.FormatInt(*p.MessageThreadID, 10) + } + if p.DirectMessagesTopicID != nil { + out["direct_messages_topic_id"] = strconv.FormatInt(*p.DirectMessagesTopicID, 10) + } + if p.Duration != nil { + out["duration"] = strconv.FormatInt(*p.Duration, 10) + } + if p.Width != nil { + out["width"] = strconv.FormatInt(*p.Width, 10) + } + if p.Height != nil { + out["height"] = strconv.FormatInt(*p.Height, 10) + } + if p.Caption != "" { + out["caption"] = p.Caption + } + if p.ParseMode != "" { + out["parse_mode"] = p.ParseMode + } + if p.CaptionEntities != nil { + if b, _ := json.Marshal(p.CaptionEntities); len(b) > 0 { + out["caption_entities"] = string(b) + } + } + if p.ShowCaptionAboveMedia != nil { + out["show_caption_above_media"] = strconv.FormatBool(*p.ShowCaptionAboveMedia) + } + if p.HasSpoiler != nil { + out["has_spoiler"] = strconv.FormatBool(*p.HasSpoiler) + } + if p.DisableNotification != nil { + out["disable_notification"] = strconv.FormatBool(*p.DisableNotification) + } + if p.ProtectContent != nil { + out["protect_content"] = strconv.FormatBool(*p.ProtectContent) + } + if p.AllowPaidBroadcast != nil { + out["allow_paid_broadcast"] = strconv.FormatBool(*p.AllowPaidBroadcast) + } + if p.MessageEffectID != "" { + out["message_effect_id"] = p.MessageEffectID + } + if p.SuggestedPostParameters != nil { + if b, _ := json.Marshal(p.SuggestedPostParameters); len(b) > 0 { + out["suggested_post_parameters"] = string(b) + } + } + if p.ReplyParameters != nil { + if b, _ := json.Marshal(p.ReplyParameters); len(b) > 0 { + out["reply_parameters"] = string(b) + } + } + if p.ReplyMarkup != nil { + if b, _ := json.Marshal(p.ReplyMarkup); len(b) > 0 && string(b) != "null" { + out["reply_markup"] = string(b) + } + } + return out +} + +// MultipartFiles returns the file parts. +func (p *SendAnimationParams) MultipartFiles() []client.MultipartFile { + var files []client.MultipartFile + if p.Animation != nil && p.Animation.IsLocalUpload() { + name := p.Animation.Filename + if name == "" { + name = "animation" + } + files = append(files, client.MultipartFile{FieldName: "animation", Filename: name, Reader: p.Animation.Reader}) + } + if p.Thumbnail != nil && p.Thumbnail.IsLocalUpload() { + name := p.Thumbnail.Filename + if name == "" { + name = "thumbnail" + } + files = append(files, client.MultipartFile{FieldName: "thumbnail", Filename: name, Reader: p.Thumbnail.Reader}) + } + return files +} + +// SendAnimation calls the sendAnimation Telegram Bot API method. +// +// Use this method to send animation files (GIF or H.264/MPEG-4 AVC video without sound). On success, the sent Message is returned. Bots can currently send animation files of up to 50 MB in size, this limit may be changed in the future. +func SendAnimation(ctx context.Context, b *client.Bot, p *SendAnimationParams) (*Message, error) { + return client.Call[*SendAnimationParams, *Message](ctx, b, "sendAnimation", p) +} + +// SendVoiceParams is the parameter set for SendVoice. +// +// Use this method to send audio files, if you want Telegram clients to display the file as a playable voice message. For this to work, your audio must be in an .OGG file encoded with OPUS, or in .MP3 format, or in .M4A format (other formats may be sent as Audio or Document). On success, the sent Message is returned. Bots can currently send voice messages of up to 50 MB in size, this limit may be changed in the future. +type SendVoiceParams struct { + // Unique identifier of the business connection on behalf of which the message will be sent + BusinessConnectionID string `json:"business_connection_id,omitempty"` + // Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username + ChatID ChatID `json:"chat_id"` + // Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only + MessageThreadID *int64 `json:"message_thread_id,omitempty"` + // Identifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat + DirectMessagesTopicID *int64 `json:"direct_messages_topic_id,omitempty"` + // Audio file to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files » + Voice *InputFile `json:"voice"` + // Voice message caption, 0-1024 characters after entities parsing + Caption string `json:"caption,omitempty"` + // Mode for parsing entities in the voice message caption. See formatting options for more details. + ParseMode string `json:"parse_mode,omitempty"` + // A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode + CaptionEntities []MessageEntity `json:"caption_entities,omitempty"` + // Duration of the voice message in seconds + Duration *int64 `json:"duration,omitempty"` + // Sends the message silently. Users will receive a notification with no sound. + DisableNotification *bool `json:"disable_notification,omitempty"` + // Protects the contents of the sent message from forwarding and saving + ProtectContent *bool `json:"protect_content,omitempty"` + // Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance. + AllowPaidBroadcast *bool `json:"allow_paid_broadcast,omitempty"` + // Unique identifier of the message effect to be added to the message; for private chats only + MessageEffectID string `json:"message_effect_id,omitempty"` + // A JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined. + SuggestedPostParameters *SuggestedPostParameters `json:"suggested_post_parameters,omitempty"` + // Description of the message to reply to + ReplyParameters *ReplyParameters `json:"reply_parameters,omitempty"` + // Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user + ReplyMarkup any `json:"reply_markup,omitempty"` +} + +// HasFile reports whether a multipart upload is required. +func (p *SendVoiceParams) HasFile() bool { + if p.Voice != nil && p.Voice.IsLocalUpload() { + return true + } + return false +} + +// MultipartFields returns the non-file fields used in the multipart body. +func (p *SendVoiceParams) MultipartFields() map[string]string { + out := map[string]string{} + if p.BusinessConnectionID != "" { + out["business_connection_id"] = p.BusinessConnectionID + } + out["chat_id"] = p.ChatID.String() + if p.MessageThreadID != nil { + out["message_thread_id"] = strconv.FormatInt(*p.MessageThreadID, 10) + } + if p.DirectMessagesTopicID != nil { + out["direct_messages_topic_id"] = strconv.FormatInt(*p.DirectMessagesTopicID, 10) + } + if p.Caption != "" { + out["caption"] = p.Caption + } + if p.ParseMode != "" { + out["parse_mode"] = p.ParseMode + } + if p.CaptionEntities != nil { + if b, _ := json.Marshal(p.CaptionEntities); len(b) > 0 { + out["caption_entities"] = string(b) + } + } + if p.Duration != nil { + out["duration"] = strconv.FormatInt(*p.Duration, 10) + } + if p.DisableNotification != nil { + out["disable_notification"] = strconv.FormatBool(*p.DisableNotification) + } + if p.ProtectContent != nil { + out["protect_content"] = strconv.FormatBool(*p.ProtectContent) + } + if p.AllowPaidBroadcast != nil { + out["allow_paid_broadcast"] = strconv.FormatBool(*p.AllowPaidBroadcast) + } + if p.MessageEffectID != "" { + out["message_effect_id"] = p.MessageEffectID + } + if p.SuggestedPostParameters != nil { + if b, _ := json.Marshal(p.SuggestedPostParameters); len(b) > 0 { + out["suggested_post_parameters"] = string(b) + } + } + if p.ReplyParameters != nil { + if b, _ := json.Marshal(p.ReplyParameters); len(b) > 0 { + out["reply_parameters"] = string(b) + } + } + if p.ReplyMarkup != nil { + if b, _ := json.Marshal(p.ReplyMarkup); len(b) > 0 && string(b) != "null" { + out["reply_markup"] = string(b) + } + } + return out +} + +// MultipartFiles returns the file parts. +func (p *SendVoiceParams) MultipartFiles() []client.MultipartFile { + var files []client.MultipartFile + if p.Voice != nil && p.Voice.IsLocalUpload() { + name := p.Voice.Filename + if name == "" { + name = "voice" + } + files = append(files, client.MultipartFile{FieldName: "voice", Filename: name, Reader: p.Voice.Reader}) + } + return files +} + +// SendVoice calls the sendVoice Telegram Bot API method. +// +// Use this method to send audio files, if you want Telegram clients to display the file as a playable voice message. For this to work, your audio must be in an .OGG file encoded with OPUS, or in .MP3 format, or in .M4A format (other formats may be sent as Audio or Document). On success, the sent Message is returned. Bots can currently send voice messages of up to 50 MB in size, this limit may be changed in the future. +func SendVoice(ctx context.Context, b *client.Bot, p *SendVoiceParams) (*Message, error) { + return client.Call[*SendVoiceParams, *Message](ctx, b, "sendVoice", p) +} + +// SendVideoNoteParams is the parameter set for SendVideoNote. +// +// As of v.4.0, Telegram clients support rounded square MPEG4 videos of up to 1 minute long. Use this method to send video messages. On success, the sent Message is returned. +type SendVideoNoteParams struct { + // Unique identifier of the business connection on behalf of which the message will be sent + BusinessConnectionID string `json:"business_connection_id,omitempty"` + // Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username + ChatID ChatID `json:"chat_id"` + // Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only + MessageThreadID *int64 `json:"message_thread_id,omitempty"` + // Identifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat + DirectMessagesTopicID *int64 `json:"direct_messages_topic_id,omitempty"` + // Video note to send. Pass a file_id as String to send a video note that exists on the Telegram servers (recommended) or upload a new video using multipart/form-data. More information on Sending Files ». Sending video notes by a URL is currently unsupported + VideoNote *InputFile `json:"video_note"` + // Duration of sent video in seconds + Duration *int64 `json:"duration,omitempty"` + // Video width and height, i.e. diameter of the video message + Length *int64 `json:"length,omitempty"` + // Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://” if the thumbnail was uploaded using multipart/form-data under . More information on Sending Files » + Thumbnail *InputFile `json:"thumbnail,omitempty"` + // Sends the message silently. Users will receive a notification with no sound. + DisableNotification *bool `json:"disable_notification,omitempty"` + // Protects the contents of the sent message from forwarding and saving + ProtectContent *bool `json:"protect_content,omitempty"` + // Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance. + AllowPaidBroadcast *bool `json:"allow_paid_broadcast,omitempty"` + // Unique identifier of the message effect to be added to the message; for private chats only + MessageEffectID string `json:"message_effect_id,omitempty"` + // A JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined. + SuggestedPostParameters *SuggestedPostParameters `json:"suggested_post_parameters,omitempty"` + // Description of the message to reply to + ReplyParameters *ReplyParameters `json:"reply_parameters,omitempty"` + // Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user + ReplyMarkup any `json:"reply_markup,omitempty"` +} + +// HasFile reports whether a multipart upload is required. +func (p *SendVideoNoteParams) HasFile() bool { + if p.VideoNote != nil && p.VideoNote.IsLocalUpload() { + return true + } + if p.Thumbnail != nil && p.Thumbnail.IsLocalUpload() { + return true + } + return false +} + +// MultipartFields returns the non-file fields used in the multipart body. +func (p *SendVideoNoteParams) MultipartFields() map[string]string { + out := map[string]string{} + if p.BusinessConnectionID != "" { + out["business_connection_id"] = p.BusinessConnectionID + } + out["chat_id"] = p.ChatID.String() + if p.MessageThreadID != nil { + out["message_thread_id"] = strconv.FormatInt(*p.MessageThreadID, 10) + } + if p.DirectMessagesTopicID != nil { + out["direct_messages_topic_id"] = strconv.FormatInt(*p.DirectMessagesTopicID, 10) + } + if p.Duration != nil { + out["duration"] = strconv.FormatInt(*p.Duration, 10) + } + if p.Length != nil { + out["length"] = strconv.FormatInt(*p.Length, 10) + } + if p.DisableNotification != nil { + out["disable_notification"] = strconv.FormatBool(*p.DisableNotification) + } + if p.ProtectContent != nil { + out["protect_content"] = strconv.FormatBool(*p.ProtectContent) + } + if p.AllowPaidBroadcast != nil { + out["allow_paid_broadcast"] = strconv.FormatBool(*p.AllowPaidBroadcast) + } + if p.MessageEffectID != "" { + out["message_effect_id"] = p.MessageEffectID + } + if p.SuggestedPostParameters != nil { + if b, _ := json.Marshal(p.SuggestedPostParameters); len(b) > 0 { + out["suggested_post_parameters"] = string(b) + } + } + if p.ReplyParameters != nil { + if b, _ := json.Marshal(p.ReplyParameters); len(b) > 0 { + out["reply_parameters"] = string(b) + } + } + if p.ReplyMarkup != nil { + if b, _ := json.Marshal(p.ReplyMarkup); len(b) > 0 && string(b) != "null" { + out["reply_markup"] = string(b) + } + } + return out +} + +// MultipartFiles returns the file parts. +func (p *SendVideoNoteParams) MultipartFiles() []client.MultipartFile { + var files []client.MultipartFile + if p.VideoNote != nil && p.VideoNote.IsLocalUpload() { + name := p.VideoNote.Filename + if name == "" { + name = "video_note" + } + files = append(files, client.MultipartFile{FieldName: "video_note", Filename: name, Reader: p.VideoNote.Reader}) + } + if p.Thumbnail != nil && p.Thumbnail.IsLocalUpload() { + name := p.Thumbnail.Filename + if name == "" { + name = "thumbnail" + } + files = append(files, client.MultipartFile{FieldName: "thumbnail", Filename: name, Reader: p.Thumbnail.Reader}) + } + return files +} + +// SendVideoNote calls the sendVideoNote Telegram Bot API method. +// +// As of v.4.0, Telegram clients support rounded square MPEG4 videos of up to 1 minute long. Use this method to send video messages. On success, the sent Message is returned. +func SendVideoNote(ctx context.Context, b *client.Bot, p *SendVideoNoteParams) (*Message, error) { + return client.Call[*SendVideoNoteParams, *Message](ctx, b, "sendVideoNote", p) +} + +// SendPaidMediaParams is the parameter set for SendPaidMedia. +// +// Use this method to send paid media. On success, the sent Message is returned. +type SendPaidMediaParams struct { + // Unique identifier of the business connection on behalf of which the message will be sent + BusinessConnectionID string `json:"business_connection_id,omitempty"` + // Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username. If the chat is a channel, all Telegram Star proceeds from this media will be credited to the chat's balance. Otherwise, they will be credited to the bot's balance. + ChatID ChatID `json:"chat_id"` + // Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only + MessageThreadID *int64 `json:"message_thread_id,omitempty"` + // Identifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat + DirectMessagesTopicID *int64 `json:"direct_messages_topic_id,omitempty"` + // The number of Telegram Stars that must be paid to buy access to the media; 1-25000 + StarCount int64 `json:"star_count"` + // A JSON-serialized array describing the media to be sent; up to 10 items + Media []InputPaidMedia `json:"media"` + // Bot-defined paid media payload, 0-128 bytes. This will not be displayed to the user, use it for your internal processes. + Payload string `json:"payload,omitempty"` + // Media caption, 0-1024 characters after entities parsing + Caption string `json:"caption,omitempty"` + // Mode for parsing entities in the media caption. See formatting options for more details. + ParseMode string `json:"parse_mode,omitempty"` + // A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode + CaptionEntities []MessageEntity `json:"caption_entities,omitempty"` + // Pass True, if the caption must be shown above the message media + ShowCaptionAboveMedia *bool `json:"show_caption_above_media,omitempty"` + // Sends the message silently. Users will receive a notification with no sound. + DisableNotification *bool `json:"disable_notification,omitempty"` + // Protects the contents of the sent message from forwarding and saving + ProtectContent *bool `json:"protect_content,omitempty"` + // Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance. + AllowPaidBroadcast *bool `json:"allow_paid_broadcast,omitempty"` + // A JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined. + SuggestedPostParameters *SuggestedPostParameters `json:"suggested_post_parameters,omitempty"` + // Description of the message to reply to + ReplyParameters *ReplyParameters `json:"reply_parameters,omitempty"` + // Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user + ReplyMarkup any `json:"reply_markup,omitempty"` +} + +// HasFile reports whether a multipart upload is required. +func (p *SendPaidMediaParams) HasFile() bool { + return false +} + +// MultipartFields returns the non-file fields used in the multipart body. +func (p *SendPaidMediaParams) MultipartFields() map[string]string { + out := map[string]string{} + if p.BusinessConnectionID != "" { + out["business_connection_id"] = p.BusinessConnectionID + } + out["chat_id"] = p.ChatID.String() + if p.MessageThreadID != nil { + out["message_thread_id"] = strconv.FormatInt(*p.MessageThreadID, 10) + } + if p.DirectMessagesTopicID != nil { + out["direct_messages_topic_id"] = strconv.FormatInt(*p.DirectMessagesTopicID, 10) + } + out["star_count"] = strconv.FormatInt(p.StarCount, 10) + if b, _ := json.Marshal(p.Media); len(b) > 0 { + out["media"] = string(b) + } + if p.Payload != "" { + out["payload"] = p.Payload + } + if p.Caption != "" { + out["caption"] = p.Caption + } + if p.ParseMode != "" { + out["parse_mode"] = p.ParseMode + } + if p.CaptionEntities != nil { + if b, _ := json.Marshal(p.CaptionEntities); len(b) > 0 { + out["caption_entities"] = string(b) + } + } + if p.ShowCaptionAboveMedia != nil { + out["show_caption_above_media"] = strconv.FormatBool(*p.ShowCaptionAboveMedia) + } + if p.DisableNotification != nil { + out["disable_notification"] = strconv.FormatBool(*p.DisableNotification) + } + if p.ProtectContent != nil { + out["protect_content"] = strconv.FormatBool(*p.ProtectContent) + } + if p.AllowPaidBroadcast != nil { + out["allow_paid_broadcast"] = strconv.FormatBool(*p.AllowPaidBroadcast) + } + if p.SuggestedPostParameters != nil { + if b, _ := json.Marshal(p.SuggestedPostParameters); len(b) > 0 { + out["suggested_post_parameters"] = string(b) + } + } + if p.ReplyParameters != nil { + if b, _ := json.Marshal(p.ReplyParameters); len(b) > 0 { + out["reply_parameters"] = string(b) + } + } + if p.ReplyMarkup != nil { + if b, _ := json.Marshal(p.ReplyMarkup); len(b) > 0 && string(b) != "null" { + out["reply_markup"] = string(b) + } + } + return out +} + +// MultipartFiles returns the file parts. +func (p *SendPaidMediaParams) MultipartFiles() []client.MultipartFile { + var files []client.MultipartFile + return files +} + +// SendPaidMedia calls the sendPaidMedia Telegram Bot API method. +// +// Use this method to send paid media. On success, the sent Message is returned. +func SendPaidMedia(ctx context.Context, b *client.Bot, p *SendPaidMediaParams) (*Message, error) { + return client.Call[*SendPaidMediaParams, *Message](ctx, b, "sendPaidMedia", p) +} + +// SendMediaGroupParams is the parameter set for SendMediaGroup. +// +// Use this method to send a group of photos, live photos, videos, documents or audios as an album. Documents and audio files can be only grouped in an album with messages of the same type. On success, an array of Message objects that were sent is returned. +type SendMediaGroupParams struct { + // Unique identifier of the business connection on behalf of which the message will be sent + BusinessConnectionID string `json:"business_connection_id,omitempty"` + // Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username + ChatID ChatID `json:"chat_id"` + // Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only + MessageThreadID *int64 `json:"message_thread_id,omitempty"` + // Identifier of the direct messages topic to which the messages will be sent; required if the messages are sent to a direct messages chat + DirectMessagesTopicID *int64 `json:"direct_messages_topic_id,omitempty"` + // A JSON-serialized array describing messages to be sent, must include 2-10 items + Media []any `json:"media"` + // Sends messages silently. Users will receive a notification with no sound. + DisableNotification *bool `json:"disable_notification,omitempty"` + // Protects the contents of the sent messages from forwarding and saving + ProtectContent *bool `json:"protect_content,omitempty"` + // Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance. + AllowPaidBroadcast *bool `json:"allow_paid_broadcast,omitempty"` + // Unique identifier of the message effect to be added to the message; for private chats only + MessageEffectID string `json:"message_effect_id,omitempty"` + // Description of the message to reply to + ReplyParameters *ReplyParameters `json:"reply_parameters,omitempty"` +} + +// HasFile reports whether a multipart upload is required. +func (p *SendMediaGroupParams) HasFile() bool { + return false +} + +// MultipartFields returns the non-file fields used in the multipart body. +func (p *SendMediaGroupParams) MultipartFields() map[string]string { + out := map[string]string{} + if p.BusinessConnectionID != "" { + out["business_connection_id"] = p.BusinessConnectionID + } + out["chat_id"] = p.ChatID.String() + if p.MessageThreadID != nil { + out["message_thread_id"] = strconv.FormatInt(*p.MessageThreadID, 10) + } + if p.DirectMessagesTopicID != nil { + out["direct_messages_topic_id"] = strconv.FormatInt(*p.DirectMessagesTopicID, 10) + } + if b, _ := json.Marshal(p.Media); len(b) > 0 { + out["media"] = string(b) + } + if p.DisableNotification != nil { + out["disable_notification"] = strconv.FormatBool(*p.DisableNotification) + } + if p.ProtectContent != nil { + out["protect_content"] = strconv.FormatBool(*p.ProtectContent) + } + if p.AllowPaidBroadcast != nil { + out["allow_paid_broadcast"] = strconv.FormatBool(*p.AllowPaidBroadcast) + } + if p.MessageEffectID != "" { + out["message_effect_id"] = p.MessageEffectID + } + if p.ReplyParameters != nil { + if b, _ := json.Marshal(p.ReplyParameters); len(b) > 0 { + out["reply_parameters"] = string(b) + } + } + return out +} + +// MultipartFiles returns the file parts. +func (p *SendMediaGroupParams) MultipartFiles() []client.MultipartFile { + var files []client.MultipartFile + return files +} + +// SendMediaGroup calls the sendMediaGroup Telegram Bot API method. +// +// Use this method to send a group of photos, live photos, videos, documents or audios as an album. Documents and audio files can be only grouped in an album with messages of the same type. On success, an array of Message objects that were sent is returned. +func SendMediaGroup(ctx context.Context, b *client.Bot, p *SendMediaGroupParams) ([]Message, error) { + return client.Call[*SendMediaGroupParams, []Message](ctx, b, "sendMediaGroup", p) +} + +// SendLocationParams is the parameter set for SendLocation. +// +// Use this method to send point on the map. On success, the sent Message is returned. +type SendLocationParams struct { + // Unique identifier of the business connection on behalf of which the message will be sent + BusinessConnectionID string `json:"business_connection_id,omitempty"` + // Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username + ChatID ChatID `json:"chat_id"` + // Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only + MessageThreadID *int64 `json:"message_thread_id,omitempty"` + // Identifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat + DirectMessagesTopicID *int64 `json:"direct_messages_topic_id,omitempty"` + // Latitude of the location + Latitude float64 `json:"latitude"` + // Longitude of the location + Longitude float64 `json:"longitude"` + // The radius of uncertainty for the location, measured in meters; 0-1500 + HorizontalAccuracy *float64 `json:"horizontal_accuracy,omitempty"` + // Period in seconds during which the location will be updated (see Live Locations, should be between 60 and 86400, or 0x7FFFFFFF for live locations that can be edited indefinitely. + LivePeriod *int64 `json:"live_period,omitempty"` + // For live locations, a direction in which the user is moving, in degrees. Must be between 1 and 360 if specified. + Heading *int64 `json:"heading,omitempty"` + // For live locations, a maximum distance for proximity alerts about approaching another chat member, in meters. Must be between 1 and 100000 if specified. + ProximityAlertRadius *int64 `json:"proximity_alert_radius,omitempty"` + // Sends the message silently. Users will receive a notification with no sound. + DisableNotification *bool `json:"disable_notification,omitempty"` + // Protects the contents of the sent message from forwarding and saving + ProtectContent *bool `json:"protect_content,omitempty"` + // Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance. + AllowPaidBroadcast *bool `json:"allow_paid_broadcast,omitempty"` + // Unique identifier of the message effect to be added to the message; for private chats only + MessageEffectID string `json:"message_effect_id,omitempty"` + // A JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined. + SuggestedPostParameters *SuggestedPostParameters `json:"suggested_post_parameters,omitempty"` + // Description of the message to reply to + ReplyParameters *ReplyParameters `json:"reply_parameters,omitempty"` + // Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user + ReplyMarkup any `json:"reply_markup,omitempty"` +} + +// SendLocation calls the sendLocation Telegram Bot API method. +// +// Use this method to send point on the map. On success, the sent Message is returned. +func SendLocation(ctx context.Context, b *client.Bot, p *SendLocationParams) (*Message, error) { + return client.Call[*SendLocationParams, *Message](ctx, b, "sendLocation", p) +} + +// SendVenueParams is the parameter set for SendVenue. +// +// Use this method to send information about a venue. On success, the sent Message is returned. +type SendVenueParams struct { + // Unique identifier of the business connection on behalf of which the message will be sent + BusinessConnectionID string `json:"business_connection_id,omitempty"` + // Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username + ChatID ChatID `json:"chat_id"` + // Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only + MessageThreadID *int64 `json:"message_thread_id,omitempty"` + // Identifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat + DirectMessagesTopicID *int64 `json:"direct_messages_topic_id,omitempty"` + // Latitude of the venue + Latitude float64 `json:"latitude"` + // Longitude of the venue + Longitude float64 `json:"longitude"` + // Name of the venue + Title string `json:"title"` + // Address of the venue + Address string `json:"address"` + // Foursquare identifier of the venue + FoursquareID string `json:"foursquare_id,omitempty"` + // Foursquare type of the venue, if known. (For example, “arts_entertainment/default”, “arts_entertainment/aquarium” or “food/icecream”.) + FoursquareType string `json:"foursquare_type,omitempty"` + // Google Places identifier of the venue + GooglePlaceID string `json:"google_place_id,omitempty"` + // Google Places type of the venue. (See supported types.) + GooglePlaceType string `json:"google_place_type,omitempty"` + // Sends the message silently. Users will receive a notification with no sound. + DisableNotification *bool `json:"disable_notification,omitempty"` + // Protects the contents of the sent message from forwarding and saving + ProtectContent *bool `json:"protect_content,omitempty"` + // Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance. + AllowPaidBroadcast *bool `json:"allow_paid_broadcast,omitempty"` + // Unique identifier of the message effect to be added to the message; for private chats only + MessageEffectID string `json:"message_effect_id,omitempty"` + // A JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined. + SuggestedPostParameters *SuggestedPostParameters `json:"suggested_post_parameters,omitempty"` + // Description of the message to reply to + ReplyParameters *ReplyParameters `json:"reply_parameters,omitempty"` + // Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user + ReplyMarkup any `json:"reply_markup,omitempty"` +} + +// SendVenue calls the sendVenue Telegram Bot API method. +// +// Use this method to send information about a venue. On success, the sent Message is returned. +func SendVenue(ctx context.Context, b *client.Bot, p *SendVenueParams) (*Message, error) { + return client.Call[*SendVenueParams, *Message](ctx, b, "sendVenue", p) +} + +// SendContactParams is the parameter set for SendContact. +// +// Use this method to send phone contacts. On success, the sent Message is returned. +type SendContactParams struct { + // Unique identifier of the business connection on behalf of which the message will be sent + BusinessConnectionID string `json:"business_connection_id,omitempty"` + // Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username + ChatID ChatID `json:"chat_id"` + // Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only + MessageThreadID *int64 `json:"message_thread_id,omitempty"` + // Identifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat + DirectMessagesTopicID *int64 `json:"direct_messages_topic_id,omitempty"` + // Contact's phone number + PhoneNumber string `json:"phone_number"` + // Contact's first name + FirstName string `json:"first_name"` + // Contact's last name + LastName string `json:"last_name,omitempty"` + // Additional data about the contact in the form of a vCard, 0-2048 bytes + Vcard string `json:"vcard,omitempty"` + // Sends the message silently. Users will receive a notification with no sound. + DisableNotification *bool `json:"disable_notification,omitempty"` + // Protects the contents of the sent message from forwarding and saving + ProtectContent *bool `json:"protect_content,omitempty"` + // Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance. + AllowPaidBroadcast *bool `json:"allow_paid_broadcast,omitempty"` + // Unique identifier of the message effect to be added to the message; for private chats only + MessageEffectID string `json:"message_effect_id,omitempty"` + // A JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined. + SuggestedPostParameters *SuggestedPostParameters `json:"suggested_post_parameters,omitempty"` + // Description of the message to reply to + ReplyParameters *ReplyParameters `json:"reply_parameters,omitempty"` + // Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user + ReplyMarkup any `json:"reply_markup,omitempty"` +} + +// SendContact calls the sendContact Telegram Bot API method. +// +// Use this method to send phone contacts. On success, the sent Message is returned. +func SendContact(ctx context.Context, b *client.Bot, p *SendContactParams) (*Message, error) { + return client.Call[*SendContactParams, *Message](ctx, b, "sendContact", p) +} + +// SendPollParams is the parameter set for SendPoll. +// +// Use this method to send a native poll. On success, the sent Message is returned. +type SendPollParams struct { + // Unique identifier of the business connection on behalf of which the message will be sent + BusinessConnectionID string `json:"business_connection_id,omitempty"` + // Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username. Polls can't be sent to channel direct messages chats. + ChatID ChatID `json:"chat_id"` + // Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only + MessageThreadID *int64 `json:"message_thread_id,omitempty"` + // Poll question, 1-300 characters + Question string `json:"question"` + // Mode for parsing entities in the question. See formatting options for more details. Currently, only custom emoji entities are allowed + QuestionParseMode string `json:"question_parse_mode,omitempty"` + // A JSON-serialized list of special entities that appear in the poll question. It can be specified instead of question_parse_mode + QuestionEntities []MessageEntity `json:"question_entities,omitempty"` + // A JSON-serialized list of 1-12 answer options + Options []InputPollOption `json:"options"` + // True, if the poll needs to be anonymous, defaults to True + IsAnonymous *bool `json:"is_anonymous,omitempty"` + // Poll type, “quiz” or “regular”, defaults to “regular” + Type string `json:"type,omitempty"` + // Pass True, if the poll allows multiple answers, defaults to False + AllowsMultipleAnswers *bool `json:"allows_multiple_answers,omitempty"` + // Pass True, if the poll allows to change chosen answer options, defaults to False for quizzes and to True for regular polls + AllowsRevoting *bool `json:"allows_revoting,omitempty"` + // Pass True, if the poll options must be shown in random order + ShuffleOptions *bool `json:"shuffle_options,omitempty"` + // Pass True, if answer options can be added to the poll after creation; not supported for anonymous polls and quizzes + AllowAddingOptions *bool `json:"allow_adding_options,omitempty"` + // Pass True, if poll results must be shown only after the poll closes + HideResultsUntilCloses *bool `json:"hide_results_until_closes,omitempty"` + // Pass True, if voting is limited to users who have been members of the chat where the poll is being sent for more than 24 hours; for channel chats only + MembersOnly *bool `json:"members_only,omitempty"` + // A JSON-serialized list of 0-12 two-letter ISO 3166-1 alpha-2 country codes indicating the countries from which users can vote in the poll; for channel chats only. If omitted or empty, then users from any country can participate in the poll. + CountryCodes []string `json:"country_codes,omitempty"` + // A JSON-serialized list of monotonically increasing 0-based identifiers of the correct answer options, required for polls in quiz mode + CorrectOptionIds []int64 `json:"correct_option_ids,omitempty"` + // Text that is shown when a user chooses an incorrect answer or taps on the lamp icon in a quiz-style poll, 0-200 characters with at most 2 line feeds after entities parsing + Explanation string `json:"explanation,omitempty"` + // Mode for parsing entities in the explanation. See formatting options for more details. + ExplanationParseMode string `json:"explanation_parse_mode,omitempty"` + // A JSON-serialized list of special entities that appear in the poll explanation. It can be specified instead of explanation_parse_mode + ExplanationEntities []MessageEntity `json:"explanation_entities,omitempty"` + // Media added to the quiz explanation + ExplanationMedia *InputPollMedia `json:"explanation_media,omitempty"` + // Amount of time in seconds the poll will be active after creation, 5-2628000. Can't be used together with close_date. + OpenPeriod *int64 `json:"open_period,omitempty"` + // Point in time (Unix timestamp) when the poll will be automatically closed. Must be at least 5 and no more than 2628000 seconds in the future. Can't be used together with open_period. + CloseDate *int64 `json:"close_date,omitempty"` + // Pass True if the poll needs to be immediately closed. This can be useful for poll preview. + IsClosed *bool `json:"is_closed,omitempty"` + // Description of the poll to be sent, 0-1024 characters after entities parsing + Description string `json:"description,omitempty"` + // Mode for parsing entities in the poll description. See formatting options for more details. + DescriptionParseMode string `json:"description_parse_mode,omitempty"` + // A JSON-serialized list of special entities that appear in the poll description, which can be specified instead of description_parse_mode + DescriptionEntities []MessageEntity `json:"description_entities,omitempty"` + // Media added to the poll description + Media *InputPollMedia `json:"media,omitempty"` + // Sends the message silently. Users will receive a notification with no sound. + DisableNotification *bool `json:"disable_notification,omitempty"` + // Protects the contents of the sent message from forwarding and saving + ProtectContent *bool `json:"protect_content,omitempty"` + // Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance. + AllowPaidBroadcast *bool `json:"allow_paid_broadcast,omitempty"` + // Unique identifier of the message effect to be added to the message; for private chats only + MessageEffectID string `json:"message_effect_id,omitempty"` + // Description of the message to reply to + ReplyParameters *ReplyParameters `json:"reply_parameters,omitempty"` + // Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user + ReplyMarkup any `json:"reply_markup,omitempty"` +} + +// SendPoll calls the sendPoll Telegram Bot API method. +// +// Use this method to send a native poll. On success, the sent Message is returned. +func SendPoll(ctx context.Context, b *client.Bot, p *SendPollParams) (*Message, error) { + return client.Call[*SendPollParams, *Message](ctx, b, "sendPoll", p) +} + +// SendChecklistParams is the parameter set for SendChecklist. +// +// Use this method to send a checklist on behalf of a connected business account. On success, the sent Message is returned. +type SendChecklistParams struct { + // Unique identifier of the business connection on behalf of which the message will be sent + BusinessConnectionID string `json:"business_connection_id"` + // Unique identifier for the target chat or username of the target bot in the format @username + ChatID ChatID `json:"chat_id"` + // A JSON-serialized object for the checklist to send + Checklist InputChecklist `json:"checklist"` + // Sends the message silently. Users will receive a notification with no sound. + DisableNotification *bool `json:"disable_notification,omitempty"` + // Protects the contents of the sent message from forwarding and saving + ProtectContent *bool `json:"protect_content,omitempty"` + // Unique identifier of the message effect to be added to the message + MessageEffectID string `json:"message_effect_id,omitempty"` + // A JSON-serialized object for description of the message to reply to + ReplyParameters *ReplyParameters `json:"reply_parameters,omitempty"` + // A JSON-serialized object for an inline keyboard + ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"` +} + +// SendChecklist calls the sendChecklist Telegram Bot API method. +// +// Use this method to send a checklist on behalf of a connected business account. On success, the sent Message is returned. +func SendChecklist(ctx context.Context, b *client.Bot, p *SendChecklistParams) (*Message, error) { + return client.Call[*SendChecklistParams, *Message](ctx, b, "sendChecklist", p) +} + +// SendDiceParams is the parameter set for SendDice. +// +// Use this method to send an animated emoji that will display a random value. On success, the sent Message is returned. +type SendDiceParams struct { + // Unique identifier of the business connection on behalf of which the message will be sent + BusinessConnectionID string `json:"business_connection_id,omitempty"` + // Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username + ChatID ChatID `json:"chat_id"` + // Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only + MessageThreadID *int64 `json:"message_thread_id,omitempty"` + // Identifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat + DirectMessagesTopicID *int64 `json:"direct_messages_topic_id,omitempty"` + // Emoji on which the dice throw animation is based. Currently, must be one of “”, “”, “”, “”, “”, or “”. Dice can have values 1-6 for “”, “” and “”, values 1-5 for “” and “”, and values 1-64 for “”. Defaults to “” + Emoji string `json:"emoji,omitempty"` + // Sends the message silently. Users will receive a notification with no sound. + DisableNotification *bool `json:"disable_notification,omitempty"` + // Protects the contents of the sent message from forwarding + ProtectContent *bool `json:"protect_content,omitempty"` + // Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance. + AllowPaidBroadcast *bool `json:"allow_paid_broadcast,omitempty"` + // Unique identifier of the message effect to be added to the message; for private chats only + MessageEffectID string `json:"message_effect_id,omitempty"` + // A JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined. + SuggestedPostParameters *SuggestedPostParameters `json:"suggested_post_parameters,omitempty"` + // Description of the message to reply to + ReplyParameters *ReplyParameters `json:"reply_parameters,omitempty"` + // Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user + ReplyMarkup any `json:"reply_markup,omitempty"` +} + +// SendDice calls the sendDice Telegram Bot API method. +// +// Use this method to send an animated emoji that will display a random value. On success, the sent Message is returned. +func SendDice(ctx context.Context, b *client.Bot, p *SendDiceParams) (*Message, error) { + return client.Call[*SendDiceParams, *Message](ctx, b, "sendDice", p) +} + +// SendMessageDraftParams is the parameter set for SendMessageDraft. +// +// Use this method to stream a partial message to a user while the message is being generated. Note that the streamed draft is ephemeral and acts as a temporary 30-second preview - once the output is finalized, you must call sendMessage with the complete message to persist it in the user's chat. Returns True on success. +type SendMessageDraftParams struct { + // Unique identifier for the target private chat + ChatID int64 `json:"chat_id"` + // Unique identifier for the target message thread + MessageThreadID *int64 `json:"message_thread_id,omitempty"` + // Unique identifier of the message draft; must be non-zero. Changes of drafts with the same identifier are animated. + DraftID int64 `json:"draft_id"` + // Text of the message to be sent, 0-4096 characters after entities parsing. Pass an empty text to show a “Thinking…” placeholder. + Text string `json:"text,omitempty"` + // Mode for parsing entities in the message text. See formatting options for more details. + ParseMode string `json:"parse_mode,omitempty"` + // A JSON-serialized list of special entities that appear in message text, which can be specified instead of parse_mode + Entities []MessageEntity `json:"entities,omitempty"` +} + +// SendMessageDraft calls the sendMessageDraft Telegram Bot API method. +// +// Use this method to stream a partial message to a user while the message is being generated. Note that the streamed draft is ephemeral and acts as a temporary 30-second preview - once the output is finalized, you must call sendMessage with the complete message to persist it in the user's chat. Returns True on success. +func SendMessageDraft(ctx context.Context, b *client.Bot, p *SendMessageDraftParams) (bool, error) { + return client.Call[*SendMessageDraftParams, bool](ctx, b, "sendMessageDraft", p) +} + +// SendChatActionParams is the parameter set for SendChatAction. +// +// Use this method when you need to tell the user that something is happening on the bot's side. The status is set for 5 seconds or less (when a message arrives from your bot, Telegram clients clear its typing status). Returns True on success. +// Example: The ImageBot needs some time to process a request and upload the image. Instead of sending a text message along the lines of “Retrieving image, please wait…”, the bot may use sendChatAction with action = upload_photo. The user will see a “sending photo” status for the bot. +// We only recommend using this method when a response from the bot will take a noticeable amount of time to arrive. +type SendChatActionParams struct { + // Unique identifier of the business connection on behalf of which the action will be sent + BusinessConnectionID string `json:"business_connection_id,omitempty"` + // Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username. Channel chats and channel direct messages chats aren't supported. + ChatID ChatID `json:"chat_id"` + // Unique identifier for the target message thread or topic of a forum; for supergroups and private chats of bots with forum topic mode enabled only + MessageThreadID *int64 `json:"message_thread_id,omitempty"` + // Type of action to broadcast. Choose one, depending on what the user is about to receive: typing for text messages, upload_photo for photos, record_video or upload_video for videos, record_voice or upload_voice for voice notes, upload_document for general files, choose_sticker for stickers, find_location for location data, record_video_note or upload_video_note for video notes. + Action string `json:"action"` +} + +// SendChatAction calls the sendChatAction Telegram Bot API method. +// +// Use this method when you need to tell the user that something is happening on the bot's side. The status is set for 5 seconds or less (when a message arrives from your bot, Telegram clients clear its typing status). Returns True on success. +// Example: The ImageBot needs some time to process a request and upload the image. Instead of sending a text message along the lines of “Retrieving image, please wait…”, the bot may use sendChatAction with action = upload_photo. The user will see a “sending photo” status for the bot. +// We only recommend using this method when a response from the bot will take a noticeable amount of time to arrive. +func SendChatAction(ctx context.Context, b *client.Bot, p *SendChatActionParams) (bool, error) { + return client.Call[*SendChatActionParams, bool](ctx, b, "sendChatAction", p) +} + +// SetMessageReactionParams is the parameter set for SetMessageReaction. +// +// Use this method to change the chosen reactions on a message. Service messages of some types can't be reacted to. Automatically forwarded messages from a channel to its discussion group have the same available reactions as messages in the channel. Bots can't use paid reactions. Returns True on success. +type SetMessageReactionParams struct { + // Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username + ChatID ChatID `json:"chat_id"` + // Identifier of the target message. If the message belongs to a media group, the reaction is set to the first non-deleted message in the group instead. + MessageID int64 `json:"message_id"` + // A JSON-serialized list of reaction types to set on the message. Currently, as non-premium users, bots can set up to one reaction per message. A custom emoji reaction can be used if it is either already present on the message or explicitly allowed by chat administrators. Paid reactions can't be used by bots. + Reaction []ReactionType `json:"reaction,omitempty"` + // Pass True to set the reaction with a big animation + IsBig *bool `json:"is_big,omitempty"` +} + +// SetMessageReaction calls the setMessageReaction Telegram Bot API method. +// +// Use this method to change the chosen reactions on a message. Service messages of some types can't be reacted to. Automatically forwarded messages from a channel to its discussion group have the same available reactions as messages in the channel. Bots can't use paid reactions. Returns True on success. +func SetMessageReaction(ctx context.Context, b *client.Bot, p *SetMessageReactionParams) (bool, error) { + return client.Call[*SetMessageReactionParams, bool](ctx, b, "setMessageReaction", p) +} + +// GetUserProfilePhotosParams is the parameter set for GetUserProfilePhotos. +// +// Use this method to get a list of profile pictures for a user. Returns a UserProfilePhotos object. +type GetUserProfilePhotosParams struct { + // Unique identifier of the target user + UserID int64 `json:"user_id"` + // Sequential number of the first photo to be returned. By default, all photos are returned. + Offset *int64 `json:"offset,omitempty"` + // Limits the number of photos to be retrieved. Values between 1-100 are accepted. Defaults to 100. + Limit *int64 `json:"limit,omitempty"` +} + +// GetUserProfilePhotos calls the getUserProfilePhotos Telegram Bot API method. +// +// Use this method to get a list of profile pictures for a user. Returns a UserProfilePhotos object. +func GetUserProfilePhotos(ctx context.Context, b *client.Bot, p *GetUserProfilePhotosParams) (*UserProfilePhotos, error) { + return client.Call[*GetUserProfilePhotosParams, *UserProfilePhotos](ctx, b, "getUserProfilePhotos", p) +} + +// GetUserProfileAudiosParams is the parameter set for GetUserProfileAudios. +// +// Use this method to get a list of profile audios for a user. Returns a UserProfileAudios object. +type GetUserProfileAudiosParams struct { + // Unique identifier of the target user + UserID int64 `json:"user_id"` + // Sequential number of the first audio to be returned. By default, all audios are returned. + Offset *int64 `json:"offset,omitempty"` + // Limits the number of audios to be retrieved. Values between 1-100 are accepted. Defaults to 100. + Limit *int64 `json:"limit,omitempty"` +} + +// GetUserProfileAudios calls the getUserProfileAudios Telegram Bot API method. +// +// Use this method to get a list of profile audios for a user. Returns a UserProfileAudios object. +func GetUserProfileAudios(ctx context.Context, b *client.Bot, p *GetUserProfileAudiosParams) (*UserProfileAudios, error) { + return client.Call[*GetUserProfileAudiosParams, *UserProfileAudios](ctx, b, "getUserProfileAudios", p) +} + +// SetUserEmojiStatusParams is the parameter set for SetUserEmojiStatus. +// +// Changes the emoji status for a given user that previously allowed the bot to manage their emoji status via the Mini App method requestEmojiStatusAccess. Returns True on success. +type SetUserEmojiStatusParams struct { + // Unique identifier of the target user + UserID int64 `json:"user_id"` + // Custom emoji identifier of the emoji status to set. Pass an empty string to remove the status. + EmojiStatusCustomEmojiID string `json:"emoji_status_custom_emoji_id,omitempty"` + // Expiration date of the emoji status, if any + EmojiStatusExpirationDate *int64 `json:"emoji_status_expiration_date,omitempty"` +} + +// SetUserEmojiStatus calls the setUserEmojiStatus Telegram Bot API method. +// +// Changes the emoji status for a given user that previously allowed the bot to manage their emoji status via the Mini App method requestEmojiStatusAccess. Returns True on success. +func SetUserEmojiStatus(ctx context.Context, b *client.Bot, p *SetUserEmojiStatusParams) (bool, error) { + return client.Call[*SetUserEmojiStatusParams, bool](ctx, b, "setUserEmojiStatus", p) +} + +// GetFileParams is the parameter set for GetFile. +// +// Use this method to get basic information about a file and prepare it for downloading. For the moment, bots can download files of up to 20MB in size. On success, a File object is returned. The file can then be downloaded via the link https://api.telegram.org/file/bot/, where is taken from the response. It is guaranteed that the link will be valid for at least 1 hour. When the link expires, a new one can be requested by calling getFile again. +// Note: This function may not preserve the original file name and MIME type. You should save the file's MIME type and name (if available) when the File object is received. +type GetFileParams struct { + // File identifier to get information about + FileID string `json:"file_id"` +} + +// GetFile calls the getFile Telegram Bot API method. +// +// Use this method to get basic information about a file and prepare it for downloading. For the moment, bots can download files of up to 20MB in size. On success, a File object is returned. The file can then be downloaded via the link https://api.telegram.org/file/bot/, where is taken from the response. It is guaranteed that the link will be valid for at least 1 hour. When the link expires, a new one can be requested by calling getFile again. +// Note: This function may not preserve the original file name and MIME type. You should save the file's MIME type and name (if available) when the File object is received. +func GetFile(ctx context.Context, b *client.Bot, p *GetFileParams) (*File, error) { + return client.Call[*GetFileParams, *File](ctx, b, "getFile", p) +} + +// BanChatMemberParams is the parameter set for BanChatMember. +// +// Use this method to ban a user in a group, a supergroup or a channel. In the case of supergroups and channels, the user will not be able to return to the chat on their own using invite links, etc., unless unbanned first. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns True on success. +type BanChatMemberParams struct { + // Unique identifier for the target group or username of the target supergroup or channel in the format @username + ChatID ChatID `json:"chat_id"` + // Unique identifier of the target user + UserID int64 `json:"user_id"` + // Date when the user will be unbanned; Unix time. If user is banned for more than 366 days or less than 30 seconds from the current time they are considered to be banned forever. Applied for supergroups and channels only. + UntilDate *int64 `json:"until_date,omitempty"` + // Pass True to delete all messages from the chat for the user that is being removed. If False, the user will be able to see messages in the group that were sent before the user was removed. Always True for supergroups and channels. + RevokeMessages *bool `json:"revoke_messages,omitempty"` +} + +// BanChatMember calls the banChatMember Telegram Bot API method. +// +// Use this method to ban a user in a group, a supergroup or a channel. In the case of supergroups and channels, the user will not be able to return to the chat on their own using invite links, etc., unless unbanned first. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns True on success. +func BanChatMember(ctx context.Context, b *client.Bot, p *BanChatMemberParams) (bool, error) { + return client.Call[*BanChatMemberParams, bool](ctx, b, "banChatMember", p) +} + +// UnbanChatMemberParams is the parameter set for UnbanChatMember. +// +// Use this method to unban a previously banned user in a supergroup or channel. The user will not return to the group or channel automatically, but will be able to join via link, etc. The bot must be an administrator for this to work. By default, this method guarantees that after the call the user is not a member of the chat, but will be able to join it. So if the user is a member of the chat they will also be removed from the chat. If you don't want this, use the parameter only_if_banned. Returns True on success. +type UnbanChatMemberParams struct { + // Unique identifier for the target group or username of the target supergroup or channel in the format @username + ChatID ChatID `json:"chat_id"` + // Unique identifier of the target user + UserID int64 `json:"user_id"` + // Do nothing if the user is not banned + OnlyIfBanned *bool `json:"only_if_banned,omitempty"` +} + +// UnbanChatMember calls the unbanChatMember Telegram Bot API method. +// +// Use this method to unban a previously banned user in a supergroup or channel. The user will not return to the group or channel automatically, but will be able to join via link, etc. The bot must be an administrator for this to work. By default, this method guarantees that after the call the user is not a member of the chat, but will be able to join it. So if the user is a member of the chat they will also be removed from the chat. If you don't want this, use the parameter only_if_banned. Returns True on success. +func UnbanChatMember(ctx context.Context, b *client.Bot, p *UnbanChatMemberParams) (bool, error) { + return client.Call[*UnbanChatMemberParams, bool](ctx, b, "unbanChatMember", p) +} + +// RestrictChatMemberParams is the parameter set for RestrictChatMember. +// +// Use this method to restrict a user in a supergroup. The bot must be an administrator in the supergroup for this to work and must have the appropriate administrator rights. Pass True for all permissions to lift restrictions from a user. Returns True on success. +type RestrictChatMemberParams struct { + // Unique identifier for the target chat or username of the target supergroup in the format @username + ChatID ChatID `json:"chat_id"` + // Unique identifier of the target user + UserID int64 `json:"user_id"` + // A JSON-serialized object for new user permissions + Permissions ChatPermissions `json:"permissions"` + // Pass True if chat permissions are set independently. Otherwise, the can_send_other_messages and can_add_web_page_previews permissions will imply the can_send_messages, can_send_audios, can_send_documents, can_send_photos, can_send_videos, can_send_video_notes, and can_send_voice_notes permissions; the can_send_polls permission will imply the can_send_messages permission. + UseIndependentChatPermissions *bool `json:"use_independent_chat_permissions,omitempty"` + // Date when restrictions will be lifted for the user; Unix time. If user is restricted for more than 366 days or less than 30 seconds from the current time, they are considered to be restricted forever + UntilDate *int64 `json:"until_date,omitempty"` +} + +// RestrictChatMember calls the restrictChatMember Telegram Bot API method. +// +// Use this method to restrict a user in a supergroup. The bot must be an administrator in the supergroup for this to work and must have the appropriate administrator rights. Pass True for all permissions to lift restrictions from a user. Returns True on success. +func RestrictChatMember(ctx context.Context, b *client.Bot, p *RestrictChatMemberParams) (bool, error) { + return client.Call[*RestrictChatMemberParams, bool](ctx, b, "restrictChatMember", p) +} + +// PromoteChatMemberParams is the parameter set for PromoteChatMember. +// +// Use this method to promote or demote a user in a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Pass False for all boolean parameters to demote a user. Returns True on success. +type PromoteChatMemberParams struct { + // Unique identifier for the target chat or username of the target channel in the format @username + ChatID ChatID `json:"chat_id"` + // Unique identifier of the target user + UserID int64 `json:"user_id"` + // Pass True if the administrator's presence in the chat is hidden + IsAnonymous *bool `json:"is_anonymous,omitempty"` + // Pass True if the administrator can access the chat event log, get boost list, see hidden supergroup and channel members, report spam messages, ignore slow mode, and send messages to the chat without paying Telegram Stars. Implied by any other administrator privilege. + CanManageChat *bool `json:"can_manage_chat,omitempty"` + // Pass True if the administrator can delete messages of other users + CanDeleteMessages *bool `json:"can_delete_messages,omitempty"` + // Pass True if the administrator can manage video chats + CanManageVideoChats *bool `json:"can_manage_video_chats,omitempty"` + // Pass True if the administrator can restrict, ban or unban chat members, or access supergroup statistics. For backward compatibility, defaults to True for promotions of channel administrators + CanRestrictMembers *bool `json:"can_restrict_members,omitempty"` + // Pass True if the administrator can add new administrators with a subset of their own privileges or demote administrators that they have promoted, directly or indirectly (promoted by administrators that were appointed by him) + CanPromoteMembers *bool `json:"can_promote_members,omitempty"` + // Pass True if the administrator can change chat title, photo and other settings + CanChangeInfo *bool `json:"can_change_info,omitempty"` + // Pass True if the administrator can invite new users to the chat + CanInviteUsers *bool `json:"can_invite_users,omitempty"` + // Pass True if the administrator can post stories to the chat + CanPostStories *bool `json:"can_post_stories,omitempty"` + // Pass True if the administrator can edit stories posted by other users, post stories to the chat page, pin chat stories, and access the chat's story archive + CanEditStories *bool `json:"can_edit_stories,omitempty"` + // Pass True if the administrator can delete stories posted by other users + CanDeleteStories *bool `json:"can_delete_stories,omitempty"` + // Pass True if the administrator can post messages in the channel, approve suggested posts, or access channel statistics; for channels only + CanPostMessages *bool `json:"can_post_messages,omitempty"` + // Pass True if the administrator can edit messages of other users and can pin messages; for channels only + CanEditMessages *bool `json:"can_edit_messages,omitempty"` + // Pass True if the administrator can pin messages; for supergroups only + CanPinMessages *bool `json:"can_pin_messages,omitempty"` + // Pass True if the user is allowed to create, rename, close, and reopen forum topics; for supergroups only + CanManageTopics *bool `json:"can_manage_topics,omitempty"` + // Pass True if the administrator can manage direct messages within the channel and decline suggested posts; for channels only + CanManageDirectMessages *bool `json:"can_manage_direct_messages,omitempty"` + // Pass True if the administrator can edit the tags of regular members; for groups and supergroups only + CanManageTags *bool `json:"can_manage_tags,omitempty"` +} + +// PromoteChatMember calls the promoteChatMember Telegram Bot API method. +// +// Use this method to promote or demote a user in a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Pass False for all boolean parameters to demote a user. Returns True on success. +func PromoteChatMember(ctx context.Context, b *client.Bot, p *PromoteChatMemberParams) (bool, error) { + return client.Call[*PromoteChatMemberParams, bool](ctx, b, "promoteChatMember", p) +} + +// SetChatAdministratorCustomTitleParams is the parameter set for SetChatAdministratorCustomTitle. +// +// Use this method to set a custom title for an administrator in a supergroup promoted by the bot. Returns True on success. +type SetChatAdministratorCustomTitleParams struct { + // Unique identifier for the target chat or username of the target supergroup in the format @username + ChatID ChatID `json:"chat_id"` + // Unique identifier of the target user + UserID int64 `json:"user_id"` + // New custom title for the administrator; 0-16 characters, emoji are not allowed + CustomTitle string `json:"custom_title"` +} + +// SetChatAdministratorCustomTitle calls the setChatAdministratorCustomTitle Telegram Bot API method. +// +// Use this method to set a custom title for an administrator in a supergroup promoted by the bot. Returns True on success. +func SetChatAdministratorCustomTitle(ctx context.Context, b *client.Bot, p *SetChatAdministratorCustomTitleParams) (bool, error) { + return client.Call[*SetChatAdministratorCustomTitleParams, bool](ctx, b, "setChatAdministratorCustomTitle", p) +} + +// SetChatMemberTagParams is the parameter set for SetChatMemberTag. +// +// Use this method to set a tag for a regular member in a group or a supergroup. The bot must be an administrator in the chat for this to work and must have the can_manage_tags administrator right. Returns True on success. +type SetChatMemberTagParams struct { + // Unique identifier for the target chat or username of the target supergroup in the format @username + ChatID ChatID `json:"chat_id"` + // Unique identifier of the target user + UserID int64 `json:"user_id"` + // New tag for the member; 0-16 characters, emoji are not allowed + Tag string `json:"tag,omitempty"` +} + +// SetChatMemberTag calls the setChatMemberTag Telegram Bot API method. +// +// Use this method to set a tag for a regular member in a group or a supergroup. The bot must be an administrator in the chat for this to work and must have the can_manage_tags administrator right. Returns True on success. +func SetChatMemberTag(ctx context.Context, b *client.Bot, p *SetChatMemberTagParams) (bool, error) { + return client.Call[*SetChatMemberTagParams, bool](ctx, b, "setChatMemberTag", p) +} + +// BanChatSenderChatParams is the parameter set for BanChatSenderChat. +// +// Use this method to ban a channel chat in a supergroup or a channel. Until the chat is unbanned, the owner of the banned chat won't be able to send messages on behalf of any of their channels. The bot must be an administrator in the supergroup or channel for this to work and must have the appropriate administrator rights. Returns True on success. +type BanChatSenderChatParams struct { + // Unique identifier for the target chat or username of the target channel in the format @username + ChatID ChatID `json:"chat_id"` + // Unique identifier of the target sender chat + SenderChatID int64 `json:"sender_chat_id"` +} + +// BanChatSenderChat calls the banChatSenderChat Telegram Bot API method. +// +// Use this method to ban a channel chat in a supergroup or a channel. Until the chat is unbanned, the owner of the banned chat won't be able to send messages on behalf of any of their channels. The bot must be an administrator in the supergroup or channel for this to work and must have the appropriate administrator rights. Returns True on success. +func BanChatSenderChat(ctx context.Context, b *client.Bot, p *BanChatSenderChatParams) (bool, error) { + return client.Call[*BanChatSenderChatParams, bool](ctx, b, "banChatSenderChat", p) +} + +// UnbanChatSenderChatParams is the parameter set for UnbanChatSenderChat. +// +// Use this method to unban a previously banned channel chat in a supergroup or channel. The bot must be an administrator for this to work and must have the appropriate administrator rights. Returns True on success. +type UnbanChatSenderChatParams struct { + // Unique identifier for the target chat or username of the target channel in the format @username + ChatID ChatID `json:"chat_id"` + // Unique identifier of the target sender chat + SenderChatID int64 `json:"sender_chat_id"` +} + +// UnbanChatSenderChat calls the unbanChatSenderChat Telegram Bot API method. +// +// Use this method to unban a previously banned channel chat in a supergroup or channel. The bot must be an administrator for this to work and must have the appropriate administrator rights. Returns True on success. +func UnbanChatSenderChat(ctx context.Context, b *client.Bot, p *UnbanChatSenderChatParams) (bool, error) { + return client.Call[*UnbanChatSenderChatParams, bool](ctx, b, "unbanChatSenderChat", p) +} + +// SetChatPermissionsParams is the parameter set for SetChatPermissions. +// +// Use this method to set default chat permissions for all members. The bot must be an administrator in the group or a supergroup for this to work and must have the can_restrict_members administrator rights. Returns True on success. +type SetChatPermissionsParams struct { + // Unique identifier for the target chat or username of the target supergroup in the format @username + ChatID ChatID `json:"chat_id"` + // A JSON-serialized object for new default chat permissions + Permissions ChatPermissions `json:"permissions"` + // Pass True if chat permissions are set independently. Otherwise, the can_send_other_messages and can_add_web_page_previews permissions will imply the can_send_messages, can_send_audios, can_send_documents, can_send_photos, can_send_videos, can_send_video_notes, and can_send_voice_notes permissions; the can_send_polls permission will imply the can_send_messages permission. + UseIndependentChatPermissions *bool `json:"use_independent_chat_permissions,omitempty"` +} + +// SetChatPermissions calls the setChatPermissions Telegram Bot API method. +// +// Use this method to set default chat permissions for all members. The bot must be an administrator in the group or a supergroup for this to work and must have the can_restrict_members administrator rights. Returns True on success. +func SetChatPermissions(ctx context.Context, b *client.Bot, p *SetChatPermissionsParams) (bool, error) { + return client.Call[*SetChatPermissionsParams, bool](ctx, b, "setChatPermissions", p) +} + +// ExportChatInviteLinkParams is the parameter set for ExportChatInviteLink. +// +// Use this method to generate a new primary invite link for a chat; any previously generated primary link is revoked. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns the new invite link as String on success. +// Note: Each administrator in a chat generates their own invite links. Bots can't use invite links generated by other administrators. If you want your bot to work with invite links, it will need to generate its own link using exportChatInviteLink or by calling the getChat method. If your bot needs to generate a new primary invite link replacing its previous one, use exportChatInviteLink again. +type ExportChatInviteLinkParams struct { + // Unique identifier for the target chat or username of the target channel in the format @username + ChatID ChatID `json:"chat_id"` +} + +// ExportChatInviteLink calls the exportChatInviteLink Telegram Bot API method. +// +// Use this method to generate a new primary invite link for a chat; any previously generated primary link is revoked. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns the new invite link as String on success. +// Note: Each administrator in a chat generates their own invite links. Bots can't use invite links generated by other administrators. If you want your bot to work with invite links, it will need to generate its own link using exportChatInviteLink or by calling the getChat method. If your bot needs to generate a new primary invite link replacing its previous one, use exportChatInviteLink again. +func ExportChatInviteLink(ctx context.Context, b *client.Bot, p *ExportChatInviteLinkParams) (string, error) { + return client.Call[*ExportChatInviteLinkParams, string](ctx, b, "exportChatInviteLink", p) +} + +// CreateChatInviteLinkParams is the parameter set for CreateChatInviteLink. +// +// Use this method to create an additional invite link for a chat. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. The link can be revoked using the method revokeChatInviteLink. Returns the new invite link as ChatInviteLink object. +type CreateChatInviteLinkParams struct { + // Unique identifier for the target chat or username of the target channel in the format @username + ChatID ChatID `json:"chat_id"` + // Invite link name; 0-32 characters + Name string `json:"name,omitempty"` + // Point in time (Unix timestamp) when the link will expire + ExpireDate *int64 `json:"expire_date,omitempty"` + // The maximum number of users that can be members of the chat simultaneously after joining the chat via this invite link; 1-99999 + MemberLimit *int64 `json:"member_limit,omitempty"` + // True, if users joining the chat via the link need to be approved by chat administrators. If True, member_limit can't be specified + CreatesJoinRequest *bool `json:"creates_join_request,omitempty"` +} + +// CreateChatInviteLink calls the createChatInviteLink Telegram Bot API method. +// +// Use this method to create an additional invite link for a chat. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. The link can be revoked using the method revokeChatInviteLink. Returns the new invite link as ChatInviteLink object. +func CreateChatInviteLink(ctx context.Context, b *client.Bot, p *CreateChatInviteLinkParams) (*ChatInviteLink, error) { + return client.Call[*CreateChatInviteLinkParams, *ChatInviteLink](ctx, b, "createChatInviteLink", p) +} + +// EditChatInviteLinkParams is the parameter set for EditChatInviteLink. +// +// Use this method to edit a non-primary invite link created by the bot. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns the edited invite link as a ChatInviteLink object. +type EditChatInviteLinkParams struct { + // Unique identifier for the target chat or username of the target channel in the format @username + ChatID ChatID `json:"chat_id"` + // The invite link to edit + InviteLink string `json:"invite_link"` + // Invite link name; 0-32 characters + Name string `json:"name,omitempty"` + // Point in time (Unix timestamp) when the link will expire + ExpireDate *int64 `json:"expire_date,omitempty"` + // The maximum number of users that can be members of the chat simultaneously after joining the chat via this invite link; 1-99999 + MemberLimit *int64 `json:"member_limit,omitempty"` + // True, if users joining the chat via the link need to be approved by chat administrators. If True, member_limit can't be specified + CreatesJoinRequest *bool `json:"creates_join_request,omitempty"` +} + +// EditChatInviteLink calls the editChatInviteLink Telegram Bot API method. +// +// Use this method to edit a non-primary invite link created by the bot. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns the edited invite link as a ChatInviteLink object. +func EditChatInviteLink(ctx context.Context, b *client.Bot, p *EditChatInviteLinkParams) (*ChatInviteLink, error) { + return client.Call[*EditChatInviteLinkParams, *ChatInviteLink](ctx, b, "editChatInviteLink", p) +} + +// CreateChatSubscriptionInviteLinkParams is the parameter set for CreateChatSubscriptionInviteLink. +// +// Use this method to create a subscription invite link for a channel chat. The bot must have the can_invite_users administrator rights. The link can be edited using the method editChatSubscriptionInviteLink or revoked using the method revokeChatInviteLink. Returns the new invite link as a ChatInviteLink object. +type CreateChatSubscriptionInviteLinkParams struct { + // Unique identifier for the target channel chat or username of the target channel in the format @username + ChatID ChatID `json:"chat_id"` + // Invite link name; 0-32 characters + Name string `json:"name,omitempty"` + // The number of seconds the subscription will be active for before the next payment. Currently, it must always be 2592000 (30 days). + SubscriptionPeriod int64 `json:"subscription_period"` + // The amount of Telegram Stars a user must pay initially and after each subsequent subscription period to be a member of the chat; 1-10000 + SubscriptionPrice int64 `json:"subscription_price"` +} + +// CreateChatSubscriptionInviteLink calls the createChatSubscriptionInviteLink Telegram Bot API method. +// +// Use this method to create a subscription invite link for a channel chat. The bot must have the can_invite_users administrator rights. The link can be edited using the method editChatSubscriptionInviteLink or revoked using the method revokeChatInviteLink. Returns the new invite link as a ChatInviteLink object. +func CreateChatSubscriptionInviteLink(ctx context.Context, b *client.Bot, p *CreateChatSubscriptionInviteLinkParams) (*ChatInviteLink, error) { + return client.Call[*CreateChatSubscriptionInviteLinkParams, *ChatInviteLink](ctx, b, "createChatSubscriptionInviteLink", p) +} + +// EditChatSubscriptionInviteLinkParams is the parameter set for EditChatSubscriptionInviteLink. +// +// Use this method to edit a subscription invite link created by the bot. The bot must have the can_invite_users administrator rights. Returns the edited invite link as a ChatInviteLink object. +type EditChatSubscriptionInviteLinkParams struct { + // Unique identifier for the target chat or username of the target channel in the format @username + ChatID ChatID `json:"chat_id"` + // The invite link to edit + InviteLink string `json:"invite_link"` + // Invite link name; 0-32 characters + Name string `json:"name,omitempty"` +} + +// EditChatSubscriptionInviteLink calls the editChatSubscriptionInviteLink Telegram Bot API method. +// +// Use this method to edit a subscription invite link created by the bot. The bot must have the can_invite_users administrator rights. Returns the edited invite link as a ChatInviteLink object. +func EditChatSubscriptionInviteLink(ctx context.Context, b *client.Bot, p *EditChatSubscriptionInviteLinkParams) (*ChatInviteLink, error) { + return client.Call[*EditChatSubscriptionInviteLinkParams, *ChatInviteLink](ctx, b, "editChatSubscriptionInviteLink", p) +} + +// RevokeChatInviteLinkParams is the parameter set for RevokeChatInviteLink. +// +// Use this method to revoke an invite link created by the bot. If the primary link is revoked, a new link is automatically generated. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns the revoked invite link as ChatInviteLink object. +type RevokeChatInviteLinkParams struct { + // Unique identifier of the target chat or username of the target channel in the format @username + ChatID ChatID `json:"chat_id"` + // The invite link to revoke + InviteLink string `json:"invite_link"` +} + +// RevokeChatInviteLink calls the revokeChatInviteLink Telegram Bot API method. +// +// Use this method to revoke an invite link created by the bot. If the primary link is revoked, a new link is automatically generated. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns the revoked invite link as ChatInviteLink object. +func RevokeChatInviteLink(ctx context.Context, b *client.Bot, p *RevokeChatInviteLinkParams) (*ChatInviteLink, error) { + return client.Call[*RevokeChatInviteLinkParams, *ChatInviteLink](ctx, b, "revokeChatInviteLink", p) +} + +// ApproveChatJoinRequestParams is the parameter set for ApproveChatJoinRequest. +// +// Use this method to approve a chat join request. The bot must be an administrator in the chat for this to work and must have the can_invite_users administrator right. Returns True on success. +type ApproveChatJoinRequestParams struct { + // Unique identifier for the target chat or username of the target channel in the format @username + ChatID ChatID `json:"chat_id"` + // Unique identifier of the target user + UserID int64 `json:"user_id"` +} + +// ApproveChatJoinRequest calls the approveChatJoinRequest Telegram Bot API method. +// +// Use this method to approve a chat join request. The bot must be an administrator in the chat for this to work and must have the can_invite_users administrator right. Returns True on success. +func ApproveChatJoinRequest(ctx context.Context, b *client.Bot, p *ApproveChatJoinRequestParams) (bool, error) { + return client.Call[*ApproveChatJoinRequestParams, bool](ctx, b, "approveChatJoinRequest", p) +} + +// DeclineChatJoinRequestParams is the parameter set for DeclineChatJoinRequest. +// +// Use this method to decline a chat join request. The bot must be an administrator in the chat for this to work and must have the can_invite_users administrator right. Returns True on success. +type DeclineChatJoinRequestParams struct { + // Unique identifier for the target chat or username of the target channel in the format @username + ChatID ChatID `json:"chat_id"` + // Unique identifier of the target user + UserID int64 `json:"user_id"` +} + +// DeclineChatJoinRequest calls the declineChatJoinRequest Telegram Bot API method. +// +// Use this method to decline a chat join request. The bot must be an administrator in the chat for this to work and must have the can_invite_users administrator right. Returns True on success. +func DeclineChatJoinRequest(ctx context.Context, b *client.Bot, p *DeclineChatJoinRequestParams) (bool, error) { + return client.Call[*DeclineChatJoinRequestParams, bool](ctx, b, "declineChatJoinRequest", p) +} + +// SetChatPhotoParams is the parameter set for SetChatPhoto. +// +// Use this method to set a new profile photo for the chat. Photos can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns True on success. +type SetChatPhotoParams struct { + // Unique identifier for the target chat or username of the target channel in the format @username + ChatID ChatID `json:"chat_id"` + // New chat photo, uploaded using multipart/form-data + Photo *InputFile `json:"photo"` +} + +// HasFile reports whether a multipart upload is required. +func (p *SetChatPhotoParams) HasFile() bool { + if p.Photo != nil && p.Photo.IsLocalUpload() { + return true + } + return false +} + +// MultipartFields returns the non-file fields used in the multipart body. +func (p *SetChatPhotoParams) MultipartFields() map[string]string { + out := map[string]string{} + out["chat_id"] = p.ChatID.String() + return out +} + +// MultipartFiles returns the file parts. +func (p *SetChatPhotoParams) MultipartFiles() []client.MultipartFile { + var files []client.MultipartFile + if p.Photo != nil && p.Photo.IsLocalUpload() { + name := p.Photo.Filename + if name == "" { + name = "photo" + } + files = append(files, client.MultipartFile{FieldName: "photo", Filename: name, Reader: p.Photo.Reader}) + } + return files +} + +// SetChatPhoto calls the setChatPhoto Telegram Bot API method. +// +// Use this method to set a new profile photo for the chat. Photos can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns True on success. +func SetChatPhoto(ctx context.Context, b *client.Bot, p *SetChatPhotoParams) (bool, error) { + return client.Call[*SetChatPhotoParams, bool](ctx, b, "setChatPhoto", p) +} + +// DeleteChatPhotoParams is the parameter set for DeleteChatPhoto. +// +// Use this method to delete a chat photo. Photos can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns True on success. +type DeleteChatPhotoParams struct { + // Unique identifier for the target chat or username of the target channel in the format @username + ChatID ChatID `json:"chat_id"` +} + +// DeleteChatPhoto calls the deleteChatPhoto Telegram Bot API method. +// +// Use this method to delete a chat photo. Photos can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns True on success. +func DeleteChatPhoto(ctx context.Context, b *client.Bot, p *DeleteChatPhotoParams) (bool, error) { + return client.Call[*DeleteChatPhotoParams, bool](ctx, b, "deleteChatPhoto", p) +} + +// SetChatTitleParams is the parameter set for SetChatTitle. +// +// Use this method to change the title of a chat. Titles can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns True on success. +type SetChatTitleParams struct { + // Unique identifier for the target chat or username of the target channel in the format @username + ChatID ChatID `json:"chat_id"` + // New chat title, 1-128 characters + Title string `json:"title"` +} + +// SetChatTitle calls the setChatTitle Telegram Bot API method. +// +// Use this method to change the title of a chat. Titles can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns True on success. +func SetChatTitle(ctx context.Context, b *client.Bot, p *SetChatTitleParams) (bool, error) { + return client.Call[*SetChatTitleParams, bool](ctx, b, "setChatTitle", p) +} + +// SetChatDescriptionParams is the parameter set for SetChatDescription. +// +// Use this method to change the description of a group, a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns True on success. +type SetChatDescriptionParams struct { + // Unique identifier for the target chat or username of the target channel in the format @username + ChatID ChatID `json:"chat_id"` + // New chat description, 0-255 characters + Description string `json:"description,omitempty"` +} + +// SetChatDescription calls the setChatDescription Telegram Bot API method. +// +// Use this method to change the description of a group, a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns True on success. +func SetChatDescription(ctx context.Context, b *client.Bot, p *SetChatDescriptionParams) (bool, error) { + return client.Call[*SetChatDescriptionParams, bool](ctx, b, "setChatDescription", p) +} + +// PinChatMessageParams is the parameter set for PinChatMessage. +// +// Use this method to add a message to the list of pinned messages in a chat. In private chats and channel direct messages chats, all non-service messages can be pinned. Conversely, the bot must be an administrator with the 'can_pin_messages' right or the 'can_edit_messages' right to pin messages in groups and channels respectively. Returns True on success. +type PinChatMessageParams struct { + // Unique identifier of the business connection on behalf of which the message will be pinned + BusinessConnectionID string `json:"business_connection_id,omitempty"` + // Unique identifier for the target chat or username of the target channel in the format @username + ChatID ChatID `json:"chat_id"` + // Identifier of a message to pin + MessageID int64 `json:"message_id"` + // Pass True if it is not necessary to send a notification to all chat members about the new pinned message. Notifications are always disabled in channels and private chats. + DisableNotification *bool `json:"disable_notification,omitempty"` +} + +// PinChatMessage calls the pinChatMessage Telegram Bot API method. +// +// Use this method to add a message to the list of pinned messages in a chat. In private chats and channel direct messages chats, all non-service messages can be pinned. Conversely, the bot must be an administrator with the 'can_pin_messages' right or the 'can_edit_messages' right to pin messages in groups and channels respectively. Returns True on success. +func PinChatMessage(ctx context.Context, b *client.Bot, p *PinChatMessageParams) (bool, error) { + return client.Call[*PinChatMessageParams, bool](ctx, b, "pinChatMessage", p) +} + +// UnpinChatMessageParams is the parameter set for UnpinChatMessage. +// +// Use this method to remove a message from the list of pinned messages in a chat. In private chats and channel direct messages chats, all messages can be unpinned. Conversely, the bot must be an administrator with the 'can_pin_messages' right or the 'can_edit_messages' right to unpin messages in groups and channels respectively. Returns True on success. +type UnpinChatMessageParams struct { + // Unique identifier of the business connection on behalf of which the message will be unpinned + BusinessConnectionID string `json:"business_connection_id,omitempty"` + // Unique identifier for the target chat or username of the target channel in the format @username + ChatID ChatID `json:"chat_id"` + // Identifier of the message to unpin. Required if business_connection_id is specified. If not specified, the most recent pinned message (by sending date) will be unpinned. + MessageID *int64 `json:"message_id,omitempty"` +} + +// UnpinChatMessage calls the unpinChatMessage Telegram Bot API method. +// +// Use this method to remove a message from the list of pinned messages in a chat. In private chats and channel direct messages chats, all messages can be unpinned. Conversely, the bot must be an administrator with the 'can_pin_messages' right or the 'can_edit_messages' right to unpin messages in groups and channels respectively. Returns True on success. +func UnpinChatMessage(ctx context.Context, b *client.Bot, p *UnpinChatMessageParams) (bool, error) { + return client.Call[*UnpinChatMessageParams, bool](ctx, b, "unpinChatMessage", p) +} + +// UnpinAllChatMessagesParams is the parameter set for UnpinAllChatMessages. +// +// Use this method to clear the list of pinned messages in a chat. In private chats and channel direct messages chats, no additional rights are required to unpin all pinned messages. Conversely, the bot must be an administrator with the 'can_pin_messages' right or the 'can_edit_messages' right to unpin all pinned messages in groups and channels respectively. Returns True on success. +type UnpinAllChatMessagesParams struct { + // Unique identifier for the target chat or username of the target channel in the format @username + ChatID ChatID `json:"chat_id"` +} + +// UnpinAllChatMessages calls the unpinAllChatMessages Telegram Bot API method. +// +// Use this method to clear the list of pinned messages in a chat. In private chats and channel direct messages chats, no additional rights are required to unpin all pinned messages. Conversely, the bot must be an administrator with the 'can_pin_messages' right or the 'can_edit_messages' right to unpin all pinned messages in groups and channels respectively. Returns True on success. +func UnpinAllChatMessages(ctx context.Context, b *client.Bot, p *UnpinAllChatMessagesParams) (bool, error) { + return client.Call[*UnpinAllChatMessagesParams, bool](ctx, b, "unpinAllChatMessages", p) +} + +// LeaveChatParams is the parameter set for LeaveChat. +// +// Use this method for your bot to leave a group, supergroup or channel. Returns True on success. +type LeaveChatParams struct { + // Unique identifier for the target chat or username of the target supergroup or channel in the format @username. Channel direct messages chats aren't supported; leave the corresponding channel instead. + ChatID ChatID `json:"chat_id"` +} + +// LeaveChat calls the leaveChat Telegram Bot API method. +// +// Use this method for your bot to leave a group, supergroup or channel. Returns True on success. +func LeaveChat(ctx context.Context, b *client.Bot, p *LeaveChatParams) (bool, error) { + return client.Call[*LeaveChatParams, bool](ctx, b, "leaveChat", p) +} + +// GetChatParams is the parameter set for GetChat. +// +// Use this method to get up-to-date information about the chat. Returns a ChatFullInfo object on success. +type GetChatParams struct { + // Unique identifier for the target chat or username of the target supergroup or channel in the format @username + ChatID ChatID `json:"chat_id"` +} + +// GetChat calls the getChat Telegram Bot API method. +// +// Use this method to get up-to-date information about the chat. Returns a ChatFullInfo object on success. +func GetChat(ctx context.Context, b *client.Bot, p *GetChatParams) (*ChatFullInfo, error) { + return client.Call[*GetChatParams, *ChatFullInfo](ctx, b, "getChat", p) +} + +// GetChatAdministratorsParams is the parameter set for GetChatAdministrators. +// +// Use this method to get a list of administrators in a chat. Returns an Array of ChatMember objects. +type GetChatAdministratorsParams struct { + // Unique identifier for the target chat or username of the target supergroup or channel in the format @username + ChatID ChatID `json:"chat_id"` + // Pass True to additionally receive all bots that are administrators of the chat. By default, bots other than the current bot are omitted. + ReturnBots *bool `json:"return_bots,omitempty"` +} + +// GetChatAdministrators calls the getChatAdministrators Telegram Bot API method. +// +// Use this method to get a list of administrators in a chat. Returns an Array of ChatMember objects. +func GetChatAdministrators(ctx context.Context, b *client.Bot, p *GetChatAdministratorsParams) ([]ChatMember, error) { + return client.Call[*GetChatAdministratorsParams, []ChatMember](ctx, b, "getChatAdministrators", p) +} + +// GetChatMemberCountParams is the parameter set for GetChatMemberCount. +// +// Use this method to get the number of members in a chat. Returns Int on success. +type GetChatMemberCountParams struct { + // Unique identifier for the target chat or username of the target supergroup or channel in the format @username + ChatID ChatID `json:"chat_id"` +} + +// GetChatMemberCount calls the getChatMemberCount Telegram Bot API method. +// +// Use this method to get the number of members in a chat. Returns Int on success. +func GetChatMemberCount(ctx context.Context, b *client.Bot, p *GetChatMemberCountParams) (int64, error) { + return client.Call[*GetChatMemberCountParams, int64](ctx, b, "getChatMemberCount", p) +} + +// GetChatMemberParams is the parameter set for GetChatMember. +// +// Use this method to get information about a member of a chat. The method is only guaranteed to work for other users if the bot is an administrator in the chat. Returns a ChatMember object on success. +type GetChatMemberParams struct { + // Unique identifier for the target chat or username of the target supergroup or channel in the format @username + ChatID ChatID `json:"chat_id"` + // Unique identifier of the target user + UserID int64 `json:"user_id"` +} + +// GetChatMember calls the getChatMember Telegram Bot API method. +// +// Use this method to get information about a member of a chat. The method is only guaranteed to work for other users if the bot is an administrator in the chat. Returns a ChatMember object on success. +func GetChatMember(ctx context.Context, b *client.Bot, p *GetChatMemberParams) (ChatMember, error) { + raw, err := client.CallRaw[*GetChatMemberParams](ctx, b, "getChatMember", p) + if err != nil { + return nil, err + } + return UnmarshalChatMember(raw) +} + +// GetUserPersonalChatMessagesParams is the parameter set for GetUserPersonalChatMessages. +// +// Use this method to get the last messages from the personal chat (i.e., the chat currently added to their profile) of a given user. On success, an array of Message objects is returned. +type GetUserPersonalChatMessagesParams struct { + // Unique identifier for the target user + UserID int64 `json:"user_id"` + // The maximum number of messages to return; 1-20 + Limit int64 `json:"limit"` +} + +// GetUserPersonalChatMessages calls the getUserPersonalChatMessages Telegram Bot API method. +// +// Use this method to get the last messages from the personal chat (i.e., the chat currently added to their profile) of a given user. On success, an array of Message objects is returned. +func GetUserPersonalChatMessages(ctx context.Context, b *client.Bot, p *GetUserPersonalChatMessagesParams) ([]Message, error) { + return client.Call[*GetUserPersonalChatMessagesParams, []Message](ctx, b, "getUserPersonalChatMessages", p) +} + +// SetChatStickerSetParams is the parameter set for SetChatStickerSet. +// +// Use this method to set a new group sticker set for a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Use the field can_set_sticker_set optionally returned in getChat requests to check if the bot can use this method. Returns True on success. +type SetChatStickerSetParams struct { + // Unique identifier for the target chat or username of the target supergroup in the format @username + ChatID ChatID `json:"chat_id"` + // Name of the sticker set to be set as the group sticker set + StickerSetName string `json:"sticker_set_name"` +} + +// SetChatStickerSet calls the setChatStickerSet Telegram Bot API method. +// +// Use this method to set a new group sticker set for a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Use the field can_set_sticker_set optionally returned in getChat requests to check if the bot can use this method. Returns True on success. +func SetChatStickerSet(ctx context.Context, b *client.Bot, p *SetChatStickerSetParams) (bool, error) { + return client.Call[*SetChatStickerSetParams, bool](ctx, b, "setChatStickerSet", p) +} + +// DeleteChatStickerSetParams is the parameter set for DeleteChatStickerSet. +// +// Use this method to delete a group sticker set from a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Use the field can_set_sticker_set optionally returned in getChat requests to check if the bot can use this method. Returns True on success. +type DeleteChatStickerSetParams struct { + // Unique identifier for the target chat or username of the target supergroup in the format @username + ChatID ChatID `json:"chat_id"` +} + +// DeleteChatStickerSet calls the deleteChatStickerSet Telegram Bot API method. +// +// Use this method to delete a group sticker set from a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Use the field can_set_sticker_set optionally returned in getChat requests to check if the bot can use this method. Returns True on success. +func DeleteChatStickerSet(ctx context.Context, b *client.Bot, p *DeleteChatStickerSetParams) (bool, error) { + return client.Call[*DeleteChatStickerSetParams, bool](ctx, b, "deleteChatStickerSet", p) +} + +// GetForumTopicIconStickersParams is the parameter set for GetForumTopicIconStickers. +// +// Use this method to get custom emoji stickers, which can be used as a forum topic icon by any user. Requires no parameters. Returns an Array of Sticker objects. +type GetForumTopicIconStickersParams struct { +} + +// GetForumTopicIconStickers calls the getForumTopicIconStickers Telegram Bot API method. +// +// Use this method to get custom emoji stickers, which can be used as a forum topic icon by any user. Requires no parameters. Returns an Array of Sticker objects. +func GetForumTopicIconStickers(ctx context.Context, b *client.Bot, p *GetForumTopicIconStickersParams) ([]Sticker, error) { + return client.Call[*GetForumTopicIconStickersParams, []Sticker](ctx, b, "getForumTopicIconStickers", p) +} + +// CreateForumTopicParams is the parameter set for CreateForumTopic. +// +// Use this method to create a topic in a forum supergroup chat or a private chat with a user. In the case of a supergroup chat the bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator right. Returns information about the created topic as a ForumTopic object. +type CreateForumTopicParams struct { + // Unique identifier for the target chat or username of the target supergroup in the format @username + ChatID ChatID `json:"chat_id"` + // Topic name, 1-128 characters + Name string `json:"name"` + // Color of the topic icon in RGB format. Currently, must be one of 7322096 (0x6FB9F0), 16766590 (0xFFD67E), 13338331 (0xCB86DB), 9367192 (0x8EEE98), 16749490 (0xFF93B2), or 16478047 (0xFB6F5F) + IconColor *int64 `json:"icon_color,omitempty"` + // Unique identifier of the custom emoji shown as the topic icon. Use getForumTopicIconStickers to get all allowed custom emoji identifiers. + IconCustomEmojiID string `json:"icon_custom_emoji_id,omitempty"` +} + +// CreateForumTopic calls the createForumTopic Telegram Bot API method. +// +// Use this method to create a topic in a forum supergroup chat or a private chat with a user. In the case of a supergroup chat the bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator right. Returns information about the created topic as a ForumTopic object. +func CreateForumTopic(ctx context.Context, b *client.Bot, p *CreateForumTopicParams) (*ForumTopic, error) { + return client.Call[*CreateForumTopicParams, *ForumTopic](ctx, b, "createForumTopic", p) +} + +// EditForumTopicParams is the parameter set for EditForumTopic. +// +// Use this method to edit name and icon of a topic in a forum supergroup chat or a private chat with a user. In the case of a supergroup chat the bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights, unless it is the creator of the topic. Returns True on success. +type EditForumTopicParams struct { + // Unique identifier for the target chat or username of the target supergroup in the format @username + ChatID ChatID `json:"chat_id"` + // Unique identifier for the target message thread of the forum topic + MessageThreadID int64 `json:"message_thread_id"` + // New topic name, 0-128 characters. If not specified or empty, the current name of the topic will be kept + Name string `json:"name,omitempty"` + // New unique identifier of the custom emoji shown as the topic icon. Use getForumTopicIconStickers to get all allowed custom emoji identifiers. Pass an empty string to remove the icon. If not specified, the current icon will be kept + IconCustomEmojiID string `json:"icon_custom_emoji_id,omitempty"` +} + +// EditForumTopic calls the editForumTopic Telegram Bot API method. +// +// Use this method to edit name and icon of a topic in a forum supergroup chat or a private chat with a user. In the case of a supergroup chat the bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights, unless it is the creator of the topic. Returns True on success. +func EditForumTopic(ctx context.Context, b *client.Bot, p *EditForumTopicParams) (bool, error) { + return client.Call[*EditForumTopicParams, bool](ctx, b, "editForumTopic", p) +} + +// CloseForumTopicParams is the parameter set for CloseForumTopic. +// +// Use this method to close an open topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights, unless it is the creator of the topic. Returns True on success. +type CloseForumTopicParams struct { + // Unique identifier for the target chat or username of the target supergroup in the format @username + ChatID ChatID `json:"chat_id"` + // Unique identifier for the target message thread of the forum topic + MessageThreadID int64 `json:"message_thread_id"` +} + +// CloseForumTopic calls the closeForumTopic Telegram Bot API method. +// +// Use this method to close an open topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights, unless it is the creator of the topic. Returns True on success. +func CloseForumTopic(ctx context.Context, b *client.Bot, p *CloseForumTopicParams) (bool, error) { + return client.Call[*CloseForumTopicParams, bool](ctx, b, "closeForumTopic", p) +} + +// ReopenForumTopicParams is the parameter set for ReopenForumTopic. +// +// Use this method to reopen a closed topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights, unless it is the creator of the topic. Returns True on success. +type ReopenForumTopicParams struct { + // Unique identifier for the target chat or username of the target supergroup in the format @username + ChatID ChatID `json:"chat_id"` + // Unique identifier for the target message thread of the forum topic + MessageThreadID int64 `json:"message_thread_id"` +} + +// ReopenForumTopic calls the reopenForumTopic Telegram Bot API method. +// +// Use this method to reopen a closed topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights, unless it is the creator of the topic. Returns True on success. +func ReopenForumTopic(ctx context.Context, b *client.Bot, p *ReopenForumTopicParams) (bool, error) { + return client.Call[*ReopenForumTopicParams, bool](ctx, b, "reopenForumTopic", p) +} + +// DeleteForumTopicParams is the parameter set for DeleteForumTopic. +// +// Use this method to delete a forum topic along with all its messages in a forum supergroup chat or a private chat with a user. In the case of a supergroup chat the bot must be an administrator in the chat for this to work and must have the can_delete_messages administrator rights. Returns True on success. +type DeleteForumTopicParams struct { + // Unique identifier for the target chat or username of the target supergroup in the format @username + ChatID ChatID `json:"chat_id"` + // Unique identifier for the target message thread of the forum topic + MessageThreadID int64 `json:"message_thread_id"` +} + +// DeleteForumTopic calls the deleteForumTopic Telegram Bot API method. +// +// Use this method to delete a forum topic along with all its messages in a forum supergroup chat or a private chat with a user. In the case of a supergroup chat the bot must be an administrator in the chat for this to work and must have the can_delete_messages administrator rights. Returns True on success. +func DeleteForumTopic(ctx context.Context, b *client.Bot, p *DeleteForumTopicParams) (bool, error) { + return client.Call[*DeleteForumTopicParams, bool](ctx, b, "deleteForumTopic", p) +} + +// UnpinAllForumTopicMessagesParams is the parameter set for UnpinAllForumTopicMessages. +// +// Use this method to clear the list of pinned messages in a forum topic in a forum supergroup chat or a private chat with a user. In the case of a supergroup chat the bot must be an administrator in the chat for this to work and must have the can_pin_messages administrator right in the supergroup. Returns True on success. +type UnpinAllForumTopicMessagesParams struct { + // Unique identifier for the target chat or username of the target supergroup in the format @username + ChatID ChatID `json:"chat_id"` + // Unique identifier for the target message thread of the forum topic + MessageThreadID int64 `json:"message_thread_id"` +} + +// UnpinAllForumTopicMessages calls the unpinAllForumTopicMessages Telegram Bot API method. +// +// Use this method to clear the list of pinned messages in a forum topic in a forum supergroup chat or a private chat with a user. In the case of a supergroup chat the bot must be an administrator in the chat for this to work and must have the can_pin_messages administrator right in the supergroup. Returns True on success. +func UnpinAllForumTopicMessages(ctx context.Context, b *client.Bot, p *UnpinAllForumTopicMessagesParams) (bool, error) { + return client.Call[*UnpinAllForumTopicMessagesParams, bool](ctx, b, "unpinAllForumTopicMessages", p) +} + +// EditGeneralForumTopicParams is the parameter set for EditGeneralForumTopic. +// +// Use this method to edit the name of the 'General' topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights. Returns True on success. +type EditGeneralForumTopicParams struct { + // Unique identifier for the target chat or username of the target supergroup in the format @username + ChatID ChatID `json:"chat_id"` + // New topic name, 1-128 characters + Name string `json:"name"` +} + +// EditGeneralForumTopic calls the editGeneralForumTopic Telegram Bot API method. +// +// Use this method to edit the name of the 'General' topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights. Returns True on success. +func EditGeneralForumTopic(ctx context.Context, b *client.Bot, p *EditGeneralForumTopicParams) (bool, error) { + return client.Call[*EditGeneralForumTopicParams, bool](ctx, b, "editGeneralForumTopic", p) +} + +// CloseGeneralForumTopicParams is the parameter set for CloseGeneralForumTopic. +// +// Use this method to close an open 'General' topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights. Returns True on success. +type CloseGeneralForumTopicParams struct { + // Unique identifier for the target chat or username of the target supergroup in the format @username + ChatID ChatID `json:"chat_id"` +} + +// CloseGeneralForumTopic calls the closeGeneralForumTopic Telegram Bot API method. +// +// Use this method to close an open 'General' topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights. Returns True on success. +func CloseGeneralForumTopic(ctx context.Context, b *client.Bot, p *CloseGeneralForumTopicParams) (bool, error) { + return client.Call[*CloseGeneralForumTopicParams, bool](ctx, b, "closeGeneralForumTopic", p) +} + +// ReopenGeneralForumTopicParams is the parameter set for ReopenGeneralForumTopic. +// +// Use this method to reopen a closed 'General' topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights. The topic will be automatically unhidden if it was hidden. Returns True on success. +type ReopenGeneralForumTopicParams struct { + // Unique identifier for the target chat or username of the target supergroup in the format @username + ChatID ChatID `json:"chat_id"` +} + +// ReopenGeneralForumTopic calls the reopenGeneralForumTopic Telegram Bot API method. +// +// Use this method to reopen a closed 'General' topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights. The topic will be automatically unhidden if it was hidden. Returns True on success. +func ReopenGeneralForumTopic(ctx context.Context, b *client.Bot, p *ReopenGeneralForumTopicParams) (bool, error) { + return client.Call[*ReopenGeneralForumTopicParams, bool](ctx, b, "reopenGeneralForumTopic", p) +} + +// HideGeneralForumTopicParams is the parameter set for HideGeneralForumTopic. +// +// Use this method to hide the 'General' topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights. The topic will be automatically closed if it was open. Returns True on success. +type HideGeneralForumTopicParams struct { + // Unique identifier for the target chat or username of the target supergroup in the format @username + ChatID ChatID `json:"chat_id"` +} + +// HideGeneralForumTopic calls the hideGeneralForumTopic Telegram Bot API method. +// +// Use this method to hide the 'General' topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights. The topic will be automatically closed if it was open. Returns True on success. +func HideGeneralForumTopic(ctx context.Context, b *client.Bot, p *HideGeneralForumTopicParams) (bool, error) { + return client.Call[*HideGeneralForumTopicParams, bool](ctx, b, "hideGeneralForumTopic", p) +} + +// UnhideGeneralForumTopicParams is the parameter set for UnhideGeneralForumTopic. +// +// Use this method to unhide the 'General' topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights. Returns True on success. +type UnhideGeneralForumTopicParams struct { + // Unique identifier for the target chat or username of the target supergroup in the format @username + ChatID ChatID `json:"chat_id"` +} + +// UnhideGeneralForumTopic calls the unhideGeneralForumTopic Telegram Bot API method. +// +// Use this method to unhide the 'General' topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights. Returns True on success. +func UnhideGeneralForumTopic(ctx context.Context, b *client.Bot, p *UnhideGeneralForumTopicParams) (bool, error) { + return client.Call[*UnhideGeneralForumTopicParams, bool](ctx, b, "unhideGeneralForumTopic", p) +} + +// UnpinAllGeneralForumTopicMessagesParams is the parameter set for UnpinAllGeneralForumTopicMessages. +// +// Use this method to clear the list of pinned messages in a General forum topic. The bot must be an administrator in the chat for this to work and must have the can_pin_messages administrator right in the supergroup. Returns True on success. +type UnpinAllGeneralForumTopicMessagesParams struct { + // Unique identifier for the target chat or username of the target supergroup in the format @username + ChatID ChatID `json:"chat_id"` +} + +// UnpinAllGeneralForumTopicMessages calls the unpinAllGeneralForumTopicMessages Telegram Bot API method. +// +// Use this method to clear the list of pinned messages in a General forum topic. The bot must be an administrator in the chat for this to work and must have the can_pin_messages administrator right in the supergroup. Returns True on success. +func UnpinAllGeneralForumTopicMessages(ctx context.Context, b *client.Bot, p *UnpinAllGeneralForumTopicMessagesParams) (bool, error) { + return client.Call[*UnpinAllGeneralForumTopicMessagesParams, bool](ctx, b, "unpinAllGeneralForumTopicMessages", p) +} + +// AnswerCallbackQueryParams is the parameter set for AnswerCallbackQuery. +// +// Use this method to send answers to callback queries sent from inline keyboards. The answer will be displayed to the user as a notification at the top of the chat screen or as an alert. On success, True is returned. +// Alternatively, the user can be redirected to the specified Game URL. For this option to work, you must first create a game for your bot via @BotFather and accept the terms. Otherwise, you may use links like t.me/your_bot?start=XXXX that open your bot with a parameter. +type AnswerCallbackQueryParams struct { + // Unique identifier for the query to be answered + CallbackQueryID string `json:"callback_query_id"` + // Text of the notification. If not specified, nothing will be shown to the user, 0-200 characters + Text string `json:"text,omitempty"` + // If True, an alert will be shown by the client instead of a notification at the top of the chat screen. Defaults to false. + ShowAlert *bool `json:"show_alert,omitempty"` + // URL that will be opened by the user's client. If you have created a Game and accepted the conditions via @BotFather, specify the URL that opens your game - note that this will only work if the query comes from a callback_game button.Otherwise, you may use links like t.me/your_bot?start=XXXX that open your bot with a parameter. + URL string `json:"url,omitempty"` + // The maximum amount of time in seconds that the result of the callback query may be cached client-side. Telegram apps will support caching starting in version 3.14. Defaults to 0. + CacheTime *int64 `json:"cache_time,omitempty"` +} + +// AnswerCallbackQuery calls the answerCallbackQuery Telegram Bot API method. +// +// Use this method to send answers to callback queries sent from inline keyboards. The answer will be displayed to the user as a notification at the top of the chat screen or as an alert. On success, True is returned. +// Alternatively, the user can be redirected to the specified Game URL. For this option to work, you must first create a game for your bot via @BotFather and accept the terms. Otherwise, you may use links like t.me/your_bot?start=XXXX that open your bot with a parameter. +func AnswerCallbackQuery(ctx context.Context, b *client.Bot, p *AnswerCallbackQueryParams) (bool, error) { + return client.Call[*AnswerCallbackQueryParams, bool](ctx, b, "answerCallbackQuery", p) +} + +// AnswerGuestQueryParams is the parameter set for AnswerGuestQuery. +// +// Use this method to reply to a received guest message. On success, a SentGuestMessage object is returned. +type AnswerGuestQueryParams struct { + // Unique identifier for the query to be answered + GuestQueryID string `json:"guest_query_id"` + // A JSON-serialized object describing the message to be sent + Result InlineQueryResult `json:"result"` +} + +// AnswerGuestQuery calls the answerGuestQuery Telegram Bot API method. +// +// Use this method to reply to a received guest message. On success, a SentGuestMessage object is returned. +func AnswerGuestQuery(ctx context.Context, b *client.Bot, p *AnswerGuestQueryParams) (*SentGuestMessage, error) { + return client.Call[*AnswerGuestQueryParams, *SentGuestMessage](ctx, b, "answerGuestQuery", p) +} + +// GetUserChatBoostsParams is the parameter set for GetUserChatBoosts. +// +// Use this method to get the list of boosts added to a chat by a user. Requires administrator rights in the chat. Returns a UserChatBoosts object. +type GetUserChatBoostsParams struct { + // Unique identifier for the chat or username of the channel in the format @username + ChatID ChatID `json:"chat_id"` + // Unique identifier of the target user + UserID int64 `json:"user_id"` +} + +// GetUserChatBoosts calls the getUserChatBoosts Telegram Bot API method. +// +// Use this method to get the list of boosts added to a chat by a user. Requires administrator rights in the chat. Returns a UserChatBoosts object. +func GetUserChatBoosts(ctx context.Context, b *client.Bot, p *GetUserChatBoostsParams) (*UserChatBoosts, error) { + return client.Call[*GetUserChatBoostsParams, *UserChatBoosts](ctx, b, "getUserChatBoosts", p) +} + +// GetBusinessConnectionParams is the parameter set for GetBusinessConnection. +// +// Use this method to get information about the connection of the bot with a business account. Returns a BusinessConnection object on success. +type GetBusinessConnectionParams struct { + // Unique identifier of the business connection + BusinessConnectionID string `json:"business_connection_id"` +} + +// GetBusinessConnection calls the getBusinessConnection Telegram Bot API method. +// +// Use this method to get information about the connection of the bot with a business account. Returns a BusinessConnection object on success. +func GetBusinessConnection(ctx context.Context, b *client.Bot, p *GetBusinessConnectionParams) (*BusinessConnection, error) { + return client.Call[*GetBusinessConnectionParams, *BusinessConnection](ctx, b, "getBusinessConnection", p) +} + +// GetManagedBotTokenParams is the parameter set for GetManagedBotToken. +// +// Use this method to get the token of a managed bot. Returns the token as String on success. +type GetManagedBotTokenParams struct { + // User identifier of the managed bot whose token will be returned + UserID int64 `json:"user_id"` +} + +// GetManagedBotToken calls the getManagedBotToken Telegram Bot API method. +// +// Use this method to get the token of a managed bot. Returns the token as String on success. +func GetManagedBotToken(ctx context.Context, b *client.Bot, p *GetManagedBotTokenParams) (string, error) { + return client.Call[*GetManagedBotTokenParams, string](ctx, b, "getManagedBotToken", p) +} + +// ReplaceManagedBotTokenParams is the parameter set for ReplaceManagedBotToken. +// +// Use this method to revoke the current token of a managed bot and generate a new one. Returns the new token as String on success. +type ReplaceManagedBotTokenParams struct { + // User identifier of the managed bot whose token will be replaced + UserID int64 `json:"user_id"` +} + +// ReplaceManagedBotToken calls the replaceManagedBotToken Telegram Bot API method. +// +// Use this method to revoke the current token of a managed bot and generate a new one. Returns the new token as String on success. +func ReplaceManagedBotToken(ctx context.Context, b *client.Bot, p *ReplaceManagedBotTokenParams) (string, error) { + return client.Call[*ReplaceManagedBotTokenParams, string](ctx, b, "replaceManagedBotToken", p) +} + +// GetManagedBotAccessSettingsParams is the parameter set for GetManagedBotAccessSettings. +// +// Use this method to get the access settings of a managed bot. Returns a BotAccessSettings object on success. +type GetManagedBotAccessSettingsParams struct { + // User identifier of the managed bot whose access settings will be returned + UserID int64 `json:"user_id"` +} + +// GetManagedBotAccessSettings calls the getManagedBotAccessSettings Telegram Bot API method. +// +// Use this method to get the access settings of a managed bot. Returns a BotAccessSettings object on success. +func GetManagedBotAccessSettings(ctx context.Context, b *client.Bot, p *GetManagedBotAccessSettingsParams) (*BotAccessSettings, error) { + return client.Call[*GetManagedBotAccessSettingsParams, *BotAccessSettings](ctx, b, "getManagedBotAccessSettings", p) +} + +// SetManagedBotAccessSettingsParams is the parameter set for SetManagedBotAccessSettings. +// +// Use this method to change the access settings of a managed bot. Returns True on success. +type SetManagedBotAccessSettingsParams struct { + // User identifier of the managed bot whose access settings will be changed + UserID int64 `json:"user_id"` + // Pass True, if only selected users can access the bot. The bot's owner can always access it. + IsAccessRestricted bool `json:"is_access_restricted"` + // A JSON-serialized list of up to 10 identifiers of users who will have access to the bot in addition to its owner. Ignored if is_access_restricted is false. + AddedUserIds []int64 `json:"added_user_ids,omitempty"` +} + +// SetManagedBotAccessSettings calls the setManagedBotAccessSettings Telegram Bot API method. +// +// Use this method to change the access settings of a managed bot. Returns True on success. +func SetManagedBotAccessSettings(ctx context.Context, b *client.Bot, p *SetManagedBotAccessSettingsParams) (bool, error) { + return client.Call[*SetManagedBotAccessSettingsParams, bool](ctx, b, "setManagedBotAccessSettings", p) +} + +// SetMyCommandsParams is the parameter set for SetMyCommands. +// +// Use this method to change the list of the bot's commands. See this manual for more details about bot commands. Returns True on success. +type SetMyCommandsParams struct { + // A JSON-serialized list of bot commands to be set as the list of the bot's commands. At most 100 commands can be specified. + Commands []BotCommand `json:"commands"` + // A JSON-serialized object, describing scope of users for which the commands are relevant. Defaults to BotCommandScopeDefault. + Scope *BotCommandScope `json:"scope,omitempty"` + // A two-letter ISO 639-1 language code. If empty, commands will be applied to all users from the given scope, for whose language there are no dedicated commands + LanguageCode string `json:"language_code,omitempty"` +} + +// SetMyCommands calls the setMyCommands Telegram Bot API method. +// +// Use this method to change the list of the bot's commands. See this manual for more details about bot commands. Returns True on success. +func SetMyCommands(ctx context.Context, b *client.Bot, p *SetMyCommandsParams) (bool, error) { + return client.Call[*SetMyCommandsParams, bool](ctx, b, "setMyCommands", p) +} + +// DeleteMyCommandsParams is the parameter set for DeleteMyCommands. +// +// Use this method to delete the list of the bot's commands for the given scope and user language. After deletion, higher level commands will be shown to affected users. Returns True on success. +type DeleteMyCommandsParams struct { + // A JSON-serialized object, describing scope of users for which the commands are relevant. Defaults to BotCommandScopeDefault. + Scope *BotCommandScope `json:"scope,omitempty"` + // A two-letter ISO 639-1 language code. If empty, commands will be applied to all users from the given scope, for whose language there are no dedicated commands + LanguageCode string `json:"language_code,omitempty"` +} + +// DeleteMyCommands calls the deleteMyCommands Telegram Bot API method. +// +// Use this method to delete the list of the bot's commands for the given scope and user language. After deletion, higher level commands will be shown to affected users. Returns True on success. +func DeleteMyCommands(ctx context.Context, b *client.Bot, p *DeleteMyCommandsParams) (bool, error) { + return client.Call[*DeleteMyCommandsParams, bool](ctx, b, "deleteMyCommands", p) +} + +// GetMyCommandsParams is the parameter set for GetMyCommands. +// +// Use this method to get the current list of the bot's commands for the given scope and user language. Returns an Array of BotCommand objects. If commands aren't set, an empty list is returned. +type GetMyCommandsParams struct { + // A JSON-serialized object, describing scope of users. Defaults to BotCommandScopeDefault. + Scope *BotCommandScope `json:"scope,omitempty"` + // A two-letter ISO 639-1 language code or an empty string + LanguageCode string `json:"language_code,omitempty"` +} + +// GetMyCommands calls the getMyCommands Telegram Bot API method. +// +// Use this method to get the current list of the bot's commands for the given scope and user language. Returns an Array of BotCommand objects. If commands aren't set, an empty list is returned. +func GetMyCommands(ctx context.Context, b *client.Bot, p *GetMyCommandsParams) ([]BotCommand, error) { + return client.Call[*GetMyCommandsParams, []BotCommand](ctx, b, "getMyCommands", p) +} + +// SetMyNameParams is the parameter set for SetMyName. +// +// Use this method to change the bot's name. Returns True on success. +type SetMyNameParams struct { + // New bot name; 0-64 characters. Pass an empty string to remove the dedicated name for the given language. + Name string `json:"name,omitempty"` + // A two-letter ISO 639-1 language code. If empty, the name will be shown to all users for whose language there is no dedicated name. + LanguageCode string `json:"language_code,omitempty"` +} + +// SetMyName calls the setMyName Telegram Bot API method. +// +// Use this method to change the bot's name. Returns True on success. +func SetMyName(ctx context.Context, b *client.Bot, p *SetMyNameParams) (bool, error) { + return client.Call[*SetMyNameParams, bool](ctx, b, "setMyName", p) +} + +// GetMyNameParams is the parameter set for GetMyName. +// +// Use this method to get the current bot name for the given user language. Returns BotName on success. +type GetMyNameParams struct { + // A two-letter ISO 639-1 language code or an empty string + LanguageCode string `json:"language_code,omitempty"` +} + +// GetMyName calls the getMyName Telegram Bot API method. +// +// Use this method to get the current bot name for the given user language. Returns BotName on success. +func GetMyName(ctx context.Context, b *client.Bot, p *GetMyNameParams) (*BotName, error) { + return client.Call[*GetMyNameParams, *BotName](ctx, b, "getMyName", p) +} + +// SetMyDescriptionParams is the parameter set for SetMyDescription. +// +// Use this method to change the bot's description, which is shown in the chat with the bot if the chat is empty. Returns True on success. +type SetMyDescriptionParams struct { + // New bot description; 0-512 characters. Pass an empty string to remove the dedicated description for the given language. + Description string `json:"description,omitempty"` + // A two-letter ISO 639-1 language code. If empty, the description will be applied to all users for whose language there is no dedicated description. + LanguageCode string `json:"language_code,omitempty"` +} + +// SetMyDescription calls the setMyDescription Telegram Bot API method. +// +// Use this method to change the bot's description, which is shown in the chat with the bot if the chat is empty. Returns True on success. +func SetMyDescription(ctx context.Context, b *client.Bot, p *SetMyDescriptionParams) (bool, error) { + return client.Call[*SetMyDescriptionParams, bool](ctx, b, "setMyDescription", p) +} + +// GetMyDescriptionParams is the parameter set for GetMyDescription. +// +// Use this method to get the current bot description for the given user language. Returns BotDescription on success. +type GetMyDescriptionParams struct { + // A two-letter ISO 639-1 language code or an empty string + LanguageCode string `json:"language_code,omitempty"` +} + +// GetMyDescription calls the getMyDescription Telegram Bot API method. +// +// Use this method to get the current bot description for the given user language. Returns BotDescription on success. +func GetMyDescription(ctx context.Context, b *client.Bot, p *GetMyDescriptionParams) (*BotDescription, error) { + return client.Call[*GetMyDescriptionParams, *BotDescription](ctx, b, "getMyDescription", p) +} + +// SetMyShortDescriptionParams is the parameter set for SetMyShortDescription. +// +// Use this method to change the bot's short description, which is shown on the bot's profile page and is sent together with the link when users share the bot. Returns True on success. +type SetMyShortDescriptionParams struct { + // New short description for the bot; 0-120 characters. Pass an empty string to remove the dedicated short description for the given language. + ShortDescription string `json:"short_description,omitempty"` + // A two-letter ISO 639-1 language code. If empty, the short description will be applied to all users for whose language there is no dedicated short description. + LanguageCode string `json:"language_code,omitempty"` +} + +// SetMyShortDescription calls the setMyShortDescription Telegram Bot API method. +// +// Use this method to change the bot's short description, which is shown on the bot's profile page and is sent together with the link when users share the bot. Returns True on success. +func SetMyShortDescription(ctx context.Context, b *client.Bot, p *SetMyShortDescriptionParams) (bool, error) { + return client.Call[*SetMyShortDescriptionParams, bool](ctx, b, "setMyShortDescription", p) +} + +// GetMyShortDescriptionParams is the parameter set for GetMyShortDescription. +// +// Use this method to get the current bot short description for the given user language. Returns BotShortDescription on success. +type GetMyShortDescriptionParams struct { + // A two-letter ISO 639-1 language code or an empty string + LanguageCode string `json:"language_code,omitempty"` +} + +// GetMyShortDescription calls the getMyShortDescription Telegram Bot API method. +// +// Use this method to get the current bot short description for the given user language. Returns BotShortDescription on success. +func GetMyShortDescription(ctx context.Context, b *client.Bot, p *GetMyShortDescriptionParams) (*BotShortDescription, error) { + return client.Call[*GetMyShortDescriptionParams, *BotShortDescription](ctx, b, "getMyShortDescription", p) +} + +// SetMyProfilePhotoParams is the parameter set for SetMyProfilePhoto. +// +// Changes the profile photo of the bot. Returns True on success. +type SetMyProfilePhotoParams struct { + // The new profile photo to set + Photo InputProfilePhoto `json:"photo"` +} + +// SetMyProfilePhoto calls the setMyProfilePhoto Telegram Bot API method. +// +// Changes the profile photo of the bot. Returns True on success. +func SetMyProfilePhoto(ctx context.Context, b *client.Bot, p *SetMyProfilePhotoParams) (bool, error) { + return client.Call[*SetMyProfilePhotoParams, bool](ctx, b, "setMyProfilePhoto", p) +} + +// RemoveMyProfilePhotoParams is the parameter set for RemoveMyProfilePhoto. +// +// Removes the profile photo of the bot. Requires no parameters. Returns True on success. +type RemoveMyProfilePhotoParams struct { +} + +// RemoveMyProfilePhoto calls the removeMyProfilePhoto Telegram Bot API method. +// +// Removes the profile photo of the bot. Requires no parameters. Returns True on success. +func RemoveMyProfilePhoto(ctx context.Context, b *client.Bot, p *RemoveMyProfilePhotoParams) (bool, error) { + return client.Call[*RemoveMyProfilePhotoParams, bool](ctx, b, "removeMyProfilePhoto", p) +} + +// SetChatMenuButtonParams is the parameter set for SetChatMenuButton. +// +// Use this method to change the bot's menu button in a private chat, or the default menu button. Returns True on success. +type SetChatMenuButtonParams struct { + // Unique identifier for the target private chat. If not specified, default bot's menu button will be changed + ChatID *int64 `json:"chat_id,omitempty"` + // A JSON-serialized object for the bot's new menu button. Defaults to MenuButtonDefault + MenuButton MenuButton `json:"menu_button,omitempty"` +} + +// SetChatMenuButton calls the setChatMenuButton Telegram Bot API method. +// +// Use this method to change the bot's menu button in a private chat, or the default menu button. Returns True on success. +func SetChatMenuButton(ctx context.Context, b *client.Bot, p *SetChatMenuButtonParams) (bool, error) { + return client.Call[*SetChatMenuButtonParams, bool](ctx, b, "setChatMenuButton", p) +} + +// GetChatMenuButtonParams is the parameter set for GetChatMenuButton. +// +// Use this method to get the current value of the bot's menu button in a private chat, or the default menu button. Returns MenuButton on success. +type GetChatMenuButtonParams struct { + // Unique identifier for the target private chat. If not specified, default bot's menu button will be returned + ChatID *int64 `json:"chat_id,omitempty"` +} + +// GetChatMenuButton calls the getChatMenuButton Telegram Bot API method. +// +// Use this method to get the current value of the bot's menu button in a private chat, or the default menu button. Returns MenuButton on success. +func GetChatMenuButton(ctx context.Context, b *client.Bot, p *GetChatMenuButtonParams) (MenuButton, error) { + raw, err := client.CallRaw[*GetChatMenuButtonParams](ctx, b, "getChatMenuButton", p) + if err != nil { + return nil, err + } + return UnmarshalMenuButton(raw) +} + +// SetMyDefaultAdministratorRightsParams is the parameter set for SetMyDefaultAdministratorRights. +// +// Use this method to change the default administrator rights requested by the bot when it's added as an administrator to groups or channels. These rights will be suggested to users, but they are free to modify the list before adding the bot. Returns True on success. +type SetMyDefaultAdministratorRightsParams struct { + // A JSON-serialized object describing new default administrator rights. If not specified, the default administrator rights will be cleared. + Rights *ChatAdministratorRights `json:"rights,omitempty"` + // Pass True to change the default administrator rights of the bot in channels. Otherwise, the default administrator rights of the bot for groups and supergroups will be changed. + ForChannels *bool `json:"for_channels,omitempty"` +} + +// SetMyDefaultAdministratorRights calls the setMyDefaultAdministratorRights Telegram Bot API method. +// +// Use this method to change the default administrator rights requested by the bot when it's added as an administrator to groups or channels. These rights will be suggested to users, but they are free to modify the list before adding the bot. Returns True on success. +func SetMyDefaultAdministratorRights(ctx context.Context, b *client.Bot, p *SetMyDefaultAdministratorRightsParams) (bool, error) { + return client.Call[*SetMyDefaultAdministratorRightsParams, bool](ctx, b, "setMyDefaultAdministratorRights", p) +} + +// GetMyDefaultAdministratorRightsParams is the parameter set for GetMyDefaultAdministratorRights. +// +// Use this method to get the current default administrator rights of the bot. Returns ChatAdministratorRights on success. +type GetMyDefaultAdministratorRightsParams struct { + // Pass True to get default administrator rights of the bot in channels. Otherwise, default administrator rights of the bot for groups and supergroups will be returned. + ForChannels *bool `json:"for_channels,omitempty"` +} + +// GetMyDefaultAdministratorRights calls the getMyDefaultAdministratorRights Telegram Bot API method. +// +// Use this method to get the current default administrator rights of the bot. Returns ChatAdministratorRights on success. +func GetMyDefaultAdministratorRights(ctx context.Context, b *client.Bot, p *GetMyDefaultAdministratorRightsParams) (*ChatAdministratorRights, error) { + return client.Call[*GetMyDefaultAdministratorRightsParams, *ChatAdministratorRights](ctx, b, "getMyDefaultAdministratorRights", p) +} + +// GetAvailableGiftsParams is the parameter set for GetAvailableGifts. +// +// Returns the list of gifts that can be sent by the bot to users and channel chats. Requires no parameters. Returns a Gifts object. +type GetAvailableGiftsParams struct { +} + +// GetAvailableGifts calls the getAvailableGifts Telegram Bot API method. +// +// Returns the list of gifts that can be sent by the bot to users and channel chats. Requires no parameters. Returns a Gifts object. +func GetAvailableGifts(ctx context.Context, b *client.Bot, p *GetAvailableGiftsParams) (*Gifts, error) { + return client.Call[*GetAvailableGiftsParams, *Gifts](ctx, b, "getAvailableGifts", p) +} + +// SendGiftParams is the parameter set for SendGift. +// +// Sends a gift to the given user or channel chat. The gift can't be converted to Telegram Stars by the receiver. Returns True on success. +type SendGiftParams struct { + // Required if chat_id is not specified. Unique identifier of the target user who will receive the gift. + UserID *int64 `json:"user_id,omitempty"` + // Required if user_id is not specified. Unique identifier for the chat or username of the channel (in the format @username) that will receive the gift. + ChatID *ChatID `json:"chat_id,omitempty"` + // Identifier of the gift; limited gifts can't be sent to channel chats + GiftID string `json:"gift_id"` + // Pass True to pay for the gift upgrade from the bot's balance, thereby making the upgrade free for the receiver + PayForUpgrade *bool `json:"pay_for_upgrade,omitempty"` + // Text that will be shown along with the gift; 0-128 characters + Text string `json:"text,omitempty"` + // Mode for parsing entities in the text. See formatting options for more details. Entities other than “bold”, “italic”, “underline”, “strikethrough”, “spoiler”, “custom_emoji”, and “date_time” are ignored. + TextParseMode string `json:"text_parse_mode,omitempty"` + // A JSON-serialized list of special entities that appear in the gift text. It can be specified instead of text_parse_mode. Entities other than “bold”, “italic”, “underline”, “strikethrough”, “spoiler”, “custom_emoji”, and “date_time” are ignored. + TextEntities []MessageEntity `json:"text_entities,omitempty"` +} + +// SendGift calls the sendGift Telegram Bot API method. +// +// Sends a gift to the given user or channel chat. The gift can't be converted to Telegram Stars by the receiver. Returns True on success. +func SendGift(ctx context.Context, b *client.Bot, p *SendGiftParams) (bool, error) { + return client.Call[*SendGiftParams, bool](ctx, b, "sendGift", p) +} + +// GiftPremiumSubscriptionParams is the parameter set for GiftPremiumSubscription. +// +// Gifts a Telegram Premium subscription to the given user. Returns True on success. +type GiftPremiumSubscriptionParams struct { + // Unique identifier of the target user who will receive a Telegram Premium subscription + UserID int64 `json:"user_id"` + // Number of months the Telegram Premium subscription will be active for the user; must be one of 3, 6, or 12 + MonthCount int64 `json:"month_count"` + // Number of Telegram Stars to pay for the Telegram Premium subscription; must be 1000 for 3 months, 1500 for 6 months, and 2500 for 12 months + StarCount int64 `json:"star_count"` + // Text that will be shown along with the service message about the subscription; 0-128 characters + Text string `json:"text,omitempty"` + // Mode for parsing entities in the text. See formatting options for more details. Entities other than “bold”, “italic”, “underline”, “strikethrough”, “spoiler”, “custom_emoji”, and “date_time” are ignored. + TextParseMode string `json:"text_parse_mode,omitempty"` + // A JSON-serialized list of special entities that appear in the gift text. It can be specified instead of text_parse_mode. Entities other than “bold”, “italic”, “underline”, “strikethrough”, “spoiler”, “custom_emoji”, and “date_time” are ignored. + TextEntities []MessageEntity `json:"text_entities,omitempty"` +} + +// GiftPremiumSubscription calls the giftPremiumSubscription Telegram Bot API method. +// +// Gifts a Telegram Premium subscription to the given user. Returns True on success. +func GiftPremiumSubscription(ctx context.Context, b *client.Bot, p *GiftPremiumSubscriptionParams) (bool, error) { + return client.Call[*GiftPremiumSubscriptionParams, bool](ctx, b, "giftPremiumSubscription", p) +} + +// VerifyUserParams is the parameter set for VerifyUser. +// +// Verifies a user on behalf of the organization which is represented by the bot. Returns True on success. +type VerifyUserParams struct { + // Unique identifier of the target user + UserID int64 `json:"user_id"` + // Custom description for the verification; 0-70 characters. Must be empty if the organization isn't allowed to provide a custom verification description. + CustomDescription string `json:"custom_description,omitempty"` +} + +// VerifyUser calls the verifyUser Telegram Bot API method. +// +// Verifies a user on behalf of the organization which is represented by the bot. Returns True on success. +func VerifyUser(ctx context.Context, b *client.Bot, p *VerifyUserParams) (bool, error) { + return client.Call[*VerifyUserParams, bool](ctx, b, "verifyUser", p) +} + +// VerifyChatParams is the parameter set for VerifyChat. +// +// Verifies a chat on behalf of the organization which is represented by the bot. Returns True on success. +type VerifyChatParams struct { + // Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username. Channel direct messages chats can't be verified. + ChatID ChatID `json:"chat_id"` + // Custom description for the verification; 0-70 characters. Must be empty if the organization isn't allowed to provide a custom verification description. + CustomDescription string `json:"custom_description,omitempty"` +} + +// VerifyChat calls the verifyChat Telegram Bot API method. +// +// Verifies a chat on behalf of the organization which is represented by the bot. Returns True on success. +func VerifyChat(ctx context.Context, b *client.Bot, p *VerifyChatParams) (bool, error) { + return client.Call[*VerifyChatParams, bool](ctx, b, "verifyChat", p) +} + +// RemoveUserVerificationParams is the parameter set for RemoveUserVerification. +// +// Removes verification from a user who is currently verified on behalf of the organization represented by the bot. Returns True on success. +type RemoveUserVerificationParams struct { + // Unique identifier of the target user + UserID int64 `json:"user_id"` +} + +// RemoveUserVerification calls the removeUserVerification Telegram Bot API method. +// +// Removes verification from a user who is currently verified on behalf of the organization represented by the bot. Returns True on success. +func RemoveUserVerification(ctx context.Context, b *client.Bot, p *RemoveUserVerificationParams) (bool, error) { + return client.Call[*RemoveUserVerificationParams, bool](ctx, b, "removeUserVerification", p) +} + +// RemoveChatVerificationParams is the parameter set for RemoveChatVerification. +// +// Removes verification from a chat that is currently verified on behalf of the organization represented by the bot. Returns True on success. +type RemoveChatVerificationParams struct { + // Unique identifier for the target chat or username of the target bot or channel in the format @username + ChatID ChatID `json:"chat_id"` +} + +// RemoveChatVerification calls the removeChatVerification Telegram Bot API method. +// +// Removes verification from a chat that is currently verified on behalf of the organization represented by the bot. Returns True on success. +func RemoveChatVerification(ctx context.Context, b *client.Bot, p *RemoveChatVerificationParams) (bool, error) { + return client.Call[*RemoveChatVerificationParams, bool](ctx, b, "removeChatVerification", p) +} + +// ReadBusinessMessageParams is the parameter set for ReadBusinessMessage. +// +// Marks incoming message as read on behalf of a business account. Requires the can_read_messages business bot right. Returns True on success. +type ReadBusinessMessageParams struct { + // Unique identifier of the business connection on behalf of which to read the message + BusinessConnectionID string `json:"business_connection_id"` + // Unique identifier of the chat in which the message was received. The chat must have been active in the last 24 hours. + ChatID int64 `json:"chat_id"` + // Unique identifier of the message to mark as read + MessageID int64 `json:"message_id"` +} + +// ReadBusinessMessage calls the readBusinessMessage Telegram Bot API method. +// +// Marks incoming message as read on behalf of a business account. Requires the can_read_messages business bot right. Returns True on success. +func ReadBusinessMessage(ctx context.Context, b *client.Bot, p *ReadBusinessMessageParams) (bool, error) { + return client.Call[*ReadBusinessMessageParams, bool](ctx, b, "readBusinessMessage", p) +} + +// DeleteBusinessMessagesParams is the parameter set for DeleteBusinessMessages. +// +// Delete messages on behalf of a business account. Requires the can_delete_sent_messages business bot right to delete messages sent by the bot itself, or the can_delete_all_messages business bot right to delete any message. Returns True on success. +type DeleteBusinessMessagesParams struct { + // Unique identifier of the business connection on behalf of which to delete the messages + BusinessConnectionID string `json:"business_connection_id"` + // A JSON-serialized list of 1-100 identifiers of messages to delete. All messages must be from the same chat. See deleteMessage for limitations on which messages can be deleted + MessageIds []int64 `json:"message_ids"` +} + +// DeleteBusinessMessages calls the deleteBusinessMessages Telegram Bot API method. +// +// Delete messages on behalf of a business account. Requires the can_delete_sent_messages business bot right to delete messages sent by the bot itself, or the can_delete_all_messages business bot right to delete any message. Returns True on success. +func DeleteBusinessMessages(ctx context.Context, b *client.Bot, p *DeleteBusinessMessagesParams) (bool, error) { + return client.Call[*DeleteBusinessMessagesParams, bool](ctx, b, "deleteBusinessMessages", p) +} + +// SetBusinessAccountNameParams is the parameter set for SetBusinessAccountName. +// +// Changes the first and last name of a managed business account. Requires the can_change_name business bot right. Returns True on success. +type SetBusinessAccountNameParams struct { + // Unique identifier of the business connection + BusinessConnectionID string `json:"business_connection_id"` + // The new value of the first name for the business account; 1-64 characters + FirstName string `json:"first_name"` + // The new value of the last name for the business account; 0-64 characters + LastName string `json:"last_name,omitempty"` +} + +// SetBusinessAccountName calls the setBusinessAccountName Telegram Bot API method. +// +// Changes the first and last name of a managed business account. Requires the can_change_name business bot right. Returns True on success. +func SetBusinessAccountName(ctx context.Context, b *client.Bot, p *SetBusinessAccountNameParams) (bool, error) { + return client.Call[*SetBusinessAccountNameParams, bool](ctx, b, "setBusinessAccountName", p) +} + +// SetBusinessAccountUsernameParams is the parameter set for SetBusinessAccountUsername. +// +// Changes the username of a managed business account. Requires the can_change_username business bot right. Returns True on success. +type SetBusinessAccountUsernameParams struct { + // Unique identifier of the business connection + BusinessConnectionID string `json:"business_connection_id"` + // The new value of the username for the business account; 0-32 characters + Username string `json:"username,omitempty"` +} + +// SetBusinessAccountUsername calls the setBusinessAccountUsername Telegram Bot API method. +// +// Changes the username of a managed business account. Requires the can_change_username business bot right. Returns True on success. +func SetBusinessAccountUsername(ctx context.Context, b *client.Bot, p *SetBusinessAccountUsernameParams) (bool, error) { + return client.Call[*SetBusinessAccountUsernameParams, bool](ctx, b, "setBusinessAccountUsername", p) +} + +// SetBusinessAccountBioParams is the parameter set for SetBusinessAccountBio. +// +// Changes the bio of a managed business account. Requires the can_change_bio business bot right. Returns True on success. +type SetBusinessAccountBioParams struct { + // Unique identifier of the business connection + BusinessConnectionID string `json:"business_connection_id"` + // The new value of the bio for the business account; 0-140 characters + Bio string `json:"bio,omitempty"` +} + +// SetBusinessAccountBio calls the setBusinessAccountBio Telegram Bot API method. +// +// Changes the bio of a managed business account. Requires the can_change_bio business bot right. Returns True on success. +func SetBusinessAccountBio(ctx context.Context, b *client.Bot, p *SetBusinessAccountBioParams) (bool, error) { + return client.Call[*SetBusinessAccountBioParams, bool](ctx, b, "setBusinessAccountBio", p) +} + +// SetBusinessAccountProfilePhotoParams is the parameter set for SetBusinessAccountProfilePhoto. +// +// Changes the profile photo of a managed business account. Requires the can_edit_profile_photo business bot right. Returns True on success. +type SetBusinessAccountProfilePhotoParams struct { + // Unique identifier of the business connection + BusinessConnectionID string `json:"business_connection_id"` + // The new profile photo to set + Photo InputProfilePhoto `json:"photo"` + // Pass True to set the public photo, which will be visible even if the main photo is hidden by the business account's privacy settings. An account can have only one public photo. + IsPublic *bool `json:"is_public,omitempty"` +} + +// SetBusinessAccountProfilePhoto calls the setBusinessAccountProfilePhoto Telegram Bot API method. +// +// Changes the profile photo of a managed business account. Requires the can_edit_profile_photo business bot right. Returns True on success. +func SetBusinessAccountProfilePhoto(ctx context.Context, b *client.Bot, p *SetBusinessAccountProfilePhotoParams) (bool, error) { + return client.Call[*SetBusinessAccountProfilePhotoParams, bool](ctx, b, "setBusinessAccountProfilePhoto", p) +} + +// RemoveBusinessAccountProfilePhotoParams is the parameter set for RemoveBusinessAccountProfilePhoto. +// +// Removes the current profile photo of a managed business account. Requires the can_edit_profile_photo business bot right. Returns True on success. +type RemoveBusinessAccountProfilePhotoParams struct { + // Unique identifier of the business connection + BusinessConnectionID string `json:"business_connection_id"` + // Pass True to remove the public photo, which is visible even if the main photo is hidden by the business account's privacy settings. After the main photo is removed, the previous profile photo (if present) becomes the main photo. + IsPublic *bool `json:"is_public,omitempty"` +} + +// RemoveBusinessAccountProfilePhoto calls the removeBusinessAccountProfilePhoto Telegram Bot API method. +// +// Removes the current profile photo of a managed business account. Requires the can_edit_profile_photo business bot right. Returns True on success. +func RemoveBusinessAccountProfilePhoto(ctx context.Context, b *client.Bot, p *RemoveBusinessAccountProfilePhotoParams) (bool, error) { + return client.Call[*RemoveBusinessAccountProfilePhotoParams, bool](ctx, b, "removeBusinessAccountProfilePhoto", p) +} + +// SetBusinessAccountGiftSettingsParams is the parameter set for SetBusinessAccountGiftSettings. +// +// Changes the privacy settings pertaining to incoming gifts in a managed business account. Requires the can_change_gift_settings business bot right. Returns True on success. +type SetBusinessAccountGiftSettingsParams struct { + // Unique identifier of the business connection + BusinessConnectionID string `json:"business_connection_id"` + // Pass True, if a button for sending a gift to the user or by the business account must always be shown in the input field + ShowGiftButton bool `json:"show_gift_button"` + // Types of gifts accepted by the business account + AcceptedGiftTypes AcceptedGiftTypes `json:"accepted_gift_types"` +} + +// SetBusinessAccountGiftSettings calls the setBusinessAccountGiftSettings Telegram Bot API method. +// +// Changes the privacy settings pertaining to incoming gifts in a managed business account. Requires the can_change_gift_settings business bot right. Returns True on success. +func SetBusinessAccountGiftSettings(ctx context.Context, b *client.Bot, p *SetBusinessAccountGiftSettingsParams) (bool, error) { + return client.Call[*SetBusinessAccountGiftSettingsParams, bool](ctx, b, "setBusinessAccountGiftSettings", p) +} + +// GetBusinessAccountStarBalanceParams is the parameter set for GetBusinessAccountStarBalance. +// +// Returns the amount of Telegram Stars owned by a managed business account. Requires the can_view_gifts_and_stars business bot right. Returns StarAmount on success. +type GetBusinessAccountStarBalanceParams struct { + // Unique identifier of the business connection + BusinessConnectionID string `json:"business_connection_id"` +} + +// GetBusinessAccountStarBalance calls the getBusinessAccountStarBalance Telegram Bot API method. +// +// Returns the amount of Telegram Stars owned by a managed business account. Requires the can_view_gifts_and_stars business bot right. Returns StarAmount on success. +func GetBusinessAccountStarBalance(ctx context.Context, b *client.Bot, p *GetBusinessAccountStarBalanceParams) (*StarAmount, error) { + return client.Call[*GetBusinessAccountStarBalanceParams, *StarAmount](ctx, b, "getBusinessAccountStarBalance", p) +} + +// TransferBusinessAccountStarsParams is the parameter set for TransferBusinessAccountStars. +// +// Transfers Telegram Stars from the business account balance to the bot's balance. Requires the can_transfer_stars business bot right. Returns True on success. +type TransferBusinessAccountStarsParams struct { + // Unique identifier of the business connection + BusinessConnectionID string `json:"business_connection_id"` + // Number of Telegram Stars to transfer; 1-10000 + StarCount int64 `json:"star_count"` +} + +// TransferBusinessAccountStars calls the transferBusinessAccountStars Telegram Bot API method. +// +// Transfers Telegram Stars from the business account balance to the bot's balance. Requires the can_transfer_stars business bot right. Returns True on success. +func TransferBusinessAccountStars(ctx context.Context, b *client.Bot, p *TransferBusinessAccountStarsParams) (bool, error) { + return client.Call[*TransferBusinessAccountStarsParams, bool](ctx, b, "transferBusinessAccountStars", p) +} + +// GetBusinessAccountGiftsParams is the parameter set for GetBusinessAccountGifts. +// +// Returns the gifts received and owned by a managed business account. Requires the can_view_gifts_and_stars business bot right. Returns OwnedGifts on success. +type GetBusinessAccountGiftsParams struct { + // Unique identifier of the business connection + BusinessConnectionID string `json:"business_connection_id"` + // Pass True to exclude gifts that aren't saved to the account's profile page + ExcludeUnsaved *bool `json:"exclude_unsaved,omitempty"` + // Pass True to exclude gifts that are saved to the account's profile page + ExcludeSaved *bool `json:"exclude_saved,omitempty"` + // Pass True to exclude gifts that can be purchased an unlimited number of times + ExcludeUnlimited *bool `json:"exclude_unlimited,omitempty"` + // Pass True to exclude gifts that can be purchased a limited number of times and can be upgraded to unique + ExcludeLimitedUpgradable *bool `json:"exclude_limited_upgradable,omitempty"` + // Pass True to exclude gifts that can be purchased a limited number of times and can't be upgraded to unique + ExcludeLimitedNonUpgradable *bool `json:"exclude_limited_non_upgradable,omitempty"` + // Pass True to exclude unique gifts + ExcludeUnique *bool `json:"exclude_unique,omitempty"` + // Pass True to exclude gifts that were assigned from the TON blockchain and can't be resold or transferred in Telegram + ExcludeFromBlockchain *bool `json:"exclude_from_blockchain,omitempty"` + // Pass True to sort results by gift price instead of send date. Sorting is applied before pagination. + SortByPrice *bool `json:"sort_by_price,omitempty"` + // Offset of the first entry to return as received from the previous request; use empty string to get the first chunk of results + Offset string `json:"offset,omitempty"` + // The maximum number of gifts to be returned; 1-100. Defaults to 100 + Limit *int64 `json:"limit,omitempty"` +} + +// GetBusinessAccountGifts calls the getBusinessAccountGifts Telegram Bot API method. +// +// Returns the gifts received and owned by a managed business account. Requires the can_view_gifts_and_stars business bot right. Returns OwnedGifts on success. +func GetBusinessAccountGifts(ctx context.Context, b *client.Bot, p *GetBusinessAccountGiftsParams) (*OwnedGifts, error) { + return client.Call[*GetBusinessAccountGiftsParams, *OwnedGifts](ctx, b, "getBusinessAccountGifts", p) +} + +// GetUserGiftsParams is the parameter set for GetUserGifts. +// +// Returns the gifts owned and hosted by a user. Returns OwnedGifts on success. +type GetUserGiftsParams struct { + // Unique identifier of the user + UserID int64 `json:"user_id"` + // Pass True to exclude gifts that can be purchased an unlimited number of times + ExcludeUnlimited *bool `json:"exclude_unlimited,omitempty"` + // Pass True to exclude gifts that can be purchased a limited number of times and can be upgraded to unique + ExcludeLimitedUpgradable *bool `json:"exclude_limited_upgradable,omitempty"` + // Pass True to exclude gifts that can be purchased a limited number of times and can't be upgraded to unique + ExcludeLimitedNonUpgradable *bool `json:"exclude_limited_non_upgradable,omitempty"` + // Pass True to exclude gifts that were assigned from the TON blockchain and can't be resold or transferred in Telegram + ExcludeFromBlockchain *bool `json:"exclude_from_blockchain,omitempty"` + // Pass True to exclude unique gifts + ExcludeUnique *bool `json:"exclude_unique,omitempty"` + // Pass True to sort results by gift price instead of send date. Sorting is applied before pagination. + SortByPrice *bool `json:"sort_by_price,omitempty"` + // Offset of the first entry to return as received from the previous request; use an empty string to get the first chunk of results + Offset string `json:"offset,omitempty"` + // The maximum number of gifts to be returned; 1-100. Defaults to 100 + Limit *int64 `json:"limit,omitempty"` +} + +// GetUserGifts calls the getUserGifts Telegram Bot API method. +// +// Returns the gifts owned and hosted by a user. Returns OwnedGifts on success. +func GetUserGifts(ctx context.Context, b *client.Bot, p *GetUserGiftsParams) (*OwnedGifts, error) { + return client.Call[*GetUserGiftsParams, *OwnedGifts](ctx, b, "getUserGifts", p) +} + +// GetChatGiftsParams is the parameter set for GetChatGifts. +// +// Returns the gifts owned by a chat. Returns OwnedGifts on success. +type GetChatGiftsParams struct { + // Unique identifier for the target chat or username of the target channel in the format @username + ChatID ChatID `json:"chat_id"` + // Pass True to exclude gifts that aren't saved to the chat's profile page. Always True, unless the bot has the can_post_messages administrator right in the channel. + ExcludeUnsaved *bool `json:"exclude_unsaved,omitempty"` + // Pass True to exclude gifts that are saved to the chat's profile page. Always False, unless the bot has the can_post_messages administrator right in the channel. + ExcludeSaved *bool `json:"exclude_saved,omitempty"` + // Pass True to exclude gifts that can be purchased an unlimited number of times + ExcludeUnlimited *bool `json:"exclude_unlimited,omitempty"` + // Pass True to exclude gifts that can be purchased a limited number of times and can be upgraded to unique + ExcludeLimitedUpgradable *bool `json:"exclude_limited_upgradable,omitempty"` + // Pass True to exclude gifts that can be purchased a limited number of times and can't be upgraded to unique + ExcludeLimitedNonUpgradable *bool `json:"exclude_limited_non_upgradable,omitempty"` + // Pass True to exclude gifts that were assigned from the TON blockchain and can't be resold or transferred in Telegram + ExcludeFromBlockchain *bool `json:"exclude_from_blockchain,omitempty"` + // Pass True to exclude unique gifts + ExcludeUnique *bool `json:"exclude_unique,omitempty"` + // Pass True to sort results by gift price instead of send date. Sorting is applied before pagination. + SortByPrice *bool `json:"sort_by_price,omitempty"` + // Offset of the first entry to return as received from the previous request; use an empty string to get the first chunk of results + Offset string `json:"offset,omitempty"` + // The maximum number of gifts to be returned; 1-100. Defaults to 100 + Limit *int64 `json:"limit,omitempty"` +} + +// GetChatGifts calls the getChatGifts Telegram Bot API method. +// +// Returns the gifts owned by a chat. Returns OwnedGifts on success. +func GetChatGifts(ctx context.Context, b *client.Bot, p *GetChatGiftsParams) (*OwnedGifts, error) { + return client.Call[*GetChatGiftsParams, *OwnedGifts](ctx, b, "getChatGifts", p) +} + +// ConvertGiftToStarsParams is the parameter set for ConvertGiftToStars. +// +// Converts a given regular gift to Telegram Stars. Requires the can_convert_gifts_to_stars business bot right. Returns True on success. +type ConvertGiftToStarsParams struct { + // Unique identifier of the business connection + BusinessConnectionID string `json:"business_connection_id"` + // Unique identifier of the regular gift that should be converted to Telegram Stars + OwnedGiftID string `json:"owned_gift_id"` +} + +// ConvertGiftToStars calls the convertGiftToStars Telegram Bot API method. +// +// Converts a given regular gift to Telegram Stars. Requires the can_convert_gifts_to_stars business bot right. Returns True on success. +func ConvertGiftToStars(ctx context.Context, b *client.Bot, p *ConvertGiftToStarsParams) (bool, error) { + return client.Call[*ConvertGiftToStarsParams, bool](ctx, b, "convertGiftToStars", p) +} + +// UpgradeGiftParams is the parameter set for UpgradeGift. +// +// Upgrades a given regular gift to a unique gift. Requires the can_transfer_and_upgrade_gifts business bot right. Additionally requires the can_transfer_stars business bot right if the upgrade is paid. Returns True on success. +type UpgradeGiftParams struct { + // Unique identifier of the business connection + BusinessConnectionID string `json:"business_connection_id"` + // Unique identifier of the regular gift that should be upgraded to a unique one + OwnedGiftID string `json:"owned_gift_id"` + // Pass True to keep the original gift text, sender and receiver in the upgraded gift + KeepOriginalDetails *bool `json:"keep_original_details,omitempty"` + // The amount of Telegram Stars that will be paid for the upgrade from the business account balance. If gift.prepaid_upgrade_star_count > 0, then pass 0, otherwise, the can_transfer_stars business bot right is required and gift.upgrade_star_count must be passed. + StarCount *int64 `json:"star_count,omitempty"` +} + +// UpgradeGift calls the upgradeGift Telegram Bot API method. +// +// Upgrades a given regular gift to a unique gift. Requires the can_transfer_and_upgrade_gifts business bot right. Additionally requires the can_transfer_stars business bot right if the upgrade is paid. Returns True on success. +func UpgradeGift(ctx context.Context, b *client.Bot, p *UpgradeGiftParams) (bool, error) { + return client.Call[*UpgradeGiftParams, bool](ctx, b, "upgradeGift", p) +} + +// TransferGiftParams is the parameter set for TransferGift. +// +// Transfers an owned unique gift to another user. Requires the can_transfer_and_upgrade_gifts business bot right. Requires can_transfer_stars business bot right if the transfer is paid. Returns True on success. +type TransferGiftParams struct { + // Unique identifier of the business connection + BusinessConnectionID string `json:"business_connection_id"` + // Unique identifier of the regular gift that should be transferred + OwnedGiftID string `json:"owned_gift_id"` + // Unique identifier of the chat which will own the gift. The chat must be active in the last 24 hours. + NewOwnerChatID int64 `json:"new_owner_chat_id"` + // The amount of Telegram Stars that will be paid for the transfer from the business account balance. If positive, then the can_transfer_stars business bot right is required. + StarCount *int64 `json:"star_count,omitempty"` +} + +// TransferGift calls the transferGift Telegram Bot API method. +// +// Transfers an owned unique gift to another user. Requires the can_transfer_and_upgrade_gifts business bot right. Requires can_transfer_stars business bot right if the transfer is paid. Returns True on success. +func TransferGift(ctx context.Context, b *client.Bot, p *TransferGiftParams) (bool, error) { + return client.Call[*TransferGiftParams, bool](ctx, b, "transferGift", p) +} + +// PostStoryParams is the parameter set for PostStory. +// +// Posts a story on behalf of a managed business account. Requires the can_manage_stories business bot right. Returns Story on success. +type PostStoryParams struct { + // Unique identifier of the business connection + BusinessConnectionID string `json:"business_connection_id"` + // Content of the story + Content InputStoryContent `json:"content"` + // Period after which the story is moved to the archive, in seconds; must be one of 6 * 3600, 12 * 3600, 86400, or 2 * 86400 + ActivePeriod int64 `json:"active_period"` + // Caption of the story, 0-2048 characters after entities parsing + Caption string `json:"caption,omitempty"` + // Mode for parsing entities in the story caption. See formatting options for more details. + ParseMode string `json:"parse_mode,omitempty"` + // A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode + CaptionEntities []MessageEntity `json:"caption_entities,omitempty"` + // A JSON-serialized list of clickable areas to be shown on the story + Areas []StoryArea `json:"areas,omitempty"` + // Pass True to keep the story accessible after it expires + PostToChatPage *bool `json:"post_to_chat_page,omitempty"` + // Pass True if the content of the story must be protected from forwarding and screenshotting + ProtectContent *bool `json:"protect_content,omitempty"` +} + +// PostStory calls the postStory Telegram Bot API method. +// +// Posts a story on behalf of a managed business account. Requires the can_manage_stories business bot right. Returns Story on success. +func PostStory(ctx context.Context, b *client.Bot, p *PostStoryParams) (*Story, error) { + return client.Call[*PostStoryParams, *Story](ctx, b, "postStory", p) +} + +// RepostStoryParams is the parameter set for RepostStory. +// +// Reposts a story on behalf of a business account from another business account. Both business accounts must be managed by the same bot, and the story on the source account must have been posted (or reposted) by the bot. Requires the can_manage_stories business bot right for both business accounts. Returns Story on success. +type RepostStoryParams struct { + // Unique identifier of the business connection + BusinessConnectionID string `json:"business_connection_id"` + // Unique identifier of the chat which posted the story that should be reposted + FromChatID int64 `json:"from_chat_id"` + // Unique identifier of the story that should be reposted + FromStoryID int64 `json:"from_story_id"` + // Period after which the story is moved to the archive, in seconds; must be one of 6 * 3600, 12 * 3600, 86400, or 2 * 86400 + ActivePeriod int64 `json:"active_period"` + // Pass True to keep the story accessible after it expires + PostToChatPage *bool `json:"post_to_chat_page,omitempty"` + // Pass True if the content of the story must be protected from forwarding and screenshotting + ProtectContent *bool `json:"protect_content,omitempty"` +} + +// RepostStory calls the repostStory Telegram Bot API method. +// +// Reposts a story on behalf of a business account from another business account. Both business accounts must be managed by the same bot, and the story on the source account must have been posted (or reposted) by the bot. Requires the can_manage_stories business bot right for both business accounts. Returns Story on success. +func RepostStory(ctx context.Context, b *client.Bot, p *RepostStoryParams) (*Story, error) { + return client.Call[*RepostStoryParams, *Story](ctx, b, "repostStory", p) +} + +// EditStoryParams is the parameter set for EditStory. +// +// Edits a story previously posted by the bot on behalf of a managed business account. Requires the can_manage_stories business bot right. Returns Story on success. +type EditStoryParams struct { + // Unique identifier of the business connection + BusinessConnectionID string `json:"business_connection_id"` + // Unique identifier of the story to edit + StoryID int64 `json:"story_id"` + // Content of the story + Content InputStoryContent `json:"content"` + // Caption of the story, 0-2048 characters after entities parsing + Caption string `json:"caption,omitempty"` + // Mode for parsing entities in the story caption. See formatting options for more details. + ParseMode string `json:"parse_mode,omitempty"` + // A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode + CaptionEntities []MessageEntity `json:"caption_entities,omitempty"` + // A JSON-serialized list of clickable areas to be shown on the story + Areas []StoryArea `json:"areas,omitempty"` +} + +// EditStory calls the editStory Telegram Bot API method. +// +// Edits a story previously posted by the bot on behalf of a managed business account. Requires the can_manage_stories business bot right. Returns Story on success. +func EditStory(ctx context.Context, b *client.Bot, p *EditStoryParams) (*Story, error) { + return client.Call[*EditStoryParams, *Story](ctx, b, "editStory", p) +} + +// DeleteStoryParams is the parameter set for DeleteStory. +// +// Deletes a story previously posted by the bot on behalf of a managed business account. Requires the can_manage_stories business bot right. Returns True on success. +type DeleteStoryParams struct { + // Unique identifier of the business connection + BusinessConnectionID string `json:"business_connection_id"` + // Unique identifier of the story to delete + StoryID int64 `json:"story_id"` +} + +// DeleteStory calls the deleteStory Telegram Bot API method. +// +// Deletes a story previously posted by the bot on behalf of a managed business account. Requires the can_manage_stories business bot right. Returns True on success. +func DeleteStory(ctx context.Context, b *client.Bot, p *DeleteStoryParams) (bool, error) { + return client.Call[*DeleteStoryParams, bool](ctx, b, "deleteStory", p) +} + +// AnswerWebAppQueryParams is the parameter set for AnswerWebAppQuery. +// +// Use this method to set the result of an interaction with a Web App and send a corresponding message on behalf of the user to the chat from which the query originated. On success, a SentWebAppMessage object is returned. +type AnswerWebAppQueryParams struct { + // Unique identifier for the query to be answered + WebAppQueryID string `json:"web_app_query_id"` + // A JSON-serialized object describing the message to be sent + Result InlineQueryResult `json:"result"` +} + +// AnswerWebAppQuery calls the answerWebAppQuery Telegram Bot API method. +// +// Use this method to set the result of an interaction with a Web App and send a corresponding message on behalf of the user to the chat from which the query originated. On success, a SentWebAppMessage object is returned. +func AnswerWebAppQuery(ctx context.Context, b *client.Bot, p *AnswerWebAppQueryParams) (*SentWebAppMessage, error) { + return client.Call[*AnswerWebAppQueryParams, *SentWebAppMessage](ctx, b, "answerWebAppQuery", p) +} + +// SavePreparedInlineMessageParams is the parameter set for SavePreparedInlineMessage. +// +// Stores a message that can be sent by a user of a Mini App. Returns a PreparedInlineMessage object. +type SavePreparedInlineMessageParams struct { + // Unique identifier of the target user that can use the prepared message + UserID int64 `json:"user_id"` + // A JSON-serialized object describing the message to be sent + Result InlineQueryResult `json:"result"` + // Pass True if the message can be sent to private chats with users + AllowUserChats *bool `json:"allow_user_chats,omitempty"` + // Pass True if the message can be sent to private chats with bots + AllowBotChats *bool `json:"allow_bot_chats,omitempty"` + // Pass True if the message can be sent to group and supergroup chats + AllowGroupChats *bool `json:"allow_group_chats,omitempty"` + // Pass True if the message can be sent to channel chats + AllowChannelChats *bool `json:"allow_channel_chats,omitempty"` +} + +// SavePreparedInlineMessage calls the savePreparedInlineMessage Telegram Bot API method. +// +// Stores a message that can be sent by a user of a Mini App. Returns a PreparedInlineMessage object. +func SavePreparedInlineMessage(ctx context.Context, b *client.Bot, p *SavePreparedInlineMessageParams) (*PreparedInlineMessage, error) { + return client.Call[*SavePreparedInlineMessageParams, *PreparedInlineMessage](ctx, b, "savePreparedInlineMessage", p) +} + +// SavePreparedKeyboardButtonParams is the parameter set for SavePreparedKeyboardButton. +// +// Stores a keyboard button that can be used by a user within a Mini App. Returns a PreparedKeyboardButton object. +type SavePreparedKeyboardButtonParams struct { + // Unique identifier of the target user that can use the button + UserID int64 `json:"user_id"` + // A JSON-serialized object describing the button to be saved. The button must be of the type request_users, request_chat, or request_managed_bot + Button KeyboardButton `json:"button"` +} + +// SavePreparedKeyboardButton calls the savePreparedKeyboardButton Telegram Bot API method. +// +// Stores a keyboard button that can be used by a user within a Mini App. Returns a PreparedKeyboardButton object. +func SavePreparedKeyboardButton(ctx context.Context, b *client.Bot, p *SavePreparedKeyboardButtonParams) (*PreparedKeyboardButton, error) { + return client.Call[*SavePreparedKeyboardButtonParams, *PreparedKeyboardButton](ctx, b, "savePreparedKeyboardButton", p) +} + +// EditMessageTextParams is the parameter set for EditMessageText. +// +// Use this method to edit text and game messages. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. Note that business messages that were not sent by the bot and do not contain an inline keyboard can only be edited within 48 hours from the time they were sent. +type EditMessageTextParams struct { + // Unique identifier of the business connection on behalf of which the message to be edited was sent + BusinessConnectionID string `json:"business_connection_id,omitempty"` + // Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username. + ChatID *ChatID `json:"chat_id,omitempty"` + // Required if inline_message_id is not specified. Identifier of the message to edit + MessageID *int64 `json:"message_id,omitempty"` + // Required if chat_id and message_id are not specified. Identifier of the inline message + InlineMessageID string `json:"inline_message_id,omitempty"` + // New text of the message, 1-4096 characters after entities parsing + Text string `json:"text"` + // Mode for parsing entities in the message text. See formatting options for more details. + ParseMode string `json:"parse_mode,omitempty"` + // A JSON-serialized list of special entities that appear in message text, which can be specified instead of parse_mode + Entities []MessageEntity `json:"entities,omitempty"` + // Link preview generation options for the message + LinkPreviewOptions *LinkPreviewOptions `json:"link_preview_options,omitempty"` + // A JSON-serialized object for an inline keyboard. + ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"` +} + +// EditMessageText calls the editMessageText Telegram Bot API method. +// +// Use this method to edit text and game messages. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. Note that business messages that were not sent by the bot and do not contain an inline keyboard can only be edited within 48 hours from the time they were sent. +func EditMessageText(ctx context.Context, b *client.Bot, p *EditMessageTextParams) (*MessageOrBool, error) { + return client.Call[*EditMessageTextParams, *MessageOrBool](ctx, b, "editMessageText", p) +} + +// EditMessageCaptionParams is the parameter set for EditMessageCaption. +// +// Use this method to edit captions of messages. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. Note that business messages that were not sent by the bot and do not contain an inline keyboard can only be edited within 48 hours from the time they were sent. +type EditMessageCaptionParams struct { + // Unique identifier of the business connection on behalf of which the message to be edited was sent + BusinessConnectionID string `json:"business_connection_id,omitempty"` + // Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username. + ChatID *ChatID `json:"chat_id,omitempty"` + // Required if inline_message_id is not specified. Identifier of the message to edit + MessageID *int64 `json:"message_id,omitempty"` + // Required if chat_id and message_id are not specified. Identifier of the inline message + InlineMessageID string `json:"inline_message_id,omitempty"` + // New caption of the message, 0-1024 characters after entities parsing + Caption string `json:"caption,omitempty"` + // Mode for parsing entities in the message caption. See formatting options for more details. + ParseMode string `json:"parse_mode,omitempty"` + // A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode + CaptionEntities []MessageEntity `json:"caption_entities,omitempty"` + // Pass True, if the caption must be shown above the message media. Supported only for animation, photo and video messages. + ShowCaptionAboveMedia *bool `json:"show_caption_above_media,omitempty"` + // A JSON-serialized object for an inline keyboard. + ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"` +} + +// EditMessageCaption calls the editMessageCaption Telegram Bot API method. +// +// Use this method to edit captions of messages. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. Note that business messages that were not sent by the bot and do not contain an inline keyboard can only be edited within 48 hours from the time they were sent. +func EditMessageCaption(ctx context.Context, b *client.Bot, p *EditMessageCaptionParams) (*MessageOrBool, error) { + return client.Call[*EditMessageCaptionParams, *MessageOrBool](ctx, b, "editMessageCaption", p) +} + +// EditMessageMediaParams is the parameter set for EditMessageMedia. +// +// Use this method to edit animation, audio, document, live photo, photo, or video messages, or to add media to text messages. If a message is part of a message album, then it can be edited only to an audio for audio albums, only to a document for document albums and to a photo, a live photo, or a video otherwise. When an inline message is edited, a new file can't be uploaded; use a previously uploaded file via its file_id or specify a URL. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. Note that business messages that were not sent by the bot and do not contain an inline keyboard can only be edited within 48 hours from the time they were sent. +type EditMessageMediaParams struct { + // Unique identifier of the business connection on behalf of which the message to be edited was sent + BusinessConnectionID string `json:"business_connection_id,omitempty"` + // Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username. + ChatID *ChatID `json:"chat_id,omitempty"` + // Required if inline_message_id is not specified. Identifier of the message to edit + MessageID *int64 `json:"message_id,omitempty"` + // Required if chat_id and message_id are not specified. Identifier of the inline message + InlineMessageID string `json:"inline_message_id,omitempty"` + // A JSON-serialized object for a new media content of the message + Media InputMedia `json:"media"` + // A JSON-serialized object for a new inline keyboard. + ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"` +} + +// HasFile reports whether a multipart upload is required. +func (p *EditMessageMediaParams) HasFile() bool { + return false +} + +// MultipartFields returns the non-file fields used in the multipart body. +func (p *EditMessageMediaParams) MultipartFields() map[string]string { + out := map[string]string{} + if p.BusinessConnectionID != "" { + out["business_connection_id"] = p.BusinessConnectionID + } + if !p.ChatID.IsZero() { + out["chat_id"] = p.ChatID.String() + } + if p.MessageID != nil { + out["message_id"] = strconv.FormatInt(*p.MessageID, 10) + } + if p.InlineMessageID != "" { + out["inline_message_id"] = p.InlineMessageID + } + if b, _ := json.Marshal(p.Media); len(b) > 0 { + out["media"] = string(b) + } + if p.ReplyMarkup != nil { + if b, _ := json.Marshal(p.ReplyMarkup); len(b) > 0 { + out["reply_markup"] = string(b) + } + } + return out +} + +// MultipartFiles returns the file parts. +func (p *EditMessageMediaParams) MultipartFiles() []client.MultipartFile { + var files []client.MultipartFile + return files +} + +// EditMessageMedia calls the editMessageMedia Telegram Bot API method. +// +// Use this method to edit animation, audio, document, live photo, photo, or video messages, or to add media to text messages. If a message is part of a message album, then it can be edited only to an audio for audio albums, only to a document for document albums and to a photo, a live photo, or a video otherwise. When an inline message is edited, a new file can't be uploaded; use a previously uploaded file via its file_id or specify a URL. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. Note that business messages that were not sent by the bot and do not contain an inline keyboard can only be edited within 48 hours from the time they were sent. +func EditMessageMedia(ctx context.Context, b *client.Bot, p *EditMessageMediaParams) (*MessageOrBool, error) { + return client.Call[*EditMessageMediaParams, *MessageOrBool](ctx, b, "editMessageMedia", p) +} + +// EditMessageLiveLocationParams is the parameter set for EditMessageLiveLocation. +// +// Use this method to edit live location messages. A location can be edited until its live_period expires or editing is explicitly disabled by a call to stopMessageLiveLocation. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. +type EditMessageLiveLocationParams struct { + // Unique identifier of the business connection on behalf of which the message to be edited was sent + BusinessConnectionID string `json:"business_connection_id,omitempty"` + // Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username. + ChatID *ChatID `json:"chat_id,omitempty"` + // Required if inline_message_id is not specified. Identifier of the message to edit + MessageID *int64 `json:"message_id,omitempty"` + // Required if chat_id and message_id are not specified. Identifier of the inline message + InlineMessageID string `json:"inline_message_id,omitempty"` + // Latitude of new location + Latitude float64 `json:"latitude"` + // Longitude of new location + Longitude float64 `json:"longitude"` + // New period in seconds during which the location can be updated, starting from the message send date. If 0x7FFFFFFF is specified, then the location can be updated forever. Otherwise, the new value must not exceed the current live_period by more than a day, and the live location expiration date must remain within the next 90 days. If not specified, then live_period remains unchanged + LivePeriod *int64 `json:"live_period,omitempty"` + // The radius of uncertainty for the location, measured in meters; 0-1500 + HorizontalAccuracy *float64 `json:"horizontal_accuracy,omitempty"` + // Direction in which the user is moving, in degrees. Must be between 1 and 360 if specified. + Heading *int64 `json:"heading,omitempty"` + // The maximum distance for proximity alerts about approaching another chat member, in meters. Must be between 1 and 100000 if specified. + ProximityAlertRadius *int64 `json:"proximity_alert_radius,omitempty"` + // A JSON-serialized object for a new inline keyboard. + ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"` +} + +// EditMessageLiveLocation calls the editMessageLiveLocation Telegram Bot API method. +// +// Use this method to edit live location messages. A location can be edited until its live_period expires or editing is explicitly disabled by a call to stopMessageLiveLocation. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. +func EditMessageLiveLocation(ctx context.Context, b *client.Bot, p *EditMessageLiveLocationParams) (*MessageOrBool, error) { + return client.Call[*EditMessageLiveLocationParams, *MessageOrBool](ctx, b, "editMessageLiveLocation", p) +} + +// StopMessageLiveLocationParams is the parameter set for StopMessageLiveLocation. +// +// Use this method to stop updating a live location message before live_period expires. On success, if the message is not an inline message, the edited Message is returned, otherwise True is returned. +type StopMessageLiveLocationParams struct { + // Unique identifier of the business connection on behalf of which the message to be edited was sent + BusinessConnectionID string `json:"business_connection_id,omitempty"` + // Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username. + ChatID *ChatID `json:"chat_id,omitempty"` + // Required if inline_message_id is not specified. Identifier of the message with live location to stop + MessageID *int64 `json:"message_id,omitempty"` + // Required if chat_id and message_id are not specified. Identifier of the inline message + InlineMessageID string `json:"inline_message_id,omitempty"` + // A JSON-serialized object for a new inline keyboard. + ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"` +} + +// StopMessageLiveLocation calls the stopMessageLiveLocation Telegram Bot API method. +// +// Use this method to stop updating a live location message before live_period expires. On success, if the message is not an inline message, the edited Message is returned, otherwise True is returned. +func StopMessageLiveLocation(ctx context.Context, b *client.Bot, p *StopMessageLiveLocationParams) (*MessageOrBool, error) { + return client.Call[*StopMessageLiveLocationParams, *MessageOrBool](ctx, b, "stopMessageLiveLocation", p) +} + +// EditMessageChecklistParams is the parameter set for EditMessageChecklist. +// +// Use this method to edit a checklist on behalf of a connected business account. On success, the edited Message is returned. +type EditMessageChecklistParams struct { + // Unique identifier of the business connection on behalf of which the message will be sent + BusinessConnectionID string `json:"business_connection_id"` + // Unique identifier for the target chat or username of the target bot in the format @username + ChatID ChatID `json:"chat_id"` + // Unique identifier for the target message + MessageID int64 `json:"message_id"` + // A JSON-serialized object for the new checklist + Checklist InputChecklist `json:"checklist"` + // A JSON-serialized object for the new inline keyboard for the message + ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"` +} + +// EditMessageChecklist calls the editMessageChecklist Telegram Bot API method. +// +// Use this method to edit a checklist on behalf of a connected business account. On success, the edited Message is returned. +func EditMessageChecklist(ctx context.Context, b *client.Bot, p *EditMessageChecklistParams) (*Message, error) { + return client.Call[*EditMessageChecklistParams, *Message](ctx, b, "editMessageChecklist", p) +} + +// EditMessageReplyMarkupParams is the parameter set for EditMessageReplyMarkup. +// +// Use this method to edit only the reply markup of messages. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. Note that business messages that were not sent by the bot and do not contain an inline keyboard can only be edited within 48 hours from the time they were sent. +type EditMessageReplyMarkupParams struct { + // Unique identifier of the business connection on behalf of which the message to be edited was sent + BusinessConnectionID string `json:"business_connection_id,omitempty"` + // Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username. + ChatID *ChatID `json:"chat_id,omitempty"` + // Required if inline_message_id is not specified. Identifier of the message to edit + MessageID *int64 `json:"message_id,omitempty"` + // Required if chat_id and message_id are not specified. Identifier of the inline message + InlineMessageID string `json:"inline_message_id,omitempty"` + // A JSON-serialized object for an inline keyboard. + ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"` +} + +// EditMessageReplyMarkup calls the editMessageReplyMarkup Telegram Bot API method. +// +// Use this method to edit only the reply markup of messages. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. Note that business messages that were not sent by the bot and do not contain an inline keyboard can only be edited within 48 hours from the time they were sent. +func EditMessageReplyMarkup(ctx context.Context, b *client.Bot, p *EditMessageReplyMarkupParams) (*MessageOrBool, error) { + return client.Call[*EditMessageReplyMarkupParams, *MessageOrBool](ctx, b, "editMessageReplyMarkup", p) +} + +// StopPollParams is the parameter set for StopPoll. +// +// Use this method to stop a poll which was sent by the bot. On success, the stopped Poll is returned. +type StopPollParams struct { + // Unique identifier of the business connection on behalf of which the message to be edited was sent + BusinessConnectionID string `json:"business_connection_id,omitempty"` + // Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username + ChatID ChatID `json:"chat_id"` + // Identifier of the original message with the poll + MessageID int64 `json:"message_id"` + // A JSON-serialized object for a new message inline keyboard. + ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"` +} + +// StopPoll calls the stopPoll Telegram Bot API method. +// +// Use this method to stop a poll which was sent by the bot. On success, the stopped Poll is returned. +func StopPoll(ctx context.Context, b *client.Bot, p *StopPollParams) (*Poll, error) { + return client.Call[*StopPollParams, *Poll](ctx, b, "stopPoll", p) +} + +// ApproveSuggestedPostParams is the parameter set for ApproveSuggestedPost. +// +// Use this method to approve a suggested post in a direct messages chat. The bot must have the 'can_post_messages' administrator right in the corresponding channel chat. Returns True on success. +type ApproveSuggestedPostParams struct { + // Unique identifier for the target direct messages chat + ChatID int64 `json:"chat_id"` + // Identifier of a suggested post message to approve + MessageID int64 `json:"message_id"` + // Point in time (Unix timestamp) when the post is expected to be published; omit if the date has already been specified when the suggested post was created. If specified, then the date must be not more than 2678400 seconds (30 days) in the future + SendDate *int64 `json:"send_date,omitempty"` +} + +// ApproveSuggestedPost calls the approveSuggestedPost Telegram Bot API method. +// +// Use this method to approve a suggested post in a direct messages chat. The bot must have the 'can_post_messages' administrator right in the corresponding channel chat. Returns True on success. +func ApproveSuggestedPost(ctx context.Context, b *client.Bot, p *ApproveSuggestedPostParams) (bool, error) { + return client.Call[*ApproveSuggestedPostParams, bool](ctx, b, "approveSuggestedPost", p) +} + +// DeclineSuggestedPostParams is the parameter set for DeclineSuggestedPost. +// +// Use this method to decline a suggested post in a direct messages chat. The bot must have the 'can_manage_direct_messages' administrator right in the corresponding channel chat. Returns True on success. +type DeclineSuggestedPostParams struct { + // Unique identifier for the target direct messages chat + ChatID int64 `json:"chat_id"` + // Identifier of a suggested post message to decline + MessageID int64 `json:"message_id"` + // Comment for the creator of the suggested post; 0-128 characters + Comment string `json:"comment,omitempty"` +} + +// DeclineSuggestedPost calls the declineSuggestedPost Telegram Bot API method. +// +// Use this method to decline a suggested post in a direct messages chat. The bot must have the 'can_manage_direct_messages' administrator right in the corresponding channel chat. Returns True on success. +func DeclineSuggestedPost(ctx context.Context, b *client.Bot, p *DeclineSuggestedPostParams) (bool, error) { + return client.Call[*DeclineSuggestedPostParams, bool](ctx, b, "declineSuggestedPost", p) +} + +// DeleteMessageParams is the parameter set for DeleteMessage. +// +// Use this method to delete a message, including service messages, with the following limitations:- A message can only be deleted if it was sent less than 48 hours ago.- Service messages about a supergroup, channel, or forum topic creation can't be deleted.- A dice message in a private chat can only be deleted if it was sent more than 24 hours ago.- Bots can delete outgoing messages in private chats, groups, and supergroups.- Bots can delete incoming messages in private chats.- Bots granted can_post_messages permissions can delete outgoing messages in channels.- If the bot is an administrator of a group, it can delete any message there.- If the bot has can_delete_messages administrator right in a supergroup or a channel, it can delete any message there.- If the bot has can_manage_direct_messages administrator right in a channel, it can delete any message in the corresponding direct messages chat.Returns True on success. +type DeleteMessageParams struct { + // Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username + ChatID ChatID `json:"chat_id"` + // Identifier of the message to delete + MessageID int64 `json:"message_id"` +} + +// DeleteMessage calls the deleteMessage Telegram Bot API method. +// +// Use this method to delete a message, including service messages, with the following limitations:- A message can only be deleted if it was sent less than 48 hours ago.- Service messages about a supergroup, channel, or forum topic creation can't be deleted.- A dice message in a private chat can only be deleted if it was sent more than 24 hours ago.- Bots can delete outgoing messages in private chats, groups, and supergroups.- Bots can delete incoming messages in private chats.- Bots granted can_post_messages permissions can delete outgoing messages in channels.- If the bot is an administrator of a group, it can delete any message there.- If the bot has can_delete_messages administrator right in a supergroup or a channel, it can delete any message there.- If the bot has can_manage_direct_messages administrator right in a channel, it can delete any message in the corresponding direct messages chat.Returns True on success. +func DeleteMessage(ctx context.Context, b *client.Bot, p *DeleteMessageParams) (bool, error) { + return client.Call[*DeleteMessageParams, bool](ctx, b, "deleteMessage", p) +} + +// DeleteMessagesParams is the parameter set for DeleteMessages. +// +// Use this method to delete multiple messages simultaneously. If some of the specified messages can't be found, they are skipped. Returns True on success. +type DeleteMessagesParams struct { + // Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username + ChatID ChatID `json:"chat_id"` + // A JSON-serialized list of 1-100 identifiers of messages to delete. See deleteMessage for limitations on which messages can be deleted + MessageIds []int64 `json:"message_ids"` +} + +// DeleteMessages calls the deleteMessages Telegram Bot API method. +// +// Use this method to delete multiple messages simultaneously. If some of the specified messages can't be found, they are skipped. Returns True on success. +func DeleteMessages(ctx context.Context, b *client.Bot, p *DeleteMessagesParams) (bool, error) { + return client.Call[*DeleteMessagesParams, bool](ctx, b, "deleteMessages", p) +} + +// DeleteMessageReactionParams is the parameter set for DeleteMessageReaction. +// +// Use this method to remove a reaction from a message in a group or a supergroup chat. The bot must have the 'can_delete_messages' administrator right in the chat. Returns True on success. +type DeleteMessageReactionParams struct { + // Unique identifier for the target chat or username of the target supergroup (in the format @username) + ChatID ChatID `json:"chat_id"` + // Identifier of the target message + MessageID int64 `json:"message_id"` + // Identifier of the user whose reaction will be removed, if the reaction was added by a user + UserID *int64 `json:"user_id,omitempty"` + // Identifier of the chat whose reaction will be removed, if the reaction was added by a chat + ActorChatID *int64 `json:"actor_chat_id,omitempty"` +} + +// DeleteMessageReaction calls the deleteMessageReaction Telegram Bot API method. +// +// Use this method to remove a reaction from a message in a group or a supergroup chat. The bot must have the 'can_delete_messages' administrator right in the chat. Returns True on success. +func DeleteMessageReaction(ctx context.Context, b *client.Bot, p *DeleteMessageReactionParams) (bool, error) { + return client.Call[*DeleteMessageReactionParams, bool](ctx, b, "deleteMessageReaction", p) +} + +// DeleteAllMessageReactionsParams is the parameter set for DeleteAllMessageReactions. +// +// Use this method to remove up to 10000 recent reactions in a group or a supergroup chat added by a given user or chat. The bot must have the 'can_delete_messages' administrator right in the chat. Returns True on success. +type DeleteAllMessageReactionsParams struct { + // Unique identifier for the target chat or username of the target supergroup (in the format @username) + ChatID ChatID `json:"chat_id"` + // Identifier of the user whose reactions will be removed, if the reactions were added by a user + UserID *int64 `json:"user_id,omitempty"` + // Identifier of the chat whose reactions will be removed, if the reactions were added by a chat + ActorChatID *int64 `json:"actor_chat_id,omitempty"` +} + +// DeleteAllMessageReactions calls the deleteAllMessageReactions Telegram Bot API method. +// +// Use this method to remove up to 10000 recent reactions in a group or a supergroup chat added by a given user or chat. The bot must have the 'can_delete_messages' administrator right in the chat. Returns True on success. +func DeleteAllMessageReactions(ctx context.Context, b *client.Bot, p *DeleteAllMessageReactionsParams) (bool, error) { + return client.Call[*DeleteAllMessageReactionsParams, bool](ctx, b, "deleteAllMessageReactions", p) +} + +// SendStickerParams is the parameter set for SendSticker. +// +// Use this method to send static .WEBP, animated .TGS, or video .WEBM stickers. On success, the sent Message is returned. +type SendStickerParams struct { + // Unique identifier of the business connection on behalf of which the message will be sent + BusinessConnectionID string `json:"business_connection_id,omitempty"` + // Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username + ChatID ChatID `json:"chat_id"` + // Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only + MessageThreadID *int64 `json:"message_thread_id,omitempty"` + // Identifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat + DirectMessagesTopicID *int64 `json:"direct_messages_topic_id,omitempty"` + // Sticker to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a .WEBP sticker from the Internet, or upload a new .WEBP, .TGS, or .WEBM sticker using multipart/form-data. More information on Sending Files ». Video and animated stickers can't be sent via an HTTP URL. + Sticker *InputFile `json:"sticker"` + // Emoji associated with the sticker; only for just uploaded stickers + Emoji string `json:"emoji,omitempty"` + // Sends the message silently. Users will receive a notification with no sound. + DisableNotification *bool `json:"disable_notification,omitempty"` + // Protects the contents of the sent message from forwarding and saving + ProtectContent *bool `json:"protect_content,omitempty"` + // Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance. + AllowPaidBroadcast *bool `json:"allow_paid_broadcast,omitempty"` + // Unique identifier of the message effect to be added to the message; for private chats only + MessageEffectID string `json:"message_effect_id,omitempty"` + // A JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined. + SuggestedPostParameters *SuggestedPostParameters `json:"suggested_post_parameters,omitempty"` + // Description of the message to reply to + ReplyParameters *ReplyParameters `json:"reply_parameters,omitempty"` + // Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user + ReplyMarkup any `json:"reply_markup,omitempty"` +} + +// HasFile reports whether a multipart upload is required. +func (p *SendStickerParams) HasFile() bool { + if p.Sticker != nil && p.Sticker.IsLocalUpload() { + return true + } + return false +} + +// MultipartFields returns the non-file fields used in the multipart body. +func (p *SendStickerParams) MultipartFields() map[string]string { + out := map[string]string{} + if p.BusinessConnectionID != "" { + out["business_connection_id"] = p.BusinessConnectionID + } + out["chat_id"] = p.ChatID.String() + if p.MessageThreadID != nil { + out["message_thread_id"] = strconv.FormatInt(*p.MessageThreadID, 10) + } + if p.DirectMessagesTopicID != nil { + out["direct_messages_topic_id"] = strconv.FormatInt(*p.DirectMessagesTopicID, 10) + } + if p.Emoji != "" { + out["emoji"] = p.Emoji + } + if p.DisableNotification != nil { + out["disable_notification"] = strconv.FormatBool(*p.DisableNotification) + } + if p.ProtectContent != nil { + out["protect_content"] = strconv.FormatBool(*p.ProtectContent) + } + if p.AllowPaidBroadcast != nil { + out["allow_paid_broadcast"] = strconv.FormatBool(*p.AllowPaidBroadcast) + } + if p.MessageEffectID != "" { + out["message_effect_id"] = p.MessageEffectID + } + if p.SuggestedPostParameters != nil { + if b, _ := json.Marshal(p.SuggestedPostParameters); len(b) > 0 { + out["suggested_post_parameters"] = string(b) + } + } + if p.ReplyParameters != nil { + if b, _ := json.Marshal(p.ReplyParameters); len(b) > 0 { + out["reply_parameters"] = string(b) + } + } + if p.ReplyMarkup != nil { + if b, _ := json.Marshal(p.ReplyMarkup); len(b) > 0 && string(b) != "null" { + out["reply_markup"] = string(b) + } + } + return out +} + +// MultipartFiles returns the file parts. +func (p *SendStickerParams) MultipartFiles() []client.MultipartFile { + var files []client.MultipartFile + if p.Sticker != nil && p.Sticker.IsLocalUpload() { + name := p.Sticker.Filename + if name == "" { + name = "sticker" + } + files = append(files, client.MultipartFile{FieldName: "sticker", Filename: name, Reader: p.Sticker.Reader}) + } + return files +} + +// SendSticker calls the sendSticker Telegram Bot API method. +// +// Use this method to send static .WEBP, animated .TGS, or video .WEBM stickers. On success, the sent Message is returned. +func SendSticker(ctx context.Context, b *client.Bot, p *SendStickerParams) (*Message, error) { + return client.Call[*SendStickerParams, *Message](ctx, b, "sendSticker", p) +} + +// GetStickerSetParams is the parameter set for GetStickerSet. +// +// Use this method to get a sticker set. On success, a StickerSet object is returned. +type GetStickerSetParams struct { + // Name of the sticker set + Name string `json:"name"` +} + +// GetStickerSet calls the getStickerSet Telegram Bot API method. +// +// Use this method to get a sticker set. On success, a StickerSet object is returned. +func GetStickerSet(ctx context.Context, b *client.Bot, p *GetStickerSetParams) (*StickerSet, error) { + return client.Call[*GetStickerSetParams, *StickerSet](ctx, b, "getStickerSet", p) +} + +// GetCustomEmojiStickersParams is the parameter set for GetCustomEmojiStickers. +// +// Use this method to get information about custom emoji stickers by their identifiers. Returns an Array of Sticker objects. +type GetCustomEmojiStickersParams struct { + // A JSON-serialized list of custom emoji identifiers. At most 200 custom emoji identifiers can be specified. + CustomEmojiIds []string `json:"custom_emoji_ids"` +} + +// GetCustomEmojiStickers calls the getCustomEmojiStickers Telegram Bot API method. +// +// Use this method to get information about custom emoji stickers by their identifiers. Returns an Array of Sticker objects. +func GetCustomEmojiStickers(ctx context.Context, b *client.Bot, p *GetCustomEmojiStickersParams) ([]Sticker, error) { + return client.Call[*GetCustomEmojiStickersParams, []Sticker](ctx, b, "getCustomEmojiStickers", p) +} + +// UploadStickerFileParams is the parameter set for UploadStickerFile. +// +// Use this method to upload a file with a sticker for later use in the createNewStickerSet, addStickerToSet, or replaceStickerInSet methods (the file can be used multiple times). Returns the uploaded File on success. +type UploadStickerFileParams struct { + // User identifier of sticker file owner + UserID int64 `json:"user_id"` + // A file with the sticker in .WEBP, .PNG, .TGS, or .WEBM format. See https://core.telegram.org/stickers for technical requirements. More information on Sending Files » + Sticker *InputFile `json:"sticker"` + // Format of the sticker, must be one of “static”, “animated”, “video” + StickerFormat string `json:"sticker_format"` +} + +// HasFile reports whether a multipart upload is required. +func (p *UploadStickerFileParams) HasFile() bool { + if p.Sticker != nil && p.Sticker.IsLocalUpload() { + return true + } + return false +} + +// MultipartFields returns the non-file fields used in the multipart body. +func (p *UploadStickerFileParams) MultipartFields() map[string]string { + out := map[string]string{} + out["user_id"] = strconv.FormatInt(p.UserID, 10) + out["sticker_format"] = p.StickerFormat + return out +} + +// MultipartFiles returns the file parts. +func (p *UploadStickerFileParams) MultipartFiles() []client.MultipartFile { + var files []client.MultipartFile + if p.Sticker != nil && p.Sticker.IsLocalUpload() { + name := p.Sticker.Filename + if name == "" { + name = "sticker" + } + files = append(files, client.MultipartFile{FieldName: "sticker", Filename: name, Reader: p.Sticker.Reader}) + } + return files +} + +// UploadStickerFile calls the uploadStickerFile Telegram Bot API method. +// +// Use this method to upload a file with a sticker for later use in the createNewStickerSet, addStickerToSet, or replaceStickerInSet methods (the file can be used multiple times). Returns the uploaded File on success. +func UploadStickerFile(ctx context.Context, b *client.Bot, p *UploadStickerFileParams) (*File, error) { + return client.Call[*UploadStickerFileParams, *File](ctx, b, "uploadStickerFile", p) +} + +// CreateNewStickerSetParams is the parameter set for CreateNewStickerSet. +// +// Use this method to create a new sticker set owned by a user. The bot will be able to edit the sticker set thus created. Returns True on success. +type CreateNewStickerSetParams struct { + // User identifier of created sticker set owner + UserID int64 `json:"user_id"` + // Short name of sticker set, to be used in t.me/addstickers/ URLs (e.g., animals). Can contain only English letters, digits and underscores. Must begin with a letter, can't contain consecutive underscores and must end in "_by_". is case insensitive. 1-64 characters. + Name string `json:"name"` + // Sticker set title, 1-64 characters + Title string `json:"title"` + // A JSON-serialized list of 1-50 initial stickers to be added to the sticker set + Stickers []InputSticker `json:"stickers"` + // Type of stickers in the set, pass “regular”, “mask”, or “custom_emoji”. By default, a regular sticker set is created. + StickerType string `json:"sticker_type,omitempty"` + // Pass True if stickers in the sticker set must be repainted to the color of text when used in messages, the accent color if used as emoji status, white on chat photos, or another appropriate color based on context; for custom emoji sticker sets only + NeedsRepainting *bool `json:"needs_repainting,omitempty"` +} + +// CreateNewStickerSet calls the createNewStickerSet Telegram Bot API method. +// +// Use this method to create a new sticker set owned by a user. The bot will be able to edit the sticker set thus created. Returns True on success. +func CreateNewStickerSet(ctx context.Context, b *client.Bot, p *CreateNewStickerSetParams) (bool, error) { + return client.Call[*CreateNewStickerSetParams, bool](ctx, b, "createNewStickerSet", p) +} + +// AddStickerToSetParams is the parameter set for AddStickerToSet. +// +// Use this method to add a new sticker to a set created by the bot. Emoji sticker sets can have up to 200 stickers. Other sticker sets can have up to 120 stickers. Returns True on success. +type AddStickerToSetParams struct { + // User identifier of sticker set owner + UserID int64 `json:"user_id"` + // Sticker set name + Name string `json:"name"` + // A JSON-serialized object with information about the added sticker. If exactly the same sticker had already been added to the set, then the set isn't changed. + Sticker InputSticker `json:"sticker"` +} + +// AddStickerToSet calls the addStickerToSet Telegram Bot API method. +// +// Use this method to add a new sticker to a set created by the bot. Emoji sticker sets can have up to 200 stickers. Other sticker sets can have up to 120 stickers. Returns True on success. +func AddStickerToSet(ctx context.Context, b *client.Bot, p *AddStickerToSetParams) (bool, error) { + return client.Call[*AddStickerToSetParams, bool](ctx, b, "addStickerToSet", p) +} + +// SetStickerPositionInSetParams is the parameter set for SetStickerPositionInSet. +// +// Use this method to move a sticker in a set created by the bot to a specific position. Returns True on success. +type SetStickerPositionInSetParams struct { + // File identifier of the sticker + Sticker string `json:"sticker"` + // New sticker position in the set, zero-based + Position int64 `json:"position"` +} + +// SetStickerPositionInSet calls the setStickerPositionInSet Telegram Bot API method. +// +// Use this method to move a sticker in a set created by the bot to a specific position. Returns True on success. +func SetStickerPositionInSet(ctx context.Context, b *client.Bot, p *SetStickerPositionInSetParams) (bool, error) { + return client.Call[*SetStickerPositionInSetParams, bool](ctx, b, "setStickerPositionInSet", p) +} + +// DeleteStickerFromSetParams is the parameter set for DeleteStickerFromSet. +// +// Use this method to delete a sticker from a set created by the bot. Returns True on success. +type DeleteStickerFromSetParams struct { + // File identifier of the sticker + Sticker string `json:"sticker"` +} + +// DeleteStickerFromSet calls the deleteStickerFromSet Telegram Bot API method. +// +// Use this method to delete a sticker from a set created by the bot. Returns True on success. +func DeleteStickerFromSet(ctx context.Context, b *client.Bot, p *DeleteStickerFromSetParams) (bool, error) { + return client.Call[*DeleteStickerFromSetParams, bool](ctx, b, "deleteStickerFromSet", p) +} + +// ReplaceStickerInSetParams is the parameter set for ReplaceStickerInSet. +// +// Use this method to replace an existing sticker in a sticker set with a new one. The method is equivalent to calling deleteStickerFromSet, then addStickerToSet, then setStickerPositionInSet. Returns True on success. +type ReplaceStickerInSetParams struct { + // User identifier of the sticker set owner + UserID int64 `json:"user_id"` + // Sticker set name + Name string `json:"name"` + // File identifier of the replaced sticker + OldSticker string `json:"old_sticker"` + // A JSON-serialized object with information about the added sticker. If exactly the same sticker had already been added to the set, then the set remains unchanged. + Sticker InputSticker `json:"sticker"` +} + +// ReplaceStickerInSet calls the replaceStickerInSet Telegram Bot API method. +// +// Use this method to replace an existing sticker in a sticker set with a new one. The method is equivalent to calling deleteStickerFromSet, then addStickerToSet, then setStickerPositionInSet. Returns True on success. +func ReplaceStickerInSet(ctx context.Context, b *client.Bot, p *ReplaceStickerInSetParams) (bool, error) { + return client.Call[*ReplaceStickerInSetParams, bool](ctx, b, "replaceStickerInSet", p) +} + +// SetStickerEmojiListParams is the parameter set for SetStickerEmojiList. +// +// Use this method to change the list of emoji assigned to a regular or custom emoji sticker. The sticker must belong to a sticker set created by the bot. Returns True on success. +type SetStickerEmojiListParams struct { + // File identifier of the sticker + Sticker string `json:"sticker"` + // A JSON-serialized list of 1-20 emoji associated with the sticker + EmojiList []string `json:"emoji_list"` +} + +// SetStickerEmojiList calls the setStickerEmojiList Telegram Bot API method. +// +// Use this method to change the list of emoji assigned to a regular or custom emoji sticker. The sticker must belong to a sticker set created by the bot. Returns True on success. +func SetStickerEmojiList(ctx context.Context, b *client.Bot, p *SetStickerEmojiListParams) (bool, error) { + return client.Call[*SetStickerEmojiListParams, bool](ctx, b, "setStickerEmojiList", p) +} + +// SetStickerKeywordsParams is the parameter set for SetStickerKeywords. +// +// Use this method to change search keywords assigned to a regular or custom emoji sticker. The sticker must belong to a sticker set created by the bot. Returns True on success. +type SetStickerKeywordsParams struct { + // File identifier of the sticker + Sticker string `json:"sticker"` + // A JSON-serialized list of 0-20 search keywords for the sticker with total length of up to 64 characters + Keywords []string `json:"keywords,omitempty"` +} + +// SetStickerKeywords calls the setStickerKeywords Telegram Bot API method. +// +// Use this method to change search keywords assigned to a regular or custom emoji sticker. The sticker must belong to a sticker set created by the bot. Returns True on success. +func SetStickerKeywords(ctx context.Context, b *client.Bot, p *SetStickerKeywordsParams) (bool, error) { + return client.Call[*SetStickerKeywordsParams, bool](ctx, b, "setStickerKeywords", p) +} + +// SetStickerMaskPositionParams is the parameter set for SetStickerMaskPosition. +// +// Use this method to change the mask position of a mask sticker. The sticker must belong to a sticker set that was created by the bot. Returns True on success. +type SetStickerMaskPositionParams struct { + // File identifier of the sticker + Sticker string `json:"sticker"` + // A JSON-serialized object with the position where the mask should be placed on faces. Omit the parameter to remove the mask position. + MaskPosition *MaskPosition `json:"mask_position,omitempty"` +} + +// SetStickerMaskPosition calls the setStickerMaskPosition Telegram Bot API method. +// +// Use this method to change the mask position of a mask sticker. The sticker must belong to a sticker set that was created by the bot. Returns True on success. +func SetStickerMaskPosition(ctx context.Context, b *client.Bot, p *SetStickerMaskPositionParams) (bool, error) { + return client.Call[*SetStickerMaskPositionParams, bool](ctx, b, "setStickerMaskPosition", p) +} + +// SetStickerSetTitleParams is the parameter set for SetStickerSetTitle. +// +// Use this method to set the title of a created sticker set. Returns True on success. +type SetStickerSetTitleParams struct { + // Sticker set name + Name string `json:"name"` + // Sticker set title, 1-64 characters + Title string `json:"title"` +} + +// SetStickerSetTitle calls the setStickerSetTitle Telegram Bot API method. +// +// Use this method to set the title of a created sticker set. Returns True on success. +func SetStickerSetTitle(ctx context.Context, b *client.Bot, p *SetStickerSetTitleParams) (bool, error) { + return client.Call[*SetStickerSetTitleParams, bool](ctx, b, "setStickerSetTitle", p) +} + +// SetStickerSetThumbnailParams is the parameter set for SetStickerSetThumbnail. +// +// Use this method to set the thumbnail of a regular or mask sticker set. The format of the thumbnail file must match the format of the stickers in the set. Returns True on success. +type SetStickerSetThumbnailParams struct { + // Sticker set name + Name string `json:"name"` + // User identifier of the sticker set owner + UserID int64 `json:"user_id"` + // A .WEBP or .PNG image with the thumbnail, must be up to 128 kilobytes in size and have a width and height of exactly 100px, or a .TGS animation with a thumbnail up to 32 kilobytes in size (see https://core.telegram.org/stickers#animation-requirements for animated sticker technical requirements), or a .WEBM video with the thumbnail up to 32 kilobytes in size; see https://core.telegram.org/stickers#video-requirements for video sticker technical requirements. Pass a file_id as a String to send a file that already exists on the Telegram servers, pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files ». Animated and video sticker set thumbnails can't be uploaded via HTTP URL. If omitted, then the thumbnail is dropped and the first sticker is used as the thumbnail. + Thumbnail *InputFile `json:"thumbnail,omitempty"` + // Format of the thumbnail, must be one of “static” for a .WEBP or .PNG image, “animated” for a .TGS animation, or “video” for a .WEBM video + Format string `json:"format"` +} + +// HasFile reports whether a multipart upload is required. +func (p *SetStickerSetThumbnailParams) HasFile() bool { + if p.Thumbnail != nil && p.Thumbnail.IsLocalUpload() { + return true + } + return false +} + +// MultipartFields returns the non-file fields used in the multipart body. +func (p *SetStickerSetThumbnailParams) MultipartFields() map[string]string { + out := map[string]string{} + out["name"] = p.Name + out["user_id"] = strconv.FormatInt(p.UserID, 10) + out["format"] = p.Format + return out +} + +// MultipartFiles returns the file parts. +func (p *SetStickerSetThumbnailParams) MultipartFiles() []client.MultipartFile { + var files []client.MultipartFile + if p.Thumbnail != nil && p.Thumbnail.IsLocalUpload() { + name := p.Thumbnail.Filename + if name == "" { + name = "thumbnail" + } + files = append(files, client.MultipartFile{FieldName: "thumbnail", Filename: name, Reader: p.Thumbnail.Reader}) + } + return files +} + +// SetStickerSetThumbnail calls the setStickerSetThumbnail Telegram Bot API method. +// +// Use this method to set the thumbnail of a regular or mask sticker set. The format of the thumbnail file must match the format of the stickers in the set. Returns True on success. +func SetStickerSetThumbnail(ctx context.Context, b *client.Bot, p *SetStickerSetThumbnailParams) (bool, error) { + return client.Call[*SetStickerSetThumbnailParams, bool](ctx, b, "setStickerSetThumbnail", p) +} + +// SetCustomEmojiStickerSetThumbnailParams is the parameter set for SetCustomEmojiStickerSetThumbnail. +// +// Use this method to set the thumbnail of a custom emoji sticker set. Returns True on success. +type SetCustomEmojiStickerSetThumbnailParams struct { + // Sticker set name + Name string `json:"name"` + // Custom emoji identifier of a sticker from the sticker set; pass an empty string to drop the thumbnail and use the first sticker as the thumbnail. + CustomEmojiID string `json:"custom_emoji_id,omitempty"` +} + +// SetCustomEmojiStickerSetThumbnail calls the setCustomEmojiStickerSetThumbnail Telegram Bot API method. +// +// Use this method to set the thumbnail of a custom emoji sticker set. Returns True on success. +func SetCustomEmojiStickerSetThumbnail(ctx context.Context, b *client.Bot, p *SetCustomEmojiStickerSetThumbnailParams) (bool, error) { + return client.Call[*SetCustomEmojiStickerSetThumbnailParams, bool](ctx, b, "setCustomEmojiStickerSetThumbnail", p) +} + +// DeleteStickerSetParams is the parameter set for DeleteStickerSet. +// +// Use this method to delete a sticker set that was created by the bot. Returns True on success. +type DeleteStickerSetParams struct { + // Sticker set name + Name string `json:"name"` +} + +// DeleteStickerSet calls the deleteStickerSet Telegram Bot API method. +// +// Use this method to delete a sticker set that was created by the bot. Returns True on success. +func DeleteStickerSet(ctx context.Context, b *client.Bot, p *DeleteStickerSetParams) (bool, error) { + return client.Call[*DeleteStickerSetParams, bool](ctx, b, "deleteStickerSet", p) +} + +// AnswerInlineQueryParams is the parameter set for AnswerInlineQuery. +// +// Use this method to send answers to an inline query. On success, True is returned.No more than 50 results per query are allowed. +type AnswerInlineQueryParams struct { + // Unique identifier for the answered query + InlineQueryID string `json:"inline_query_id"` + // A JSON-serialized array of results for the inline query + Results []InlineQueryResult `json:"results"` + // The maximum amount of time in seconds that the result of the inline query may be cached on the server. Defaults to 300. + CacheTime *int64 `json:"cache_time,omitempty"` + // Pass True if results may be cached on the server side only for the user that sent the query. By default, results may be returned to any user who sends the same query. + IsPersonal *bool `json:"is_personal,omitempty"` + // Pass the offset that a client should send in the next query with the same text to receive more results. Pass an empty string if there are no more results or if you don't support pagination. Offset length can't exceed 64 bytes. + NextOffset string `json:"next_offset,omitempty"` + // A JSON-serialized object describing a button to be shown above inline query results + Button *InlineQueryResultsButton `json:"button,omitempty"` +} + +// AnswerInlineQuery calls the answerInlineQuery Telegram Bot API method. +// +// Use this method to send answers to an inline query. On success, True is returned.No more than 50 results per query are allowed. +func AnswerInlineQuery(ctx context.Context, b *client.Bot, p *AnswerInlineQueryParams) (bool, error) { + return client.Call[*AnswerInlineQueryParams, bool](ctx, b, "answerInlineQuery", p) +} + +// SendInvoiceParams is the parameter set for SendInvoice. +// +// Use this method to send invoices. On success, the sent Message is returned. +type SendInvoiceParams struct { + // Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username + ChatID ChatID `json:"chat_id"` + // Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only + MessageThreadID *int64 `json:"message_thread_id,omitempty"` + // Identifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat + DirectMessagesTopicID *int64 `json:"direct_messages_topic_id,omitempty"` + // Product name, 1-32 characters + Title string `json:"title"` + // Product description, 1-255 characters + Description string `json:"description"` + // Bot-defined invoice payload, 1-128 bytes. This will not be displayed to the user, use it for your internal processes. + Payload string `json:"payload"` + // Payment provider token, obtained via @BotFather. Pass an empty string for payments in Telegram Stars. + ProviderToken string `json:"provider_token,omitempty"` + // Three-letter ISO 4217 currency code, see more on currencies. Pass “XTR” for payments in Telegram Stars. + Currency string `json:"currency"` + // Price breakdown, a JSON-serialized list of components (e.g. product price, tax, discount, delivery cost, delivery tax, bonus, etc.). Must contain exactly one item for payments in Telegram Stars. + Prices []LabeledPrice `json:"prices"` + // The maximum accepted amount for tips in the smallest units of the currency (integer, not float/double). For example, for a maximum tip of US$ 1.45 pass max_tip_amount = 145. See the exp parameter in currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies). Defaults to 0. Not supported for payments in Telegram Stars. + MaxTipAmount *int64 `json:"max_tip_amount,omitempty"` + // A JSON-serialized array of suggested amounts of tips in the smallest units of the currency (integer, not float/double). At most 4 suggested tip amounts can be specified. The suggested tip amounts must be positive, passed in a strictly increased order and must not exceed max_tip_amount. + SuggestedTipAmounts []int64 `json:"suggested_tip_amounts,omitempty"` + // Unique deep-linking parameter. If left empty, forwarded copies of the sent message will have a Pay button, allowing multiple users to pay directly from the forwarded message, using the same invoice. If non-empty, forwarded copies of the sent message will have a URL button with a deep link to the bot (instead of a Pay button), with the value used as the start parameter + StartParameter string `json:"start_parameter,omitempty"` + // JSON-serialized data about the invoice, which will be shared with the payment provider. A detailed description of required fields should be provided by the payment provider. + ProviderData string `json:"provider_data,omitempty"` + // URL of the product photo for the invoice. Can be a photo of the goods or a marketing image for a service. People like it better when they see what they are paying for. + PhotoURL string `json:"photo_url,omitempty"` + // Photo size in bytes + PhotoSize *int64 `json:"photo_size,omitempty"` + // Photo width + PhotoWidth *int64 `json:"photo_width,omitempty"` + // Photo height + PhotoHeight *int64 `json:"photo_height,omitempty"` + // Pass True if you require the user's full name to complete the order. Ignored for payments in Telegram Stars. + NeedName *bool `json:"need_name,omitempty"` + // Pass True if you require the user's phone number to complete the order. Ignored for payments in Telegram Stars. + NeedPhoneNumber *bool `json:"need_phone_number,omitempty"` + // Pass True if you require the user's email address to complete the order. Ignored for payments in Telegram Stars. + NeedEmail *bool `json:"need_email,omitempty"` + // Pass True if you require the user's shipping address to complete the order. Ignored for payments in Telegram Stars. + NeedShippingAddress *bool `json:"need_shipping_address,omitempty"` + // Pass True if the user's phone number should be sent to the provider. Ignored for payments in Telegram Stars. + SendPhoneNumberToProvider *bool `json:"send_phone_number_to_provider,omitempty"` + // Pass True if the user's email address should be sent to the provider. Ignored for payments in Telegram Stars. + SendEmailToProvider *bool `json:"send_email_to_provider,omitempty"` + // Pass True if the final price depends on the shipping method. Ignored for payments in Telegram Stars. + IsFlexible *bool `json:"is_flexible,omitempty"` + // Sends the message silently. Users will receive a notification with no sound. + DisableNotification *bool `json:"disable_notification,omitempty"` + // Protects the contents of the sent message from forwarding and saving + ProtectContent *bool `json:"protect_content,omitempty"` + // Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance. + AllowPaidBroadcast *bool `json:"allow_paid_broadcast,omitempty"` + // Unique identifier of the message effect to be added to the message; for private chats only + MessageEffectID string `json:"message_effect_id,omitempty"` + // A JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined. + SuggestedPostParameters *SuggestedPostParameters `json:"suggested_post_parameters,omitempty"` + // Description of the message to reply to + ReplyParameters *ReplyParameters `json:"reply_parameters,omitempty"` + // A JSON-serialized object for an inline keyboard. If empty, one 'Pay total price' button will be shown. If not empty, the first button must be a Pay button. + ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"` +} + +// SendInvoice calls the sendInvoice Telegram Bot API method. +// +// Use this method to send invoices. On success, the sent Message is returned. +func SendInvoice(ctx context.Context, b *client.Bot, p *SendInvoiceParams) (*Message, error) { + return client.Call[*SendInvoiceParams, *Message](ctx, b, "sendInvoice", p) +} + +// CreateInvoiceLinkParams is the parameter set for CreateInvoiceLink. +// +// Use this method to create a link for an invoice. Returns the created invoice link as String on success. +type CreateInvoiceLinkParams struct { + // Unique identifier of the business connection on behalf of which the link will be created. For payments in Telegram Stars only. + BusinessConnectionID string `json:"business_connection_id,omitempty"` + // Product name, 1-32 characters + Title string `json:"title"` + // Product description, 1-255 characters + Description string `json:"description"` + // Bot-defined invoice payload, 1-128 bytes. This will not be displayed to the user, use it for your internal processes. + Payload string `json:"payload"` + // Payment provider token, obtained via @BotFather. Pass an empty string for payments in Telegram Stars. + ProviderToken string `json:"provider_token,omitempty"` + // Three-letter ISO 4217 currency code, see more on currencies. Pass “XTR” for payments in Telegram Stars. + Currency string `json:"currency"` + // Price breakdown, a JSON-serialized list of components (e.g. product price, tax, discount, delivery cost, delivery tax, bonus, etc.). Must contain exactly one item for payments in Telegram Stars. + Prices []LabeledPrice `json:"prices"` + // The number of seconds the subscription will be active for before the next payment. The currency must be set to “XTR” (Telegram Stars) if the parameter is used. Currently, it must always be 2592000 (30 days) if specified. Any number of subscriptions can be active for a given bot at the same time, including multiple concurrent subscriptions from the same user. Subscription price must no exceed 10000 Telegram Stars. + SubscriptionPeriod *int64 `json:"subscription_period,omitempty"` + // The maximum accepted amount for tips in the smallest units of the currency (integer, not float/double). For example, for a maximum tip of US$ 1.45 pass max_tip_amount = 145. See the exp parameter in currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies). Defaults to 0. Not supported for payments in Telegram Stars. + MaxTipAmount *int64 `json:"max_tip_amount,omitempty"` + // A JSON-serialized array of suggested amounts of tips in the smallest units of the currency (integer, not float/double). At most 4 suggested tip amounts can be specified. The suggested tip amounts must be positive, passed in a strictly increased order and must not exceed max_tip_amount. + SuggestedTipAmounts []int64 `json:"suggested_tip_amounts,omitempty"` + // JSON-serialized data about the invoice, which will be shared with the payment provider. A detailed description of required fields should be provided by the payment provider. + ProviderData string `json:"provider_data,omitempty"` + // URL of the product photo for the invoice. Can be a photo of the goods or a marketing image for a service. + PhotoURL string `json:"photo_url,omitempty"` + // Photo size in bytes + PhotoSize *int64 `json:"photo_size,omitempty"` + // Photo width + PhotoWidth *int64 `json:"photo_width,omitempty"` + // Photo height + PhotoHeight *int64 `json:"photo_height,omitempty"` + // Pass True if you require the user's full name to complete the order. Ignored for payments in Telegram Stars. + NeedName *bool `json:"need_name,omitempty"` + // Pass True if you require the user's phone number to complete the order. Ignored for payments in Telegram Stars. + NeedPhoneNumber *bool `json:"need_phone_number,omitempty"` + // Pass True if you require the user's email address to complete the order. Ignored for payments in Telegram Stars. + NeedEmail *bool `json:"need_email,omitempty"` + // Pass True if you require the user's shipping address to complete the order. Ignored for payments in Telegram Stars. + NeedShippingAddress *bool `json:"need_shipping_address,omitempty"` + // Pass True if the user's phone number should be sent to the provider. Ignored for payments in Telegram Stars. + SendPhoneNumberToProvider *bool `json:"send_phone_number_to_provider,omitempty"` + // Pass True if the user's email address should be sent to the provider. Ignored for payments in Telegram Stars. + SendEmailToProvider *bool `json:"send_email_to_provider,omitempty"` + // Pass True if the final price depends on the shipping method. Ignored for payments in Telegram Stars. + IsFlexible *bool `json:"is_flexible,omitempty"` +} + +// CreateInvoiceLink calls the createInvoiceLink Telegram Bot API method. +// +// Use this method to create a link for an invoice. Returns the created invoice link as String on success. +func CreateInvoiceLink(ctx context.Context, b *client.Bot, p *CreateInvoiceLinkParams) (string, error) { + return client.Call[*CreateInvoiceLinkParams, string](ctx, b, "createInvoiceLink", p) +} + +// AnswerShippingQueryParams is the parameter set for AnswerShippingQuery. +// +// If you sent an invoice requesting a shipping address and the parameter is_flexible was specified, the Bot API will send an Update with a shipping_query field to the bot. Use this method to reply to shipping queries. On success, True is returned. +type AnswerShippingQueryParams struct { + // Unique identifier for the query to be answered + ShippingQueryID string `json:"shipping_query_id"` + // Pass True if delivery to the specified address is possible and False if there are any problems (for example, if delivery to the specified address is not possible) + Ok bool `json:"ok"` + // Required if ok is True. A JSON-serialized array of available shipping options. + ShippingOptions []ShippingOption `json:"shipping_options,omitempty"` + // Required if ok is False. Error message in human readable form that explains why it is impossible to complete the order (e.g. “Sorry, delivery to your desired address is unavailable”). Telegram will display this message to the user. + ErrorMessage string `json:"error_message,omitempty"` +} + +// AnswerShippingQuery calls the answerShippingQuery Telegram Bot API method. +// +// If you sent an invoice requesting a shipping address and the parameter is_flexible was specified, the Bot API will send an Update with a shipping_query field to the bot. Use this method to reply to shipping queries. On success, True is returned. +func AnswerShippingQuery(ctx context.Context, b *client.Bot, p *AnswerShippingQueryParams) (bool, error) { + return client.Call[*AnswerShippingQueryParams, bool](ctx, b, "answerShippingQuery", p) +} + +// AnswerPreCheckoutQueryParams is the parameter set for AnswerPreCheckoutQuery. +// +// Once the user has confirmed their payment and shipping details, the Bot API sends the final confirmation in the form of an Update with the field pre_checkout_query. Use this method to respond to such pre-checkout queries. On success, True is returned. Note: The Bot API must receive an answer within 10 seconds after the pre-checkout query was sent. +type AnswerPreCheckoutQueryParams struct { + // Unique identifier for the query to be answered + PreCheckoutQueryID string `json:"pre_checkout_query_id"` + // Specify True if everything is alright (goods are available, etc.) and the bot is ready to proceed with the order. Use False if there are any problems. + Ok bool `json:"ok"` + // Required if ok is False. Error message in human readable form that explains the reason for failure to proceed with the checkout (e.g. "Sorry, somebody just bought the last of our amazing black T-shirts while you were busy filling out your payment details. Please choose a different color or garment!"). Telegram will display this message to the user. + ErrorMessage string `json:"error_message,omitempty"` +} + +// AnswerPreCheckoutQuery calls the answerPreCheckoutQuery Telegram Bot API method. +// +// Once the user has confirmed their payment and shipping details, the Bot API sends the final confirmation in the form of an Update with the field pre_checkout_query. Use this method to respond to such pre-checkout queries. On success, True is returned. Note: The Bot API must receive an answer within 10 seconds after the pre-checkout query was sent. +func AnswerPreCheckoutQuery(ctx context.Context, b *client.Bot, p *AnswerPreCheckoutQueryParams) (bool, error) { + return client.Call[*AnswerPreCheckoutQueryParams, bool](ctx, b, "answerPreCheckoutQuery", p) +} + +// GetMyStarBalanceParams is the parameter set for GetMyStarBalance. +// +// A method to get the current Telegram Stars balance of the bot. Requires no parameters. On success, returns a StarAmount object. +type GetMyStarBalanceParams struct { +} + +// GetMyStarBalance calls the getMyStarBalance Telegram Bot API method. +// +// A method to get the current Telegram Stars balance of the bot. Requires no parameters. On success, returns a StarAmount object. +func GetMyStarBalance(ctx context.Context, b *client.Bot, p *GetMyStarBalanceParams) (*StarAmount, error) { + return client.Call[*GetMyStarBalanceParams, *StarAmount](ctx, b, "getMyStarBalance", p) +} + +// GetStarTransactionsParams is the parameter set for GetStarTransactions. +// +// Returns the bot's Telegram Star transactions in chronological order. On success, returns a StarTransactions object. +type GetStarTransactionsParams struct { + // Number of transactions to skip in the response + Offset *int64 `json:"offset,omitempty"` + // The maximum number of transactions to be retrieved. Values between 1-100 are accepted. Defaults to 100. + Limit *int64 `json:"limit,omitempty"` +} + +// GetStarTransactions calls the getStarTransactions Telegram Bot API method. +// +// Returns the bot's Telegram Star transactions in chronological order. On success, returns a StarTransactions object. +func GetStarTransactions(ctx context.Context, b *client.Bot, p *GetStarTransactionsParams) (*StarTransactions, error) { + return client.Call[*GetStarTransactionsParams, *StarTransactions](ctx, b, "getStarTransactions", p) +} + +// RefundStarPaymentParams is the parameter set for RefundStarPayment. +// +// Refunds a successful payment in Telegram Stars. Returns True on success. +type RefundStarPaymentParams struct { + // Identifier of the user whose payment will be refunded + UserID int64 `json:"user_id"` + // Telegram payment identifier + TelegramPaymentChargeID string `json:"telegram_payment_charge_id"` +} + +// RefundStarPayment calls the refundStarPayment Telegram Bot API method. +// +// Refunds a successful payment in Telegram Stars. Returns True on success. +func RefundStarPayment(ctx context.Context, b *client.Bot, p *RefundStarPaymentParams) (bool, error) { + return client.Call[*RefundStarPaymentParams, bool](ctx, b, "refundStarPayment", p) +} + +// EditUserStarSubscriptionParams is the parameter set for EditUserStarSubscription. +// +// Allows the bot to cancel or re-enable extension of a subscription paid in Telegram Stars. Returns True on success. +type EditUserStarSubscriptionParams struct { + // Identifier of the user whose subscription will be edited + UserID int64 `json:"user_id"` + // Telegram payment identifier for the subscription + TelegramPaymentChargeID string `json:"telegram_payment_charge_id"` + // Pass True to cancel extension of the user subscription; the subscription must be active up to the end of the current subscription period. Pass False to allow the user to re-enable a subscription that was previously canceled by the bot. + IsCanceled bool `json:"is_canceled"` +} + +// EditUserStarSubscription calls the editUserStarSubscription Telegram Bot API method. +// +// Allows the bot to cancel or re-enable extension of a subscription paid in Telegram Stars. Returns True on success. +func EditUserStarSubscription(ctx context.Context, b *client.Bot, p *EditUserStarSubscriptionParams) (bool, error) { + return client.Call[*EditUserStarSubscriptionParams, bool](ctx, b, "editUserStarSubscription", p) +} + +// SetPassportDataErrorsParams is the parameter set for SetPassportDataErrors. +// +// Informs a user that some of the Telegram Passport elements they provided contains errors. The user will not be able to re-submit their Passport to you until the errors are fixed (the contents of the field for which you returned the error must change). Returns True on success. +// Use this if the data submitted by the user doesn't satisfy the standards your service requires for any reason. For example, if a birthday date seems invalid, a submitted document is blurry, a scan shows evidence of tampering, etc. Supply some details in the error message to make sure the user knows how to correct the issues. +type SetPassportDataErrorsParams struct { + // User identifier + UserID int64 `json:"user_id"` + // A JSON-serialized array describing the errors + Errors []PassportElementError `json:"errors"` +} + +// SetPassportDataErrors calls the setPassportDataErrors Telegram Bot API method. +// +// Informs a user that some of the Telegram Passport elements they provided contains errors. The user will not be able to re-submit their Passport to you until the errors are fixed (the contents of the field for which you returned the error must change). Returns True on success. +// Use this if the data submitted by the user doesn't satisfy the standards your service requires for any reason. For example, if a birthday date seems invalid, a submitted document is blurry, a scan shows evidence of tampering, etc. Supply some details in the error message to make sure the user knows how to correct the issues. +func SetPassportDataErrors(ctx context.Context, b *client.Bot, p *SetPassportDataErrorsParams) (bool, error) { + return client.Call[*SetPassportDataErrorsParams, bool](ctx, b, "setPassportDataErrors", p) +} + +// SendGameParams is the parameter set for SendGame. +// +// Use this method to send a game. On success, the sent Message is returned. +type SendGameParams struct { + // Unique identifier of the business connection on behalf of which the message will be sent + BusinessConnectionID string `json:"business_connection_id,omitempty"` + // Unique identifier for the target chat or username of the target bot in the format @username. Games can't be sent to channel direct messages chats and channel chats. + ChatID ChatID `json:"chat_id"` + // Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only + MessageThreadID *int64 `json:"message_thread_id,omitempty"` + // Short name of the game, serves as the unique identifier for the game. Set up your games via @BotFather. + GameShortName string `json:"game_short_name"` + // Sends the message silently. Users will receive a notification with no sound. + DisableNotification *bool `json:"disable_notification,omitempty"` + // Protects the contents of the sent message from forwarding and saving + ProtectContent *bool `json:"protect_content,omitempty"` + // Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance. + AllowPaidBroadcast *bool `json:"allow_paid_broadcast,omitempty"` + // Unique identifier of the message effect to be added to the message; for private chats only + MessageEffectID string `json:"message_effect_id,omitempty"` + // Description of the message to reply to + ReplyParameters *ReplyParameters `json:"reply_parameters,omitempty"` + // A JSON-serialized object for an inline keyboard. If empty, one 'Play game_title' button will be shown. If not empty, the first button must launch the game. + ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"` +} + +// SendGame calls the sendGame Telegram Bot API method. +// +// Use this method to send a game. On success, the sent Message is returned. +func SendGame(ctx context.Context, b *client.Bot, p *SendGameParams) (*Message, error) { + return client.Call[*SendGameParams, *Message](ctx, b, "sendGame", p) +} + +// SetGameScoreParams is the parameter set for SetGameScore. +// +// Use this method to set the score of the specified user in a game message. On success, if the message is not an inline message, the Message is returned, otherwise True is returned. Returns an error, if the new score is not greater than the user's current score in the chat and force is False. +type SetGameScoreParams struct { + // User identifier + UserID int64 `json:"user_id"` + // New score, must be non-negative + Score int64 `json:"score"` + // Pass True if the high score is allowed to decrease. This can be useful when fixing mistakes or banning cheaters + Force *bool `json:"force,omitempty"` + // Pass True if the game message should not be automatically edited to include the current scoreboard + DisableEditMessage *bool `json:"disable_edit_message,omitempty"` + // Required if inline_message_id is not specified. Unique identifier for the target chat + ChatID *int64 `json:"chat_id,omitempty"` + // Required if inline_message_id is not specified. Identifier of the sent message + MessageID *int64 `json:"message_id,omitempty"` + // Required if chat_id and message_id are not specified. Identifier of the inline message + InlineMessageID string `json:"inline_message_id,omitempty"` +} + +// SetGameScore calls the setGameScore Telegram Bot API method. +// +// Use this method to set the score of the specified user in a game message. On success, if the message is not an inline message, the Message is returned, otherwise True is returned. Returns an error, if the new score is not greater than the user's current score in the chat and force is False. +func SetGameScore(ctx context.Context, b *client.Bot, p *SetGameScoreParams) (*MessageOrBool, error) { + return client.Call[*SetGameScoreParams, *MessageOrBool](ctx, b, "setGameScore", p) +} + +// GetGameHighScoresParams is the parameter set for GetGameHighScores. +// +// Use this method to get data for high score tables. Will return the score of the specified user and several of their neighbors in a game. Returns an Array of GameHighScore objects. +// This method will currently return scores for the target user, plus two of their closest neighbors on each side. Will also return the top three users if the user and their neighbors are not among them. Please note that this behavior is subject to change. +type GetGameHighScoresParams struct { + // Target user id + UserID int64 `json:"user_id"` + // Required if inline_message_id is not specified. Unique identifier for the target chat + ChatID *int64 `json:"chat_id,omitempty"` + // Required if inline_message_id is not specified. Identifier of the sent message + MessageID *int64 `json:"message_id,omitempty"` + // Required if chat_id and message_id are not specified. Identifier of the inline message + InlineMessageID string `json:"inline_message_id,omitempty"` +} + +// GetGameHighScores calls the getGameHighScores Telegram Bot API method. +// +// Use this method to get data for high score tables. Will return the score of the specified user and several of their neighbors in a game. Returns an Array of GameHighScore objects. +// This method will currently return scores for the target user, plus two of their closest neighbors on each side. Will also return the top three users if the user and their neighbors are not among them. Please note that this behavior is subject to change. +func GetGameHighScores(ctx context.Context, b *client.Bot, p *GetGameHighScoresParams) ([]GameHighScore, error) { + return client.Call[*GetGameHighScoresParams, []GameHighScore](ctx, b, "getGameHighScores", p) +} diff --git a/api/methods_gen_test.go b/api/methods_gen_test.go new file mode 100644 index 0000000..fa2a30e --- /dev/null +++ b/api/methods_gen_test.go @@ -0,0 +1,24703 @@ +// Code generated by cmd/genapi. DO NOT EDIT. + +//go:build !ignore_autogenerated + +package api + +import ( + "bytes" + "context" + "errors" + "io" + "net/http" + "strings" + "testing" + + "github.com/lukaszraczylo/go-telegram/client" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" +) + +// genTestMockDoer is a testify-mock HTTPDoer used by generated tests only. +type genTestMockDoer struct{ mock.Mock } + +func (m *genTestMockDoer) Do(r *http.Request) (*http.Response, error) { + args := m.Called(r) + if v := args.Get(0); v != nil { + return v.(*http.Response), args.Error(1) + } + return nil, args.Error(1) +} + +func genTestResp(status int, body string) *http.Response { + return &http.Response{ + StatusCode: status, + Body: io.NopCloser(bytes.NewBufferString(body)), + Header: http.Header{"Content-Type": []string{"application/json"}}, + } +} + +func Test_GetUpdates_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/getUpdates") + })).Return(genTestResp(200, `{"ok":true,"result":[]}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetUpdatesParams{} + _, err := GetUpdates(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_GetUpdates_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetUpdatesParams{} + _, err := GetUpdates(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_GetUpdates_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetUpdatesParams{} + _, err := GetUpdates(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_GetUpdates_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetUpdatesParams{} + _, err := GetUpdates(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_GetUpdates_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetUpdatesParams{} + _, err := GetUpdates(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_GetUpdates_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_GetUpdates_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := GetUpdates(context.Background(), bot, &GetUpdatesParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_GetUpdates_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_GetUpdates_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetUpdatesParams{} + _, err := GetUpdates(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_GetUpdates_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_GetUpdates_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetUpdatesParams{} + _, err := GetUpdates(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_SetWebhook_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/setWebhook") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetWebhookParams{ + URL: "test_value", + } + _, err := SetWebhook(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_SetWebhook_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetWebhookParams{ + URL: "test_value", + } + _, err := SetWebhook(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_SetWebhook_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetWebhookParams{ + URL: "test_value", + } + _, err := SetWebhook(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_SetWebhook_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetWebhookParams{ + URL: "test_value", + } + _, err := SetWebhook(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_SetWebhook_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetWebhookParams{ + URL: "test_value", + } + _, err := SetWebhook(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_SetWebhook_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_SetWebhook_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := SetWebhook(context.Background(), bot, &SetWebhookParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_SetWebhook_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_SetWebhook_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetWebhookParams{ + URL: "test_value", + } + _, err := SetWebhook(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_SetWebhook_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_SetWebhook_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetWebhookParams{ + URL: "test_value", + } + _, err := SetWebhook(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_DeleteWebhook_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/deleteWebhook") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteWebhookParams{} + _, err := DeleteWebhook(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_DeleteWebhook_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteWebhookParams{} + _, err := DeleteWebhook(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_DeleteWebhook_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteWebhookParams{} + _, err := DeleteWebhook(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_DeleteWebhook_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteWebhookParams{} + _, err := DeleteWebhook(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_DeleteWebhook_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteWebhookParams{} + _, err := DeleteWebhook(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_DeleteWebhook_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_DeleteWebhook_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := DeleteWebhook(context.Background(), bot, &DeleteWebhookParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_DeleteWebhook_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_DeleteWebhook_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteWebhookParams{} + _, err := DeleteWebhook(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_DeleteWebhook_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_DeleteWebhook_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteWebhookParams{} + _, err := DeleteWebhook(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_GetWebhookInfo_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/getWebhookInfo") + })).Return(genTestResp(200, `{"ok":true,"result":{}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + _, err := GetWebhookInfo(context.Background(), bot, &GetWebhookInfoParams{}) + require.NoError(t, err) +} + +func Test_GetWebhookInfo_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + _, err := GetWebhookInfo(context.Background(), bot, &GetWebhookInfoParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_GetWebhookInfo_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + _, err := GetWebhookInfo(context.Background(), bot, &GetWebhookInfoParams{}) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_GetWebhookInfo_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + _, err := GetWebhookInfo(context.Background(), bot, &GetWebhookInfoParams{}) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_GetWebhookInfo_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + _, err := GetWebhookInfo(ctx, bot, &GetWebhookInfoParams{}) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_GetWebhookInfo_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_GetWebhookInfo_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := GetWebhookInfo(context.Background(), bot, &GetWebhookInfoParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_GetWebhookInfo_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_GetWebhookInfo_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + _, err := GetWebhookInfo(context.Background(), bot, &GetWebhookInfoParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_GetWebhookInfo_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_GetWebhookInfo_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + _, err := GetWebhookInfo(context.Background(), bot, &GetWebhookInfoParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_GetMe_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/getMe") + })).Return(genTestResp(200, `{"ok":true,"result":{}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + _, err := GetMe(context.Background(), bot, &GetMeParams{}) + require.NoError(t, err) +} + +func Test_GetMe_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + _, err := GetMe(context.Background(), bot, &GetMeParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_GetMe_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + _, err := GetMe(context.Background(), bot, &GetMeParams{}) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_GetMe_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + _, err := GetMe(context.Background(), bot, &GetMeParams{}) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_GetMe_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + _, err := GetMe(ctx, bot, &GetMeParams{}) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_GetMe_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_GetMe_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := GetMe(context.Background(), bot, &GetMeParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_GetMe_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_GetMe_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + _, err := GetMe(context.Background(), bot, &GetMeParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_GetMe_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_GetMe_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + _, err := GetMe(context.Background(), bot, &GetMeParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_LogOut_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/logOut") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + _, err := LogOut(context.Background(), bot, &LogOutParams{}) + require.NoError(t, err) +} + +func Test_LogOut_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + _, err := LogOut(context.Background(), bot, &LogOutParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_LogOut_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + _, err := LogOut(context.Background(), bot, &LogOutParams{}) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_LogOut_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + _, err := LogOut(context.Background(), bot, &LogOutParams{}) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_LogOut_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + _, err := LogOut(ctx, bot, &LogOutParams{}) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_LogOut_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_LogOut_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := LogOut(context.Background(), bot, &LogOutParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_LogOut_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_LogOut_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + _, err := LogOut(context.Background(), bot, &LogOutParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_LogOut_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_LogOut_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + _, err := LogOut(context.Background(), bot, &LogOutParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_Close_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/close") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + _, err := Close(context.Background(), bot, &CloseParams{}) + require.NoError(t, err) +} + +func Test_Close_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + _, err := Close(context.Background(), bot, &CloseParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_Close_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + _, err := Close(context.Background(), bot, &CloseParams{}) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_Close_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + _, err := Close(context.Background(), bot, &CloseParams{}) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_Close_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + _, err := Close(ctx, bot, &CloseParams{}) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_Close_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_Close_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := Close(context.Background(), bot, &CloseParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_Close_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_Close_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + _, err := Close(context.Background(), bot, &CloseParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_Close_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_Close_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + _, err := Close(context.Background(), bot, &CloseParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_SendMessage_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/sendMessage") + })).Return(genTestResp(200, `{"ok":true,"result":{}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendMessageParams{ + ChatID: ChatIDFromInt(123), + Text: "test_value", + } + _, err := SendMessage(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_SendMessage_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendMessageParams{ + ChatID: ChatIDFromInt(123), + Text: "test_value", + } + _, err := SendMessage(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_SendMessage_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendMessageParams{ + ChatID: ChatIDFromInt(123), + Text: "test_value", + } + _, err := SendMessage(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_SendMessage_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendMessageParams{ + ChatID: ChatIDFromInt(123), + Text: "test_value", + } + _, err := SendMessage(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_SendMessage_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendMessageParams{ + ChatID: ChatIDFromInt(123), + Text: "test_value", + } + _, err := SendMessage(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_SendMessage_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_SendMessage_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := SendMessage(context.Background(), bot, &SendMessageParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_SendMessage_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_SendMessage_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendMessageParams{ + ChatID: ChatIDFromInt(123), + Text: "test_value", + } + _, err := SendMessage(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_SendMessage_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_SendMessage_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendMessageParams{ + ChatID: ChatIDFromInt(123), + Text: "test_value", + } + _, err := SendMessage(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_ForwardMessage_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/forwardMessage") + })).Return(genTestResp(200, `{"ok":true,"result":{}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &ForwardMessageParams{ + ChatID: ChatIDFromInt(123), + FromChatID: ChatIDFromInt(123), + MessageID: 42, + } + _, err := ForwardMessage(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_ForwardMessage_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &ForwardMessageParams{ + ChatID: ChatIDFromInt(123), + FromChatID: ChatIDFromInt(123), + MessageID: 42, + } + _, err := ForwardMessage(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_ForwardMessage_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &ForwardMessageParams{ + ChatID: ChatIDFromInt(123), + FromChatID: ChatIDFromInt(123), + MessageID: 42, + } + _, err := ForwardMessage(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_ForwardMessage_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &ForwardMessageParams{ + ChatID: ChatIDFromInt(123), + FromChatID: ChatIDFromInt(123), + MessageID: 42, + } + _, err := ForwardMessage(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_ForwardMessage_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &ForwardMessageParams{ + ChatID: ChatIDFromInt(123), + FromChatID: ChatIDFromInt(123), + MessageID: 42, + } + _, err := ForwardMessage(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_ForwardMessage_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_ForwardMessage_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := ForwardMessage(context.Background(), bot, &ForwardMessageParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_ForwardMessage_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_ForwardMessage_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &ForwardMessageParams{ + ChatID: ChatIDFromInt(123), + FromChatID: ChatIDFromInt(123), + MessageID: 42, + } + _, err := ForwardMessage(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_ForwardMessage_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_ForwardMessage_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &ForwardMessageParams{ + ChatID: ChatIDFromInt(123), + FromChatID: ChatIDFromInt(123), + MessageID: 42, + } + _, err := ForwardMessage(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_ForwardMessages_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/forwardMessages") + })).Return(genTestResp(200, `{"ok":true,"result":[]}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &ForwardMessagesParams{ + ChatID: ChatIDFromInt(123), + FromChatID: ChatIDFromInt(123), + MessageIds: nil, + } + _, err := ForwardMessages(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_ForwardMessages_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &ForwardMessagesParams{ + ChatID: ChatIDFromInt(123), + FromChatID: ChatIDFromInt(123), + MessageIds: nil, + } + _, err := ForwardMessages(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_ForwardMessages_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &ForwardMessagesParams{ + ChatID: ChatIDFromInt(123), + FromChatID: ChatIDFromInt(123), + MessageIds: nil, + } + _, err := ForwardMessages(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_ForwardMessages_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &ForwardMessagesParams{ + ChatID: ChatIDFromInt(123), + FromChatID: ChatIDFromInt(123), + MessageIds: nil, + } + _, err := ForwardMessages(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_ForwardMessages_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &ForwardMessagesParams{ + ChatID: ChatIDFromInt(123), + FromChatID: ChatIDFromInt(123), + MessageIds: nil, + } + _, err := ForwardMessages(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_ForwardMessages_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_ForwardMessages_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := ForwardMessages(context.Background(), bot, &ForwardMessagesParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_ForwardMessages_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_ForwardMessages_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &ForwardMessagesParams{ + ChatID: ChatIDFromInt(123), + FromChatID: ChatIDFromInt(123), + MessageIds: nil, + } + _, err := ForwardMessages(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_ForwardMessages_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_ForwardMessages_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &ForwardMessagesParams{ + ChatID: ChatIDFromInt(123), + FromChatID: ChatIDFromInt(123), + MessageIds: nil, + } + _, err := ForwardMessages(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_CopyMessage_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/copyMessage") + })).Return(genTestResp(200, `{"ok":true,"result":{}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &CopyMessageParams{ + ChatID: ChatIDFromInt(123), + FromChatID: ChatIDFromInt(123), + MessageID: 42, + } + _, err := CopyMessage(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_CopyMessage_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &CopyMessageParams{ + ChatID: ChatIDFromInt(123), + FromChatID: ChatIDFromInt(123), + MessageID: 42, + } + _, err := CopyMessage(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_CopyMessage_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &CopyMessageParams{ + ChatID: ChatIDFromInt(123), + FromChatID: ChatIDFromInt(123), + MessageID: 42, + } + _, err := CopyMessage(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_CopyMessage_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &CopyMessageParams{ + ChatID: ChatIDFromInt(123), + FromChatID: ChatIDFromInt(123), + MessageID: 42, + } + _, err := CopyMessage(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_CopyMessage_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &CopyMessageParams{ + ChatID: ChatIDFromInt(123), + FromChatID: ChatIDFromInt(123), + MessageID: 42, + } + _, err := CopyMessage(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_CopyMessage_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_CopyMessage_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := CopyMessage(context.Background(), bot, &CopyMessageParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_CopyMessage_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_CopyMessage_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &CopyMessageParams{ + ChatID: ChatIDFromInt(123), + FromChatID: ChatIDFromInt(123), + MessageID: 42, + } + _, err := CopyMessage(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_CopyMessage_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_CopyMessage_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &CopyMessageParams{ + ChatID: ChatIDFromInt(123), + FromChatID: ChatIDFromInt(123), + MessageID: 42, + } + _, err := CopyMessage(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_CopyMessages_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/copyMessages") + })).Return(genTestResp(200, `{"ok":true,"result":[]}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &CopyMessagesParams{ + ChatID: ChatIDFromInt(123), + FromChatID: ChatIDFromInt(123), + MessageIds: nil, + } + _, err := CopyMessages(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_CopyMessages_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &CopyMessagesParams{ + ChatID: ChatIDFromInt(123), + FromChatID: ChatIDFromInt(123), + MessageIds: nil, + } + _, err := CopyMessages(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_CopyMessages_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &CopyMessagesParams{ + ChatID: ChatIDFromInt(123), + FromChatID: ChatIDFromInt(123), + MessageIds: nil, + } + _, err := CopyMessages(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_CopyMessages_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &CopyMessagesParams{ + ChatID: ChatIDFromInt(123), + FromChatID: ChatIDFromInt(123), + MessageIds: nil, + } + _, err := CopyMessages(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_CopyMessages_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &CopyMessagesParams{ + ChatID: ChatIDFromInt(123), + FromChatID: ChatIDFromInt(123), + MessageIds: nil, + } + _, err := CopyMessages(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_CopyMessages_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_CopyMessages_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := CopyMessages(context.Background(), bot, &CopyMessagesParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_CopyMessages_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_CopyMessages_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &CopyMessagesParams{ + ChatID: ChatIDFromInt(123), + FromChatID: ChatIDFromInt(123), + MessageIds: nil, + } + _, err := CopyMessages(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_CopyMessages_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_CopyMessages_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &CopyMessagesParams{ + ChatID: ChatIDFromInt(123), + FromChatID: ChatIDFromInt(123), + MessageIds: nil, + } + _, err := CopyMessages(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_SendPhoto_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/sendPhoto") + })).Return(genTestResp(200, `{"ok":true,"result":{}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendPhotoParams{ + ChatID: ChatIDFromInt(123), + Photo: &InputFile{PathOrID: "file_id_test"}, + } + _, err := SendPhoto(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_SendPhoto_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendPhotoParams{ + ChatID: ChatIDFromInt(123), + Photo: &InputFile{PathOrID: "file_id_test"}, + } + _, err := SendPhoto(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_SendPhoto_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendPhotoParams{ + ChatID: ChatIDFromInt(123), + Photo: &InputFile{PathOrID: "file_id_test"}, + } + _, err := SendPhoto(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_SendPhoto_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendPhotoParams{ + ChatID: ChatIDFromInt(123), + Photo: &InputFile{PathOrID: "file_id_test"}, + } + _, err := SendPhoto(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_SendPhoto_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendPhotoParams{ + ChatID: ChatIDFromInt(123), + Photo: &InputFile{PathOrID: "file_id_test"}, + } + _, err := SendPhoto(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_SendPhoto_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_SendPhoto_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := SendPhoto(context.Background(), bot, &SendPhotoParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_SendPhoto_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_SendPhoto_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendPhotoParams{ + ChatID: ChatIDFromInt(123), + Photo: &InputFile{PathOrID: "file_id_test"}, + } + _, err := SendPhoto(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_SendPhoto_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_SendPhoto_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendPhotoParams{ + ChatID: ChatIDFromInt(123), + Photo: &InputFile{PathOrID: "file_id_test"}, + } + _, err := SendPhoto(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_SendLivePhoto_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/sendLivePhoto") + })).Return(genTestResp(200, `{"ok":true,"result":{}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendLivePhotoParams{ + ChatID: ChatIDFromInt(123), + LivePhoto: &InputFile{PathOrID: "file_id_test"}, + Photo: &InputFile{PathOrID: "file_id_test"}, + } + _, err := SendLivePhoto(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_SendLivePhoto_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendLivePhotoParams{ + ChatID: ChatIDFromInt(123), + LivePhoto: &InputFile{PathOrID: "file_id_test"}, + Photo: &InputFile{PathOrID: "file_id_test"}, + } + _, err := SendLivePhoto(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_SendLivePhoto_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendLivePhotoParams{ + ChatID: ChatIDFromInt(123), + LivePhoto: &InputFile{PathOrID: "file_id_test"}, + Photo: &InputFile{PathOrID: "file_id_test"}, + } + _, err := SendLivePhoto(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_SendLivePhoto_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendLivePhotoParams{ + ChatID: ChatIDFromInt(123), + LivePhoto: &InputFile{PathOrID: "file_id_test"}, + Photo: &InputFile{PathOrID: "file_id_test"}, + } + _, err := SendLivePhoto(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_SendLivePhoto_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendLivePhotoParams{ + ChatID: ChatIDFromInt(123), + LivePhoto: &InputFile{PathOrID: "file_id_test"}, + Photo: &InputFile{PathOrID: "file_id_test"}, + } + _, err := SendLivePhoto(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_SendLivePhoto_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_SendLivePhoto_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := SendLivePhoto(context.Background(), bot, &SendLivePhotoParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_SendLivePhoto_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_SendLivePhoto_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendLivePhotoParams{ + ChatID: ChatIDFromInt(123), + LivePhoto: &InputFile{PathOrID: "file_id_test"}, + Photo: &InputFile{PathOrID: "file_id_test"}, + } + _, err := SendLivePhoto(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_SendLivePhoto_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_SendLivePhoto_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendLivePhotoParams{ + ChatID: ChatIDFromInt(123), + LivePhoto: &InputFile{PathOrID: "file_id_test"}, + Photo: &InputFile{PathOrID: "file_id_test"}, + } + _, err := SendLivePhoto(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_SendAudio_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/sendAudio") + })).Return(genTestResp(200, `{"ok":true,"result":{}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendAudioParams{ + ChatID: ChatIDFromInt(123), + Audio: &InputFile{PathOrID: "file_id_test"}, + } + _, err := SendAudio(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_SendAudio_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendAudioParams{ + ChatID: ChatIDFromInt(123), + Audio: &InputFile{PathOrID: "file_id_test"}, + } + _, err := SendAudio(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_SendAudio_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendAudioParams{ + ChatID: ChatIDFromInt(123), + Audio: &InputFile{PathOrID: "file_id_test"}, + } + _, err := SendAudio(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_SendAudio_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendAudioParams{ + ChatID: ChatIDFromInt(123), + Audio: &InputFile{PathOrID: "file_id_test"}, + } + _, err := SendAudio(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_SendAudio_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendAudioParams{ + ChatID: ChatIDFromInt(123), + Audio: &InputFile{PathOrID: "file_id_test"}, + } + _, err := SendAudio(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_SendAudio_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_SendAudio_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := SendAudio(context.Background(), bot, &SendAudioParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_SendAudio_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_SendAudio_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendAudioParams{ + ChatID: ChatIDFromInt(123), + Audio: &InputFile{PathOrID: "file_id_test"}, + } + _, err := SendAudio(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_SendAudio_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_SendAudio_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendAudioParams{ + ChatID: ChatIDFromInt(123), + Audio: &InputFile{PathOrID: "file_id_test"}, + } + _, err := SendAudio(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_SendDocument_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/sendDocument") + })).Return(genTestResp(200, `{"ok":true,"result":{}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendDocumentParams{ + ChatID: ChatIDFromInt(123), + Document: &InputFile{PathOrID: "file_id_test"}, + } + _, err := SendDocument(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_SendDocument_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendDocumentParams{ + ChatID: ChatIDFromInt(123), + Document: &InputFile{PathOrID: "file_id_test"}, + } + _, err := SendDocument(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_SendDocument_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendDocumentParams{ + ChatID: ChatIDFromInt(123), + Document: &InputFile{PathOrID: "file_id_test"}, + } + _, err := SendDocument(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_SendDocument_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendDocumentParams{ + ChatID: ChatIDFromInt(123), + Document: &InputFile{PathOrID: "file_id_test"}, + } + _, err := SendDocument(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_SendDocument_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendDocumentParams{ + ChatID: ChatIDFromInt(123), + Document: &InputFile{PathOrID: "file_id_test"}, + } + _, err := SendDocument(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_SendDocument_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_SendDocument_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := SendDocument(context.Background(), bot, &SendDocumentParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_SendDocument_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_SendDocument_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendDocumentParams{ + ChatID: ChatIDFromInt(123), + Document: &InputFile{PathOrID: "file_id_test"}, + } + _, err := SendDocument(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_SendDocument_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_SendDocument_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendDocumentParams{ + ChatID: ChatIDFromInt(123), + Document: &InputFile{PathOrID: "file_id_test"}, + } + _, err := SendDocument(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_SendVideo_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/sendVideo") + })).Return(genTestResp(200, `{"ok":true,"result":{}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendVideoParams{ + ChatID: ChatIDFromInt(123), + Video: &InputFile{PathOrID: "file_id_test"}, + } + _, err := SendVideo(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_SendVideo_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendVideoParams{ + ChatID: ChatIDFromInt(123), + Video: &InputFile{PathOrID: "file_id_test"}, + } + _, err := SendVideo(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_SendVideo_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendVideoParams{ + ChatID: ChatIDFromInt(123), + Video: &InputFile{PathOrID: "file_id_test"}, + } + _, err := SendVideo(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_SendVideo_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendVideoParams{ + ChatID: ChatIDFromInt(123), + Video: &InputFile{PathOrID: "file_id_test"}, + } + _, err := SendVideo(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_SendVideo_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendVideoParams{ + ChatID: ChatIDFromInt(123), + Video: &InputFile{PathOrID: "file_id_test"}, + } + _, err := SendVideo(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_SendVideo_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_SendVideo_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := SendVideo(context.Background(), bot, &SendVideoParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_SendVideo_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_SendVideo_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendVideoParams{ + ChatID: ChatIDFromInt(123), + Video: &InputFile{PathOrID: "file_id_test"}, + } + _, err := SendVideo(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_SendVideo_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_SendVideo_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendVideoParams{ + ChatID: ChatIDFromInt(123), + Video: &InputFile{PathOrID: "file_id_test"}, + } + _, err := SendVideo(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_SendAnimation_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/sendAnimation") + })).Return(genTestResp(200, `{"ok":true,"result":{}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendAnimationParams{ + ChatID: ChatIDFromInt(123), + Animation: &InputFile{PathOrID: "file_id_test"}, + } + _, err := SendAnimation(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_SendAnimation_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendAnimationParams{ + ChatID: ChatIDFromInt(123), + Animation: &InputFile{PathOrID: "file_id_test"}, + } + _, err := SendAnimation(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_SendAnimation_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendAnimationParams{ + ChatID: ChatIDFromInt(123), + Animation: &InputFile{PathOrID: "file_id_test"}, + } + _, err := SendAnimation(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_SendAnimation_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendAnimationParams{ + ChatID: ChatIDFromInt(123), + Animation: &InputFile{PathOrID: "file_id_test"}, + } + _, err := SendAnimation(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_SendAnimation_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendAnimationParams{ + ChatID: ChatIDFromInt(123), + Animation: &InputFile{PathOrID: "file_id_test"}, + } + _, err := SendAnimation(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_SendAnimation_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_SendAnimation_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := SendAnimation(context.Background(), bot, &SendAnimationParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_SendAnimation_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_SendAnimation_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendAnimationParams{ + ChatID: ChatIDFromInt(123), + Animation: &InputFile{PathOrID: "file_id_test"}, + } + _, err := SendAnimation(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_SendAnimation_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_SendAnimation_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendAnimationParams{ + ChatID: ChatIDFromInt(123), + Animation: &InputFile{PathOrID: "file_id_test"}, + } + _, err := SendAnimation(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_SendVoice_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/sendVoice") + })).Return(genTestResp(200, `{"ok":true,"result":{}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendVoiceParams{ + ChatID: ChatIDFromInt(123), + Voice: &InputFile{PathOrID: "file_id_test"}, + } + _, err := SendVoice(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_SendVoice_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendVoiceParams{ + ChatID: ChatIDFromInt(123), + Voice: &InputFile{PathOrID: "file_id_test"}, + } + _, err := SendVoice(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_SendVoice_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendVoiceParams{ + ChatID: ChatIDFromInt(123), + Voice: &InputFile{PathOrID: "file_id_test"}, + } + _, err := SendVoice(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_SendVoice_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendVoiceParams{ + ChatID: ChatIDFromInt(123), + Voice: &InputFile{PathOrID: "file_id_test"}, + } + _, err := SendVoice(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_SendVoice_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendVoiceParams{ + ChatID: ChatIDFromInt(123), + Voice: &InputFile{PathOrID: "file_id_test"}, + } + _, err := SendVoice(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_SendVoice_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_SendVoice_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := SendVoice(context.Background(), bot, &SendVoiceParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_SendVoice_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_SendVoice_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendVoiceParams{ + ChatID: ChatIDFromInt(123), + Voice: &InputFile{PathOrID: "file_id_test"}, + } + _, err := SendVoice(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_SendVoice_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_SendVoice_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendVoiceParams{ + ChatID: ChatIDFromInt(123), + Voice: &InputFile{PathOrID: "file_id_test"}, + } + _, err := SendVoice(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_SendVideoNote_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/sendVideoNote") + })).Return(genTestResp(200, `{"ok":true,"result":{}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendVideoNoteParams{ + ChatID: ChatIDFromInt(123), + VideoNote: &InputFile{PathOrID: "file_id_test"}, + } + _, err := SendVideoNote(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_SendVideoNote_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendVideoNoteParams{ + ChatID: ChatIDFromInt(123), + VideoNote: &InputFile{PathOrID: "file_id_test"}, + } + _, err := SendVideoNote(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_SendVideoNote_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendVideoNoteParams{ + ChatID: ChatIDFromInt(123), + VideoNote: &InputFile{PathOrID: "file_id_test"}, + } + _, err := SendVideoNote(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_SendVideoNote_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendVideoNoteParams{ + ChatID: ChatIDFromInt(123), + VideoNote: &InputFile{PathOrID: "file_id_test"}, + } + _, err := SendVideoNote(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_SendVideoNote_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendVideoNoteParams{ + ChatID: ChatIDFromInt(123), + VideoNote: &InputFile{PathOrID: "file_id_test"}, + } + _, err := SendVideoNote(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_SendVideoNote_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_SendVideoNote_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := SendVideoNote(context.Background(), bot, &SendVideoNoteParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_SendVideoNote_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_SendVideoNote_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendVideoNoteParams{ + ChatID: ChatIDFromInt(123), + VideoNote: &InputFile{PathOrID: "file_id_test"}, + } + _, err := SendVideoNote(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_SendVideoNote_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_SendVideoNote_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendVideoNoteParams{ + ChatID: ChatIDFromInt(123), + VideoNote: &InputFile{PathOrID: "file_id_test"}, + } + _, err := SendVideoNote(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_SendPaidMedia_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/sendPaidMedia") + })).Return(genTestResp(200, `{"ok":true,"result":{}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendPaidMediaParams{ + ChatID: ChatIDFromInt(123), + StarCount: 42, + Media: nil, + } + _, err := SendPaidMedia(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_SendPaidMedia_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendPaidMediaParams{ + ChatID: ChatIDFromInt(123), + StarCount: 42, + Media: nil, + } + _, err := SendPaidMedia(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_SendPaidMedia_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendPaidMediaParams{ + ChatID: ChatIDFromInt(123), + StarCount: 42, + Media: nil, + } + _, err := SendPaidMedia(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_SendPaidMedia_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendPaidMediaParams{ + ChatID: ChatIDFromInt(123), + StarCount: 42, + Media: nil, + } + _, err := SendPaidMedia(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_SendPaidMedia_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendPaidMediaParams{ + ChatID: ChatIDFromInt(123), + StarCount: 42, + Media: nil, + } + _, err := SendPaidMedia(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_SendPaidMedia_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_SendPaidMedia_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := SendPaidMedia(context.Background(), bot, &SendPaidMediaParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_SendPaidMedia_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_SendPaidMedia_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendPaidMediaParams{ + ChatID: ChatIDFromInt(123), + StarCount: 42, + Media: nil, + } + _, err := SendPaidMedia(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_SendPaidMedia_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_SendPaidMedia_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendPaidMediaParams{ + ChatID: ChatIDFromInt(123), + StarCount: 42, + Media: nil, + } + _, err := SendPaidMedia(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_SendMediaGroup_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/sendMediaGroup") + })).Return(genTestResp(200, `{"ok":true,"result":[]}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendMediaGroupParams{ + ChatID: ChatIDFromInt(123), + Media: nil, + } + _, err := SendMediaGroup(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_SendMediaGroup_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendMediaGroupParams{ + ChatID: ChatIDFromInt(123), + Media: nil, + } + _, err := SendMediaGroup(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_SendMediaGroup_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendMediaGroupParams{ + ChatID: ChatIDFromInt(123), + Media: nil, + } + _, err := SendMediaGroup(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_SendMediaGroup_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendMediaGroupParams{ + ChatID: ChatIDFromInt(123), + Media: nil, + } + _, err := SendMediaGroup(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_SendMediaGroup_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendMediaGroupParams{ + ChatID: ChatIDFromInt(123), + Media: nil, + } + _, err := SendMediaGroup(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_SendMediaGroup_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_SendMediaGroup_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := SendMediaGroup(context.Background(), bot, &SendMediaGroupParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_SendMediaGroup_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_SendMediaGroup_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendMediaGroupParams{ + ChatID: ChatIDFromInt(123), + Media: nil, + } + _, err := SendMediaGroup(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_SendMediaGroup_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_SendMediaGroup_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendMediaGroupParams{ + ChatID: ChatIDFromInt(123), + Media: nil, + } + _, err := SendMediaGroup(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_SendLocation_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/sendLocation") + })).Return(genTestResp(200, `{"ok":true,"result":{}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendLocationParams{ + ChatID: ChatIDFromInt(123), + Latitude: 1.0, + Longitude: 1.0, + } + _, err := SendLocation(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_SendLocation_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendLocationParams{ + ChatID: ChatIDFromInt(123), + Latitude: 1.0, + Longitude: 1.0, + } + _, err := SendLocation(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_SendLocation_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendLocationParams{ + ChatID: ChatIDFromInt(123), + Latitude: 1.0, + Longitude: 1.0, + } + _, err := SendLocation(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_SendLocation_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendLocationParams{ + ChatID: ChatIDFromInt(123), + Latitude: 1.0, + Longitude: 1.0, + } + _, err := SendLocation(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_SendLocation_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendLocationParams{ + ChatID: ChatIDFromInt(123), + Latitude: 1.0, + Longitude: 1.0, + } + _, err := SendLocation(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_SendLocation_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_SendLocation_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := SendLocation(context.Background(), bot, &SendLocationParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_SendLocation_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_SendLocation_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendLocationParams{ + ChatID: ChatIDFromInt(123), + Latitude: 1.0, + Longitude: 1.0, + } + _, err := SendLocation(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_SendLocation_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_SendLocation_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendLocationParams{ + ChatID: ChatIDFromInt(123), + Latitude: 1.0, + Longitude: 1.0, + } + _, err := SendLocation(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_SendVenue_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/sendVenue") + })).Return(genTestResp(200, `{"ok":true,"result":{}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendVenueParams{ + ChatID: ChatIDFromInt(123), + Latitude: 1.0, + Longitude: 1.0, + Title: "test_value", + Address: "test_value", + } + _, err := SendVenue(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_SendVenue_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendVenueParams{ + ChatID: ChatIDFromInt(123), + Latitude: 1.0, + Longitude: 1.0, + Title: "test_value", + Address: "test_value", + } + _, err := SendVenue(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_SendVenue_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendVenueParams{ + ChatID: ChatIDFromInt(123), + Latitude: 1.0, + Longitude: 1.0, + Title: "test_value", + Address: "test_value", + } + _, err := SendVenue(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_SendVenue_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendVenueParams{ + ChatID: ChatIDFromInt(123), + Latitude: 1.0, + Longitude: 1.0, + Title: "test_value", + Address: "test_value", + } + _, err := SendVenue(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_SendVenue_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendVenueParams{ + ChatID: ChatIDFromInt(123), + Latitude: 1.0, + Longitude: 1.0, + Title: "test_value", + Address: "test_value", + } + _, err := SendVenue(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_SendVenue_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_SendVenue_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := SendVenue(context.Background(), bot, &SendVenueParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_SendVenue_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_SendVenue_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendVenueParams{ + ChatID: ChatIDFromInt(123), + Latitude: 1.0, + Longitude: 1.0, + Title: "test_value", + Address: "test_value", + } + _, err := SendVenue(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_SendVenue_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_SendVenue_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendVenueParams{ + ChatID: ChatIDFromInt(123), + Latitude: 1.0, + Longitude: 1.0, + Title: "test_value", + Address: "test_value", + } + _, err := SendVenue(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_SendContact_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/sendContact") + })).Return(genTestResp(200, `{"ok":true,"result":{}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendContactParams{ + ChatID: ChatIDFromInt(123), + PhoneNumber: "test_value", + FirstName: "test_value", + } + _, err := SendContact(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_SendContact_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendContactParams{ + ChatID: ChatIDFromInt(123), + PhoneNumber: "test_value", + FirstName: "test_value", + } + _, err := SendContact(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_SendContact_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendContactParams{ + ChatID: ChatIDFromInt(123), + PhoneNumber: "test_value", + FirstName: "test_value", + } + _, err := SendContact(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_SendContact_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendContactParams{ + ChatID: ChatIDFromInt(123), + PhoneNumber: "test_value", + FirstName: "test_value", + } + _, err := SendContact(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_SendContact_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendContactParams{ + ChatID: ChatIDFromInt(123), + PhoneNumber: "test_value", + FirstName: "test_value", + } + _, err := SendContact(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_SendContact_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_SendContact_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := SendContact(context.Background(), bot, &SendContactParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_SendContact_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_SendContact_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendContactParams{ + ChatID: ChatIDFromInt(123), + PhoneNumber: "test_value", + FirstName: "test_value", + } + _, err := SendContact(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_SendContact_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_SendContact_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendContactParams{ + ChatID: ChatIDFromInt(123), + PhoneNumber: "test_value", + FirstName: "test_value", + } + _, err := SendContact(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_SendPoll_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/sendPoll") + })).Return(genTestResp(200, `{"ok":true,"result":{}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendPollParams{ + ChatID: ChatIDFromInt(123), + Question: "test_value", + Options: nil, + } + _, err := SendPoll(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_SendPoll_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendPollParams{ + ChatID: ChatIDFromInt(123), + Question: "test_value", + Options: nil, + } + _, err := SendPoll(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_SendPoll_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendPollParams{ + ChatID: ChatIDFromInt(123), + Question: "test_value", + Options: nil, + } + _, err := SendPoll(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_SendPoll_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendPollParams{ + ChatID: ChatIDFromInt(123), + Question: "test_value", + Options: nil, + } + _, err := SendPoll(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_SendPoll_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendPollParams{ + ChatID: ChatIDFromInt(123), + Question: "test_value", + Options: nil, + } + _, err := SendPoll(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_SendPoll_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_SendPoll_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := SendPoll(context.Background(), bot, &SendPollParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_SendPoll_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_SendPoll_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendPollParams{ + ChatID: ChatIDFromInt(123), + Question: "test_value", + Options: nil, + } + _, err := SendPoll(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_SendPoll_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_SendPoll_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendPollParams{ + ChatID: ChatIDFromInt(123), + Question: "test_value", + Options: nil, + } + _, err := SendPoll(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_SendChecklist_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/sendChecklist") + })).Return(genTestResp(200, `{"ok":true,"result":{}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendChecklistParams{ + BusinessConnectionID: "test_value", + ChatID: ChatIDFromInt(123), + Checklist: InputChecklist{}, + } + _, err := SendChecklist(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_SendChecklist_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendChecklistParams{ + BusinessConnectionID: "test_value", + ChatID: ChatIDFromInt(123), + Checklist: InputChecklist{}, + } + _, err := SendChecklist(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_SendChecklist_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendChecklistParams{ + BusinessConnectionID: "test_value", + ChatID: ChatIDFromInt(123), + Checklist: InputChecklist{}, + } + _, err := SendChecklist(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_SendChecklist_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendChecklistParams{ + BusinessConnectionID: "test_value", + ChatID: ChatIDFromInt(123), + Checklist: InputChecklist{}, + } + _, err := SendChecklist(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_SendChecklist_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendChecklistParams{ + BusinessConnectionID: "test_value", + ChatID: ChatIDFromInt(123), + Checklist: InputChecklist{}, + } + _, err := SendChecklist(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_SendChecklist_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_SendChecklist_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := SendChecklist(context.Background(), bot, &SendChecklistParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_SendChecklist_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_SendChecklist_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendChecklistParams{ + BusinessConnectionID: "test_value", + ChatID: ChatIDFromInt(123), + Checklist: InputChecklist{}, + } + _, err := SendChecklist(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_SendChecklist_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_SendChecklist_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendChecklistParams{ + BusinessConnectionID: "test_value", + ChatID: ChatIDFromInt(123), + Checklist: InputChecklist{}, + } + _, err := SendChecklist(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_SendDice_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/sendDice") + })).Return(genTestResp(200, `{"ok":true,"result":{}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendDiceParams{ + ChatID: ChatIDFromInt(123), + } + _, err := SendDice(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_SendDice_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendDiceParams{ + ChatID: ChatIDFromInt(123), + } + _, err := SendDice(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_SendDice_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendDiceParams{ + ChatID: ChatIDFromInt(123), + } + _, err := SendDice(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_SendDice_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendDiceParams{ + ChatID: ChatIDFromInt(123), + } + _, err := SendDice(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_SendDice_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendDiceParams{ + ChatID: ChatIDFromInt(123), + } + _, err := SendDice(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_SendDice_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_SendDice_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := SendDice(context.Background(), bot, &SendDiceParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_SendDice_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_SendDice_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendDiceParams{ + ChatID: ChatIDFromInt(123), + } + _, err := SendDice(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_SendDice_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_SendDice_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendDiceParams{ + ChatID: ChatIDFromInt(123), + } + _, err := SendDice(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_SendMessageDraft_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/sendMessageDraft") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendMessageDraftParams{ + ChatID: 42, + DraftID: 42, + } + _, err := SendMessageDraft(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_SendMessageDraft_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendMessageDraftParams{ + ChatID: 42, + DraftID: 42, + } + _, err := SendMessageDraft(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_SendMessageDraft_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendMessageDraftParams{ + ChatID: 42, + DraftID: 42, + } + _, err := SendMessageDraft(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_SendMessageDraft_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendMessageDraftParams{ + ChatID: 42, + DraftID: 42, + } + _, err := SendMessageDraft(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_SendMessageDraft_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendMessageDraftParams{ + ChatID: 42, + DraftID: 42, + } + _, err := SendMessageDraft(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_SendMessageDraft_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_SendMessageDraft_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := SendMessageDraft(context.Background(), bot, &SendMessageDraftParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_SendMessageDraft_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_SendMessageDraft_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendMessageDraftParams{ + ChatID: 42, + DraftID: 42, + } + _, err := SendMessageDraft(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_SendMessageDraft_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_SendMessageDraft_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendMessageDraftParams{ + ChatID: 42, + DraftID: 42, + } + _, err := SendMessageDraft(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_SendChatAction_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/sendChatAction") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendChatActionParams{ + ChatID: ChatIDFromInt(123), + Action: "test_value", + } + _, err := SendChatAction(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_SendChatAction_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendChatActionParams{ + ChatID: ChatIDFromInt(123), + Action: "test_value", + } + _, err := SendChatAction(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_SendChatAction_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendChatActionParams{ + ChatID: ChatIDFromInt(123), + Action: "test_value", + } + _, err := SendChatAction(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_SendChatAction_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendChatActionParams{ + ChatID: ChatIDFromInt(123), + Action: "test_value", + } + _, err := SendChatAction(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_SendChatAction_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendChatActionParams{ + ChatID: ChatIDFromInt(123), + Action: "test_value", + } + _, err := SendChatAction(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_SendChatAction_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_SendChatAction_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := SendChatAction(context.Background(), bot, &SendChatActionParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_SendChatAction_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_SendChatAction_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendChatActionParams{ + ChatID: ChatIDFromInt(123), + Action: "test_value", + } + _, err := SendChatAction(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_SendChatAction_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_SendChatAction_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendChatActionParams{ + ChatID: ChatIDFromInt(123), + Action: "test_value", + } + _, err := SendChatAction(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_SetMessageReaction_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/setMessageReaction") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetMessageReactionParams{ + ChatID: ChatIDFromInt(123), + MessageID: 42, + } + _, err := SetMessageReaction(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_SetMessageReaction_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetMessageReactionParams{ + ChatID: ChatIDFromInt(123), + MessageID: 42, + } + _, err := SetMessageReaction(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_SetMessageReaction_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetMessageReactionParams{ + ChatID: ChatIDFromInt(123), + MessageID: 42, + } + _, err := SetMessageReaction(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_SetMessageReaction_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetMessageReactionParams{ + ChatID: ChatIDFromInt(123), + MessageID: 42, + } + _, err := SetMessageReaction(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_SetMessageReaction_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetMessageReactionParams{ + ChatID: ChatIDFromInt(123), + MessageID: 42, + } + _, err := SetMessageReaction(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_SetMessageReaction_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_SetMessageReaction_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := SetMessageReaction(context.Background(), bot, &SetMessageReactionParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_SetMessageReaction_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_SetMessageReaction_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetMessageReactionParams{ + ChatID: ChatIDFromInt(123), + MessageID: 42, + } + _, err := SetMessageReaction(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_SetMessageReaction_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_SetMessageReaction_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetMessageReactionParams{ + ChatID: ChatIDFromInt(123), + MessageID: 42, + } + _, err := SetMessageReaction(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_GetUserProfilePhotos_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/getUserProfilePhotos") + })).Return(genTestResp(200, `{"ok":true,"result":{}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetUserProfilePhotosParams{ + UserID: 42, + } + _, err := GetUserProfilePhotos(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_GetUserProfilePhotos_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetUserProfilePhotosParams{ + UserID: 42, + } + _, err := GetUserProfilePhotos(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_GetUserProfilePhotos_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetUserProfilePhotosParams{ + UserID: 42, + } + _, err := GetUserProfilePhotos(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_GetUserProfilePhotos_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetUserProfilePhotosParams{ + UserID: 42, + } + _, err := GetUserProfilePhotos(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_GetUserProfilePhotos_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetUserProfilePhotosParams{ + UserID: 42, + } + _, err := GetUserProfilePhotos(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_GetUserProfilePhotos_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_GetUserProfilePhotos_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := GetUserProfilePhotos(context.Background(), bot, &GetUserProfilePhotosParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_GetUserProfilePhotos_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_GetUserProfilePhotos_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetUserProfilePhotosParams{ + UserID: 42, + } + _, err := GetUserProfilePhotos(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_GetUserProfilePhotos_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_GetUserProfilePhotos_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetUserProfilePhotosParams{ + UserID: 42, + } + _, err := GetUserProfilePhotos(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_GetUserProfileAudios_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/getUserProfileAudios") + })).Return(genTestResp(200, `{"ok":true,"result":{}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetUserProfileAudiosParams{ + UserID: 42, + } + _, err := GetUserProfileAudios(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_GetUserProfileAudios_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetUserProfileAudiosParams{ + UserID: 42, + } + _, err := GetUserProfileAudios(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_GetUserProfileAudios_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetUserProfileAudiosParams{ + UserID: 42, + } + _, err := GetUserProfileAudios(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_GetUserProfileAudios_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetUserProfileAudiosParams{ + UserID: 42, + } + _, err := GetUserProfileAudios(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_GetUserProfileAudios_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetUserProfileAudiosParams{ + UserID: 42, + } + _, err := GetUserProfileAudios(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_GetUserProfileAudios_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_GetUserProfileAudios_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := GetUserProfileAudios(context.Background(), bot, &GetUserProfileAudiosParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_GetUserProfileAudios_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_GetUserProfileAudios_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetUserProfileAudiosParams{ + UserID: 42, + } + _, err := GetUserProfileAudios(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_GetUserProfileAudios_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_GetUserProfileAudios_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetUserProfileAudiosParams{ + UserID: 42, + } + _, err := GetUserProfileAudios(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_SetUserEmojiStatus_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/setUserEmojiStatus") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetUserEmojiStatusParams{ + UserID: 42, + } + _, err := SetUserEmojiStatus(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_SetUserEmojiStatus_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetUserEmojiStatusParams{ + UserID: 42, + } + _, err := SetUserEmojiStatus(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_SetUserEmojiStatus_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetUserEmojiStatusParams{ + UserID: 42, + } + _, err := SetUserEmojiStatus(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_SetUserEmojiStatus_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetUserEmojiStatusParams{ + UserID: 42, + } + _, err := SetUserEmojiStatus(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_SetUserEmojiStatus_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetUserEmojiStatusParams{ + UserID: 42, + } + _, err := SetUserEmojiStatus(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_SetUserEmojiStatus_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_SetUserEmojiStatus_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := SetUserEmojiStatus(context.Background(), bot, &SetUserEmojiStatusParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_SetUserEmojiStatus_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_SetUserEmojiStatus_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetUserEmojiStatusParams{ + UserID: 42, + } + _, err := SetUserEmojiStatus(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_SetUserEmojiStatus_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_SetUserEmojiStatus_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetUserEmojiStatusParams{ + UserID: 42, + } + _, err := SetUserEmojiStatus(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_GetFile_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/getFile") + })).Return(genTestResp(200, `{"ok":true,"result":{}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetFileParams{ + FileID: "test_value", + } + _, err := GetFile(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_GetFile_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetFileParams{ + FileID: "test_value", + } + _, err := GetFile(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_GetFile_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetFileParams{ + FileID: "test_value", + } + _, err := GetFile(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_GetFile_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetFileParams{ + FileID: "test_value", + } + _, err := GetFile(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_GetFile_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetFileParams{ + FileID: "test_value", + } + _, err := GetFile(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_GetFile_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_GetFile_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := GetFile(context.Background(), bot, &GetFileParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_GetFile_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_GetFile_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetFileParams{ + FileID: "test_value", + } + _, err := GetFile(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_GetFile_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_GetFile_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetFileParams{ + FileID: "test_value", + } + _, err := GetFile(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_BanChatMember_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/banChatMember") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &BanChatMemberParams{ + ChatID: ChatIDFromInt(123), + UserID: 42, + } + _, err := BanChatMember(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_BanChatMember_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &BanChatMemberParams{ + ChatID: ChatIDFromInt(123), + UserID: 42, + } + _, err := BanChatMember(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_BanChatMember_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &BanChatMemberParams{ + ChatID: ChatIDFromInt(123), + UserID: 42, + } + _, err := BanChatMember(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_BanChatMember_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &BanChatMemberParams{ + ChatID: ChatIDFromInt(123), + UserID: 42, + } + _, err := BanChatMember(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_BanChatMember_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &BanChatMemberParams{ + ChatID: ChatIDFromInt(123), + UserID: 42, + } + _, err := BanChatMember(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_BanChatMember_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_BanChatMember_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := BanChatMember(context.Background(), bot, &BanChatMemberParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_BanChatMember_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_BanChatMember_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &BanChatMemberParams{ + ChatID: ChatIDFromInt(123), + UserID: 42, + } + _, err := BanChatMember(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_BanChatMember_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_BanChatMember_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &BanChatMemberParams{ + ChatID: ChatIDFromInt(123), + UserID: 42, + } + _, err := BanChatMember(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_UnbanChatMember_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/unbanChatMember") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &UnbanChatMemberParams{ + ChatID: ChatIDFromInt(123), + UserID: 42, + } + _, err := UnbanChatMember(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_UnbanChatMember_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &UnbanChatMemberParams{ + ChatID: ChatIDFromInt(123), + UserID: 42, + } + _, err := UnbanChatMember(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_UnbanChatMember_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &UnbanChatMemberParams{ + ChatID: ChatIDFromInt(123), + UserID: 42, + } + _, err := UnbanChatMember(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_UnbanChatMember_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &UnbanChatMemberParams{ + ChatID: ChatIDFromInt(123), + UserID: 42, + } + _, err := UnbanChatMember(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_UnbanChatMember_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &UnbanChatMemberParams{ + ChatID: ChatIDFromInt(123), + UserID: 42, + } + _, err := UnbanChatMember(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_UnbanChatMember_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_UnbanChatMember_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := UnbanChatMember(context.Background(), bot, &UnbanChatMemberParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_UnbanChatMember_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_UnbanChatMember_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &UnbanChatMemberParams{ + ChatID: ChatIDFromInt(123), + UserID: 42, + } + _, err := UnbanChatMember(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_UnbanChatMember_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_UnbanChatMember_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &UnbanChatMemberParams{ + ChatID: ChatIDFromInt(123), + UserID: 42, + } + _, err := UnbanChatMember(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_RestrictChatMember_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/restrictChatMember") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &RestrictChatMemberParams{ + ChatID: ChatIDFromInt(123), + UserID: 42, + Permissions: ChatPermissions{}, + } + _, err := RestrictChatMember(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_RestrictChatMember_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &RestrictChatMemberParams{ + ChatID: ChatIDFromInt(123), + UserID: 42, + Permissions: ChatPermissions{}, + } + _, err := RestrictChatMember(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_RestrictChatMember_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &RestrictChatMemberParams{ + ChatID: ChatIDFromInt(123), + UserID: 42, + Permissions: ChatPermissions{}, + } + _, err := RestrictChatMember(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_RestrictChatMember_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &RestrictChatMemberParams{ + ChatID: ChatIDFromInt(123), + UserID: 42, + Permissions: ChatPermissions{}, + } + _, err := RestrictChatMember(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_RestrictChatMember_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &RestrictChatMemberParams{ + ChatID: ChatIDFromInt(123), + UserID: 42, + Permissions: ChatPermissions{}, + } + _, err := RestrictChatMember(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_RestrictChatMember_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_RestrictChatMember_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := RestrictChatMember(context.Background(), bot, &RestrictChatMemberParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_RestrictChatMember_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_RestrictChatMember_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &RestrictChatMemberParams{ + ChatID: ChatIDFromInt(123), + UserID: 42, + Permissions: ChatPermissions{}, + } + _, err := RestrictChatMember(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_RestrictChatMember_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_RestrictChatMember_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &RestrictChatMemberParams{ + ChatID: ChatIDFromInt(123), + UserID: 42, + Permissions: ChatPermissions{}, + } + _, err := RestrictChatMember(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_PromoteChatMember_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/promoteChatMember") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &PromoteChatMemberParams{ + ChatID: ChatIDFromInt(123), + UserID: 42, + } + _, err := PromoteChatMember(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_PromoteChatMember_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &PromoteChatMemberParams{ + ChatID: ChatIDFromInt(123), + UserID: 42, + } + _, err := PromoteChatMember(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_PromoteChatMember_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &PromoteChatMemberParams{ + ChatID: ChatIDFromInt(123), + UserID: 42, + } + _, err := PromoteChatMember(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_PromoteChatMember_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &PromoteChatMemberParams{ + ChatID: ChatIDFromInt(123), + UserID: 42, + } + _, err := PromoteChatMember(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_PromoteChatMember_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &PromoteChatMemberParams{ + ChatID: ChatIDFromInt(123), + UserID: 42, + } + _, err := PromoteChatMember(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_PromoteChatMember_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_PromoteChatMember_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := PromoteChatMember(context.Background(), bot, &PromoteChatMemberParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_PromoteChatMember_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_PromoteChatMember_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &PromoteChatMemberParams{ + ChatID: ChatIDFromInt(123), + UserID: 42, + } + _, err := PromoteChatMember(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_PromoteChatMember_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_PromoteChatMember_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &PromoteChatMemberParams{ + ChatID: ChatIDFromInt(123), + UserID: 42, + } + _, err := PromoteChatMember(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_SetChatAdministratorCustomTitle_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/setChatAdministratorCustomTitle") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetChatAdministratorCustomTitleParams{ + ChatID: ChatIDFromInt(123), + UserID: 42, + CustomTitle: "test_value", + } + _, err := SetChatAdministratorCustomTitle(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_SetChatAdministratorCustomTitle_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetChatAdministratorCustomTitleParams{ + ChatID: ChatIDFromInt(123), + UserID: 42, + CustomTitle: "test_value", + } + _, err := SetChatAdministratorCustomTitle(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_SetChatAdministratorCustomTitle_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetChatAdministratorCustomTitleParams{ + ChatID: ChatIDFromInt(123), + UserID: 42, + CustomTitle: "test_value", + } + _, err := SetChatAdministratorCustomTitle(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_SetChatAdministratorCustomTitle_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetChatAdministratorCustomTitleParams{ + ChatID: ChatIDFromInt(123), + UserID: 42, + CustomTitle: "test_value", + } + _, err := SetChatAdministratorCustomTitle(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_SetChatAdministratorCustomTitle_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetChatAdministratorCustomTitleParams{ + ChatID: ChatIDFromInt(123), + UserID: 42, + CustomTitle: "test_value", + } + _, err := SetChatAdministratorCustomTitle(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_SetChatAdministratorCustomTitle_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_SetChatAdministratorCustomTitle_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := SetChatAdministratorCustomTitle(context.Background(), bot, &SetChatAdministratorCustomTitleParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_SetChatAdministratorCustomTitle_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_SetChatAdministratorCustomTitle_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetChatAdministratorCustomTitleParams{ + ChatID: ChatIDFromInt(123), + UserID: 42, + CustomTitle: "test_value", + } + _, err := SetChatAdministratorCustomTitle(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_SetChatAdministratorCustomTitle_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_SetChatAdministratorCustomTitle_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetChatAdministratorCustomTitleParams{ + ChatID: ChatIDFromInt(123), + UserID: 42, + CustomTitle: "test_value", + } + _, err := SetChatAdministratorCustomTitle(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_SetChatMemberTag_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/setChatMemberTag") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetChatMemberTagParams{ + ChatID: ChatIDFromInt(123), + UserID: 42, + } + _, err := SetChatMemberTag(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_SetChatMemberTag_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetChatMemberTagParams{ + ChatID: ChatIDFromInt(123), + UserID: 42, + } + _, err := SetChatMemberTag(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_SetChatMemberTag_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetChatMemberTagParams{ + ChatID: ChatIDFromInt(123), + UserID: 42, + } + _, err := SetChatMemberTag(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_SetChatMemberTag_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetChatMemberTagParams{ + ChatID: ChatIDFromInt(123), + UserID: 42, + } + _, err := SetChatMemberTag(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_SetChatMemberTag_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetChatMemberTagParams{ + ChatID: ChatIDFromInt(123), + UserID: 42, + } + _, err := SetChatMemberTag(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_SetChatMemberTag_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_SetChatMemberTag_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := SetChatMemberTag(context.Background(), bot, &SetChatMemberTagParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_SetChatMemberTag_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_SetChatMemberTag_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetChatMemberTagParams{ + ChatID: ChatIDFromInt(123), + UserID: 42, + } + _, err := SetChatMemberTag(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_SetChatMemberTag_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_SetChatMemberTag_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetChatMemberTagParams{ + ChatID: ChatIDFromInt(123), + UserID: 42, + } + _, err := SetChatMemberTag(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_BanChatSenderChat_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/banChatSenderChat") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &BanChatSenderChatParams{ + ChatID: ChatIDFromInt(123), + SenderChatID: 42, + } + _, err := BanChatSenderChat(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_BanChatSenderChat_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &BanChatSenderChatParams{ + ChatID: ChatIDFromInt(123), + SenderChatID: 42, + } + _, err := BanChatSenderChat(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_BanChatSenderChat_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &BanChatSenderChatParams{ + ChatID: ChatIDFromInt(123), + SenderChatID: 42, + } + _, err := BanChatSenderChat(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_BanChatSenderChat_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &BanChatSenderChatParams{ + ChatID: ChatIDFromInt(123), + SenderChatID: 42, + } + _, err := BanChatSenderChat(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_BanChatSenderChat_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &BanChatSenderChatParams{ + ChatID: ChatIDFromInt(123), + SenderChatID: 42, + } + _, err := BanChatSenderChat(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_BanChatSenderChat_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_BanChatSenderChat_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := BanChatSenderChat(context.Background(), bot, &BanChatSenderChatParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_BanChatSenderChat_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_BanChatSenderChat_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &BanChatSenderChatParams{ + ChatID: ChatIDFromInt(123), + SenderChatID: 42, + } + _, err := BanChatSenderChat(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_BanChatSenderChat_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_BanChatSenderChat_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &BanChatSenderChatParams{ + ChatID: ChatIDFromInt(123), + SenderChatID: 42, + } + _, err := BanChatSenderChat(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_UnbanChatSenderChat_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/unbanChatSenderChat") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &UnbanChatSenderChatParams{ + ChatID: ChatIDFromInt(123), + SenderChatID: 42, + } + _, err := UnbanChatSenderChat(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_UnbanChatSenderChat_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &UnbanChatSenderChatParams{ + ChatID: ChatIDFromInt(123), + SenderChatID: 42, + } + _, err := UnbanChatSenderChat(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_UnbanChatSenderChat_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &UnbanChatSenderChatParams{ + ChatID: ChatIDFromInt(123), + SenderChatID: 42, + } + _, err := UnbanChatSenderChat(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_UnbanChatSenderChat_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &UnbanChatSenderChatParams{ + ChatID: ChatIDFromInt(123), + SenderChatID: 42, + } + _, err := UnbanChatSenderChat(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_UnbanChatSenderChat_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &UnbanChatSenderChatParams{ + ChatID: ChatIDFromInt(123), + SenderChatID: 42, + } + _, err := UnbanChatSenderChat(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_UnbanChatSenderChat_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_UnbanChatSenderChat_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := UnbanChatSenderChat(context.Background(), bot, &UnbanChatSenderChatParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_UnbanChatSenderChat_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_UnbanChatSenderChat_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &UnbanChatSenderChatParams{ + ChatID: ChatIDFromInt(123), + SenderChatID: 42, + } + _, err := UnbanChatSenderChat(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_UnbanChatSenderChat_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_UnbanChatSenderChat_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &UnbanChatSenderChatParams{ + ChatID: ChatIDFromInt(123), + SenderChatID: 42, + } + _, err := UnbanChatSenderChat(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_SetChatPermissions_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/setChatPermissions") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetChatPermissionsParams{ + ChatID: ChatIDFromInt(123), + Permissions: ChatPermissions{}, + } + _, err := SetChatPermissions(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_SetChatPermissions_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetChatPermissionsParams{ + ChatID: ChatIDFromInt(123), + Permissions: ChatPermissions{}, + } + _, err := SetChatPermissions(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_SetChatPermissions_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetChatPermissionsParams{ + ChatID: ChatIDFromInt(123), + Permissions: ChatPermissions{}, + } + _, err := SetChatPermissions(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_SetChatPermissions_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetChatPermissionsParams{ + ChatID: ChatIDFromInt(123), + Permissions: ChatPermissions{}, + } + _, err := SetChatPermissions(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_SetChatPermissions_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetChatPermissionsParams{ + ChatID: ChatIDFromInt(123), + Permissions: ChatPermissions{}, + } + _, err := SetChatPermissions(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_SetChatPermissions_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_SetChatPermissions_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := SetChatPermissions(context.Background(), bot, &SetChatPermissionsParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_SetChatPermissions_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_SetChatPermissions_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetChatPermissionsParams{ + ChatID: ChatIDFromInt(123), + Permissions: ChatPermissions{}, + } + _, err := SetChatPermissions(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_SetChatPermissions_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_SetChatPermissions_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetChatPermissionsParams{ + ChatID: ChatIDFromInt(123), + Permissions: ChatPermissions{}, + } + _, err := SetChatPermissions(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_ExportChatInviteLink_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/exportChatInviteLink") + })).Return(genTestResp(200, `{"ok":true,"result":""}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &ExportChatInviteLinkParams{ + ChatID: ChatIDFromInt(123), + } + _, err := ExportChatInviteLink(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_ExportChatInviteLink_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &ExportChatInviteLinkParams{ + ChatID: ChatIDFromInt(123), + } + _, err := ExportChatInviteLink(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_ExportChatInviteLink_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &ExportChatInviteLinkParams{ + ChatID: ChatIDFromInt(123), + } + _, err := ExportChatInviteLink(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_ExportChatInviteLink_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &ExportChatInviteLinkParams{ + ChatID: ChatIDFromInt(123), + } + _, err := ExportChatInviteLink(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_ExportChatInviteLink_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &ExportChatInviteLinkParams{ + ChatID: ChatIDFromInt(123), + } + _, err := ExportChatInviteLink(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_ExportChatInviteLink_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_ExportChatInviteLink_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := ExportChatInviteLink(context.Background(), bot, &ExportChatInviteLinkParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_ExportChatInviteLink_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_ExportChatInviteLink_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &ExportChatInviteLinkParams{ + ChatID: ChatIDFromInt(123), + } + _, err := ExportChatInviteLink(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_ExportChatInviteLink_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_ExportChatInviteLink_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &ExportChatInviteLinkParams{ + ChatID: ChatIDFromInt(123), + } + _, err := ExportChatInviteLink(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_CreateChatInviteLink_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/createChatInviteLink") + })).Return(genTestResp(200, `{"ok":true,"result":{}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &CreateChatInviteLinkParams{ + ChatID: ChatIDFromInt(123), + } + _, err := CreateChatInviteLink(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_CreateChatInviteLink_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &CreateChatInviteLinkParams{ + ChatID: ChatIDFromInt(123), + } + _, err := CreateChatInviteLink(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_CreateChatInviteLink_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &CreateChatInviteLinkParams{ + ChatID: ChatIDFromInt(123), + } + _, err := CreateChatInviteLink(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_CreateChatInviteLink_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &CreateChatInviteLinkParams{ + ChatID: ChatIDFromInt(123), + } + _, err := CreateChatInviteLink(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_CreateChatInviteLink_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &CreateChatInviteLinkParams{ + ChatID: ChatIDFromInt(123), + } + _, err := CreateChatInviteLink(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_CreateChatInviteLink_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_CreateChatInviteLink_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := CreateChatInviteLink(context.Background(), bot, &CreateChatInviteLinkParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_CreateChatInviteLink_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_CreateChatInviteLink_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &CreateChatInviteLinkParams{ + ChatID: ChatIDFromInt(123), + } + _, err := CreateChatInviteLink(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_CreateChatInviteLink_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_CreateChatInviteLink_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &CreateChatInviteLinkParams{ + ChatID: ChatIDFromInt(123), + } + _, err := CreateChatInviteLink(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_EditChatInviteLink_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/editChatInviteLink") + })).Return(genTestResp(200, `{"ok":true,"result":{}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditChatInviteLinkParams{ + ChatID: ChatIDFromInt(123), + InviteLink: "test_value", + } + _, err := EditChatInviteLink(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_EditChatInviteLink_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditChatInviteLinkParams{ + ChatID: ChatIDFromInt(123), + InviteLink: "test_value", + } + _, err := EditChatInviteLink(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_EditChatInviteLink_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditChatInviteLinkParams{ + ChatID: ChatIDFromInt(123), + InviteLink: "test_value", + } + _, err := EditChatInviteLink(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_EditChatInviteLink_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditChatInviteLinkParams{ + ChatID: ChatIDFromInt(123), + InviteLink: "test_value", + } + _, err := EditChatInviteLink(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_EditChatInviteLink_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditChatInviteLinkParams{ + ChatID: ChatIDFromInt(123), + InviteLink: "test_value", + } + _, err := EditChatInviteLink(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_EditChatInviteLink_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_EditChatInviteLink_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := EditChatInviteLink(context.Background(), bot, &EditChatInviteLinkParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_EditChatInviteLink_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_EditChatInviteLink_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditChatInviteLinkParams{ + ChatID: ChatIDFromInt(123), + InviteLink: "test_value", + } + _, err := EditChatInviteLink(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_EditChatInviteLink_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_EditChatInviteLink_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditChatInviteLinkParams{ + ChatID: ChatIDFromInt(123), + InviteLink: "test_value", + } + _, err := EditChatInviteLink(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_CreateChatSubscriptionInviteLink_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/createChatSubscriptionInviteLink") + })).Return(genTestResp(200, `{"ok":true,"result":{}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &CreateChatSubscriptionInviteLinkParams{ + ChatID: ChatIDFromInt(123), + SubscriptionPeriod: 42, + SubscriptionPrice: 42, + } + _, err := CreateChatSubscriptionInviteLink(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_CreateChatSubscriptionInviteLink_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &CreateChatSubscriptionInviteLinkParams{ + ChatID: ChatIDFromInt(123), + SubscriptionPeriod: 42, + SubscriptionPrice: 42, + } + _, err := CreateChatSubscriptionInviteLink(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_CreateChatSubscriptionInviteLink_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &CreateChatSubscriptionInviteLinkParams{ + ChatID: ChatIDFromInt(123), + SubscriptionPeriod: 42, + SubscriptionPrice: 42, + } + _, err := CreateChatSubscriptionInviteLink(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_CreateChatSubscriptionInviteLink_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &CreateChatSubscriptionInviteLinkParams{ + ChatID: ChatIDFromInt(123), + SubscriptionPeriod: 42, + SubscriptionPrice: 42, + } + _, err := CreateChatSubscriptionInviteLink(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_CreateChatSubscriptionInviteLink_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &CreateChatSubscriptionInviteLinkParams{ + ChatID: ChatIDFromInt(123), + SubscriptionPeriod: 42, + SubscriptionPrice: 42, + } + _, err := CreateChatSubscriptionInviteLink(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_CreateChatSubscriptionInviteLink_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_CreateChatSubscriptionInviteLink_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := CreateChatSubscriptionInviteLink(context.Background(), bot, &CreateChatSubscriptionInviteLinkParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_CreateChatSubscriptionInviteLink_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_CreateChatSubscriptionInviteLink_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &CreateChatSubscriptionInviteLinkParams{ + ChatID: ChatIDFromInt(123), + SubscriptionPeriod: 42, + SubscriptionPrice: 42, + } + _, err := CreateChatSubscriptionInviteLink(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_CreateChatSubscriptionInviteLink_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_CreateChatSubscriptionInviteLink_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &CreateChatSubscriptionInviteLinkParams{ + ChatID: ChatIDFromInt(123), + SubscriptionPeriod: 42, + SubscriptionPrice: 42, + } + _, err := CreateChatSubscriptionInviteLink(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_EditChatSubscriptionInviteLink_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/editChatSubscriptionInviteLink") + })).Return(genTestResp(200, `{"ok":true,"result":{}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditChatSubscriptionInviteLinkParams{ + ChatID: ChatIDFromInt(123), + InviteLink: "test_value", + } + _, err := EditChatSubscriptionInviteLink(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_EditChatSubscriptionInviteLink_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditChatSubscriptionInviteLinkParams{ + ChatID: ChatIDFromInt(123), + InviteLink: "test_value", + } + _, err := EditChatSubscriptionInviteLink(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_EditChatSubscriptionInviteLink_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditChatSubscriptionInviteLinkParams{ + ChatID: ChatIDFromInt(123), + InviteLink: "test_value", + } + _, err := EditChatSubscriptionInviteLink(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_EditChatSubscriptionInviteLink_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditChatSubscriptionInviteLinkParams{ + ChatID: ChatIDFromInt(123), + InviteLink: "test_value", + } + _, err := EditChatSubscriptionInviteLink(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_EditChatSubscriptionInviteLink_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditChatSubscriptionInviteLinkParams{ + ChatID: ChatIDFromInt(123), + InviteLink: "test_value", + } + _, err := EditChatSubscriptionInviteLink(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_EditChatSubscriptionInviteLink_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_EditChatSubscriptionInviteLink_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := EditChatSubscriptionInviteLink(context.Background(), bot, &EditChatSubscriptionInviteLinkParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_EditChatSubscriptionInviteLink_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_EditChatSubscriptionInviteLink_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditChatSubscriptionInviteLinkParams{ + ChatID: ChatIDFromInt(123), + InviteLink: "test_value", + } + _, err := EditChatSubscriptionInviteLink(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_EditChatSubscriptionInviteLink_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_EditChatSubscriptionInviteLink_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditChatSubscriptionInviteLinkParams{ + ChatID: ChatIDFromInt(123), + InviteLink: "test_value", + } + _, err := EditChatSubscriptionInviteLink(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_RevokeChatInviteLink_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/revokeChatInviteLink") + })).Return(genTestResp(200, `{"ok":true,"result":{}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &RevokeChatInviteLinkParams{ + ChatID: ChatIDFromInt(123), + InviteLink: "test_value", + } + _, err := RevokeChatInviteLink(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_RevokeChatInviteLink_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &RevokeChatInviteLinkParams{ + ChatID: ChatIDFromInt(123), + InviteLink: "test_value", + } + _, err := RevokeChatInviteLink(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_RevokeChatInviteLink_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &RevokeChatInviteLinkParams{ + ChatID: ChatIDFromInt(123), + InviteLink: "test_value", + } + _, err := RevokeChatInviteLink(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_RevokeChatInviteLink_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &RevokeChatInviteLinkParams{ + ChatID: ChatIDFromInt(123), + InviteLink: "test_value", + } + _, err := RevokeChatInviteLink(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_RevokeChatInviteLink_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &RevokeChatInviteLinkParams{ + ChatID: ChatIDFromInt(123), + InviteLink: "test_value", + } + _, err := RevokeChatInviteLink(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_RevokeChatInviteLink_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_RevokeChatInviteLink_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := RevokeChatInviteLink(context.Background(), bot, &RevokeChatInviteLinkParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_RevokeChatInviteLink_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_RevokeChatInviteLink_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &RevokeChatInviteLinkParams{ + ChatID: ChatIDFromInt(123), + InviteLink: "test_value", + } + _, err := RevokeChatInviteLink(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_RevokeChatInviteLink_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_RevokeChatInviteLink_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &RevokeChatInviteLinkParams{ + ChatID: ChatIDFromInt(123), + InviteLink: "test_value", + } + _, err := RevokeChatInviteLink(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_ApproveChatJoinRequest_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/approveChatJoinRequest") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &ApproveChatJoinRequestParams{ + ChatID: ChatIDFromInt(123), + UserID: 42, + } + _, err := ApproveChatJoinRequest(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_ApproveChatJoinRequest_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &ApproveChatJoinRequestParams{ + ChatID: ChatIDFromInt(123), + UserID: 42, + } + _, err := ApproveChatJoinRequest(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_ApproveChatJoinRequest_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &ApproveChatJoinRequestParams{ + ChatID: ChatIDFromInt(123), + UserID: 42, + } + _, err := ApproveChatJoinRequest(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_ApproveChatJoinRequest_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &ApproveChatJoinRequestParams{ + ChatID: ChatIDFromInt(123), + UserID: 42, + } + _, err := ApproveChatJoinRequest(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_ApproveChatJoinRequest_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &ApproveChatJoinRequestParams{ + ChatID: ChatIDFromInt(123), + UserID: 42, + } + _, err := ApproveChatJoinRequest(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_ApproveChatJoinRequest_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_ApproveChatJoinRequest_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := ApproveChatJoinRequest(context.Background(), bot, &ApproveChatJoinRequestParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_ApproveChatJoinRequest_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_ApproveChatJoinRequest_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &ApproveChatJoinRequestParams{ + ChatID: ChatIDFromInt(123), + UserID: 42, + } + _, err := ApproveChatJoinRequest(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_ApproveChatJoinRequest_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_ApproveChatJoinRequest_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &ApproveChatJoinRequestParams{ + ChatID: ChatIDFromInt(123), + UserID: 42, + } + _, err := ApproveChatJoinRequest(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_DeclineChatJoinRequest_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/declineChatJoinRequest") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeclineChatJoinRequestParams{ + ChatID: ChatIDFromInt(123), + UserID: 42, + } + _, err := DeclineChatJoinRequest(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_DeclineChatJoinRequest_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeclineChatJoinRequestParams{ + ChatID: ChatIDFromInt(123), + UserID: 42, + } + _, err := DeclineChatJoinRequest(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_DeclineChatJoinRequest_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeclineChatJoinRequestParams{ + ChatID: ChatIDFromInt(123), + UserID: 42, + } + _, err := DeclineChatJoinRequest(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_DeclineChatJoinRequest_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeclineChatJoinRequestParams{ + ChatID: ChatIDFromInt(123), + UserID: 42, + } + _, err := DeclineChatJoinRequest(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_DeclineChatJoinRequest_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeclineChatJoinRequestParams{ + ChatID: ChatIDFromInt(123), + UserID: 42, + } + _, err := DeclineChatJoinRequest(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_DeclineChatJoinRequest_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_DeclineChatJoinRequest_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := DeclineChatJoinRequest(context.Background(), bot, &DeclineChatJoinRequestParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_DeclineChatJoinRequest_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_DeclineChatJoinRequest_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeclineChatJoinRequestParams{ + ChatID: ChatIDFromInt(123), + UserID: 42, + } + _, err := DeclineChatJoinRequest(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_DeclineChatJoinRequest_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_DeclineChatJoinRequest_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeclineChatJoinRequestParams{ + ChatID: ChatIDFromInt(123), + UserID: 42, + } + _, err := DeclineChatJoinRequest(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_SetChatPhoto_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/setChatPhoto") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetChatPhotoParams{ + ChatID: ChatIDFromInt(123), + Photo: &InputFile{PathOrID: "file_id_test"}, + } + _, err := SetChatPhoto(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_SetChatPhoto_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetChatPhotoParams{ + ChatID: ChatIDFromInt(123), + Photo: &InputFile{PathOrID: "file_id_test"}, + } + _, err := SetChatPhoto(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_SetChatPhoto_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetChatPhotoParams{ + ChatID: ChatIDFromInt(123), + Photo: &InputFile{PathOrID: "file_id_test"}, + } + _, err := SetChatPhoto(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_SetChatPhoto_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetChatPhotoParams{ + ChatID: ChatIDFromInt(123), + Photo: &InputFile{PathOrID: "file_id_test"}, + } + _, err := SetChatPhoto(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_SetChatPhoto_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetChatPhotoParams{ + ChatID: ChatIDFromInt(123), + Photo: &InputFile{PathOrID: "file_id_test"}, + } + _, err := SetChatPhoto(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_SetChatPhoto_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_SetChatPhoto_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := SetChatPhoto(context.Background(), bot, &SetChatPhotoParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_SetChatPhoto_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_SetChatPhoto_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetChatPhotoParams{ + ChatID: ChatIDFromInt(123), + Photo: &InputFile{PathOrID: "file_id_test"}, + } + _, err := SetChatPhoto(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_SetChatPhoto_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_SetChatPhoto_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetChatPhotoParams{ + ChatID: ChatIDFromInt(123), + Photo: &InputFile{PathOrID: "file_id_test"}, + } + _, err := SetChatPhoto(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_DeleteChatPhoto_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/deleteChatPhoto") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteChatPhotoParams{ + ChatID: ChatIDFromInt(123), + } + _, err := DeleteChatPhoto(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_DeleteChatPhoto_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteChatPhotoParams{ + ChatID: ChatIDFromInt(123), + } + _, err := DeleteChatPhoto(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_DeleteChatPhoto_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteChatPhotoParams{ + ChatID: ChatIDFromInt(123), + } + _, err := DeleteChatPhoto(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_DeleteChatPhoto_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteChatPhotoParams{ + ChatID: ChatIDFromInt(123), + } + _, err := DeleteChatPhoto(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_DeleteChatPhoto_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteChatPhotoParams{ + ChatID: ChatIDFromInt(123), + } + _, err := DeleteChatPhoto(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_DeleteChatPhoto_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_DeleteChatPhoto_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := DeleteChatPhoto(context.Background(), bot, &DeleteChatPhotoParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_DeleteChatPhoto_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_DeleteChatPhoto_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteChatPhotoParams{ + ChatID: ChatIDFromInt(123), + } + _, err := DeleteChatPhoto(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_DeleteChatPhoto_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_DeleteChatPhoto_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteChatPhotoParams{ + ChatID: ChatIDFromInt(123), + } + _, err := DeleteChatPhoto(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_SetChatTitle_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/setChatTitle") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetChatTitleParams{ + ChatID: ChatIDFromInt(123), + Title: "test_value", + } + _, err := SetChatTitle(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_SetChatTitle_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetChatTitleParams{ + ChatID: ChatIDFromInt(123), + Title: "test_value", + } + _, err := SetChatTitle(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_SetChatTitle_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetChatTitleParams{ + ChatID: ChatIDFromInt(123), + Title: "test_value", + } + _, err := SetChatTitle(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_SetChatTitle_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetChatTitleParams{ + ChatID: ChatIDFromInt(123), + Title: "test_value", + } + _, err := SetChatTitle(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_SetChatTitle_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetChatTitleParams{ + ChatID: ChatIDFromInt(123), + Title: "test_value", + } + _, err := SetChatTitle(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_SetChatTitle_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_SetChatTitle_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := SetChatTitle(context.Background(), bot, &SetChatTitleParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_SetChatTitle_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_SetChatTitle_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetChatTitleParams{ + ChatID: ChatIDFromInt(123), + Title: "test_value", + } + _, err := SetChatTitle(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_SetChatTitle_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_SetChatTitle_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetChatTitleParams{ + ChatID: ChatIDFromInt(123), + Title: "test_value", + } + _, err := SetChatTitle(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_SetChatDescription_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/setChatDescription") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetChatDescriptionParams{ + ChatID: ChatIDFromInt(123), + } + _, err := SetChatDescription(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_SetChatDescription_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetChatDescriptionParams{ + ChatID: ChatIDFromInt(123), + } + _, err := SetChatDescription(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_SetChatDescription_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetChatDescriptionParams{ + ChatID: ChatIDFromInt(123), + } + _, err := SetChatDescription(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_SetChatDescription_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetChatDescriptionParams{ + ChatID: ChatIDFromInt(123), + } + _, err := SetChatDescription(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_SetChatDescription_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetChatDescriptionParams{ + ChatID: ChatIDFromInt(123), + } + _, err := SetChatDescription(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_SetChatDescription_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_SetChatDescription_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := SetChatDescription(context.Background(), bot, &SetChatDescriptionParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_SetChatDescription_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_SetChatDescription_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetChatDescriptionParams{ + ChatID: ChatIDFromInt(123), + } + _, err := SetChatDescription(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_SetChatDescription_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_SetChatDescription_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetChatDescriptionParams{ + ChatID: ChatIDFromInt(123), + } + _, err := SetChatDescription(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_PinChatMessage_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/pinChatMessage") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &PinChatMessageParams{ + ChatID: ChatIDFromInt(123), + MessageID: 42, + } + _, err := PinChatMessage(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_PinChatMessage_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &PinChatMessageParams{ + ChatID: ChatIDFromInt(123), + MessageID: 42, + } + _, err := PinChatMessage(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_PinChatMessage_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &PinChatMessageParams{ + ChatID: ChatIDFromInt(123), + MessageID: 42, + } + _, err := PinChatMessage(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_PinChatMessage_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &PinChatMessageParams{ + ChatID: ChatIDFromInt(123), + MessageID: 42, + } + _, err := PinChatMessage(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_PinChatMessage_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &PinChatMessageParams{ + ChatID: ChatIDFromInt(123), + MessageID: 42, + } + _, err := PinChatMessage(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_PinChatMessage_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_PinChatMessage_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := PinChatMessage(context.Background(), bot, &PinChatMessageParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_PinChatMessage_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_PinChatMessage_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &PinChatMessageParams{ + ChatID: ChatIDFromInt(123), + MessageID: 42, + } + _, err := PinChatMessage(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_PinChatMessage_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_PinChatMessage_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &PinChatMessageParams{ + ChatID: ChatIDFromInt(123), + MessageID: 42, + } + _, err := PinChatMessage(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_UnpinChatMessage_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/unpinChatMessage") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &UnpinChatMessageParams{ + ChatID: ChatIDFromInt(123), + } + _, err := UnpinChatMessage(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_UnpinChatMessage_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &UnpinChatMessageParams{ + ChatID: ChatIDFromInt(123), + } + _, err := UnpinChatMessage(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_UnpinChatMessage_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &UnpinChatMessageParams{ + ChatID: ChatIDFromInt(123), + } + _, err := UnpinChatMessage(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_UnpinChatMessage_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &UnpinChatMessageParams{ + ChatID: ChatIDFromInt(123), + } + _, err := UnpinChatMessage(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_UnpinChatMessage_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &UnpinChatMessageParams{ + ChatID: ChatIDFromInt(123), + } + _, err := UnpinChatMessage(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_UnpinChatMessage_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_UnpinChatMessage_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := UnpinChatMessage(context.Background(), bot, &UnpinChatMessageParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_UnpinChatMessage_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_UnpinChatMessage_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &UnpinChatMessageParams{ + ChatID: ChatIDFromInt(123), + } + _, err := UnpinChatMessage(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_UnpinChatMessage_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_UnpinChatMessage_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &UnpinChatMessageParams{ + ChatID: ChatIDFromInt(123), + } + _, err := UnpinChatMessage(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_UnpinAllChatMessages_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/unpinAllChatMessages") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &UnpinAllChatMessagesParams{ + ChatID: ChatIDFromInt(123), + } + _, err := UnpinAllChatMessages(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_UnpinAllChatMessages_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &UnpinAllChatMessagesParams{ + ChatID: ChatIDFromInt(123), + } + _, err := UnpinAllChatMessages(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_UnpinAllChatMessages_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &UnpinAllChatMessagesParams{ + ChatID: ChatIDFromInt(123), + } + _, err := UnpinAllChatMessages(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_UnpinAllChatMessages_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &UnpinAllChatMessagesParams{ + ChatID: ChatIDFromInt(123), + } + _, err := UnpinAllChatMessages(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_UnpinAllChatMessages_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &UnpinAllChatMessagesParams{ + ChatID: ChatIDFromInt(123), + } + _, err := UnpinAllChatMessages(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_UnpinAllChatMessages_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_UnpinAllChatMessages_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := UnpinAllChatMessages(context.Background(), bot, &UnpinAllChatMessagesParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_UnpinAllChatMessages_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_UnpinAllChatMessages_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &UnpinAllChatMessagesParams{ + ChatID: ChatIDFromInt(123), + } + _, err := UnpinAllChatMessages(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_UnpinAllChatMessages_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_UnpinAllChatMessages_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &UnpinAllChatMessagesParams{ + ChatID: ChatIDFromInt(123), + } + _, err := UnpinAllChatMessages(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_LeaveChat_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/leaveChat") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &LeaveChatParams{ + ChatID: ChatIDFromInt(123), + } + _, err := LeaveChat(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_LeaveChat_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &LeaveChatParams{ + ChatID: ChatIDFromInt(123), + } + _, err := LeaveChat(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_LeaveChat_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &LeaveChatParams{ + ChatID: ChatIDFromInt(123), + } + _, err := LeaveChat(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_LeaveChat_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &LeaveChatParams{ + ChatID: ChatIDFromInt(123), + } + _, err := LeaveChat(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_LeaveChat_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &LeaveChatParams{ + ChatID: ChatIDFromInt(123), + } + _, err := LeaveChat(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_LeaveChat_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_LeaveChat_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := LeaveChat(context.Background(), bot, &LeaveChatParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_LeaveChat_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_LeaveChat_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &LeaveChatParams{ + ChatID: ChatIDFromInt(123), + } + _, err := LeaveChat(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_LeaveChat_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_LeaveChat_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &LeaveChatParams{ + ChatID: ChatIDFromInt(123), + } + _, err := LeaveChat(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_GetChat_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/getChat") + })).Return(genTestResp(200, `{"ok":true,"result":{}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetChatParams{ + ChatID: ChatIDFromInt(123), + } + _, err := GetChat(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_GetChat_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetChatParams{ + ChatID: ChatIDFromInt(123), + } + _, err := GetChat(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_GetChat_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetChatParams{ + ChatID: ChatIDFromInt(123), + } + _, err := GetChat(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_GetChat_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetChatParams{ + ChatID: ChatIDFromInt(123), + } + _, err := GetChat(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_GetChat_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetChatParams{ + ChatID: ChatIDFromInt(123), + } + _, err := GetChat(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_GetChat_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_GetChat_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := GetChat(context.Background(), bot, &GetChatParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_GetChat_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_GetChat_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetChatParams{ + ChatID: ChatIDFromInt(123), + } + _, err := GetChat(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_GetChat_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_GetChat_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetChatParams{ + ChatID: ChatIDFromInt(123), + } + _, err := GetChat(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_GetChatAdministrators_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/getChatAdministrators") + })).Return(genTestResp(200, `{"ok":true,"result":[]}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetChatAdministratorsParams{ + ChatID: ChatIDFromInt(123), + } + _, err := GetChatAdministrators(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_GetChatAdministrators_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetChatAdministratorsParams{ + ChatID: ChatIDFromInt(123), + } + _, err := GetChatAdministrators(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_GetChatAdministrators_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetChatAdministratorsParams{ + ChatID: ChatIDFromInt(123), + } + _, err := GetChatAdministrators(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_GetChatAdministrators_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetChatAdministratorsParams{ + ChatID: ChatIDFromInt(123), + } + _, err := GetChatAdministrators(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_GetChatAdministrators_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetChatAdministratorsParams{ + ChatID: ChatIDFromInt(123), + } + _, err := GetChatAdministrators(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_GetChatAdministrators_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_GetChatAdministrators_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := GetChatAdministrators(context.Background(), bot, &GetChatAdministratorsParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_GetChatAdministrators_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_GetChatAdministrators_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetChatAdministratorsParams{ + ChatID: ChatIDFromInt(123), + } + _, err := GetChatAdministrators(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_GetChatAdministrators_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_GetChatAdministrators_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetChatAdministratorsParams{ + ChatID: ChatIDFromInt(123), + } + _, err := GetChatAdministrators(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_GetChatMemberCount_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/getChatMemberCount") + })).Return(genTestResp(200, `{"ok":true,"result":0}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetChatMemberCountParams{ + ChatID: ChatIDFromInt(123), + } + _, err := GetChatMemberCount(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_GetChatMemberCount_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetChatMemberCountParams{ + ChatID: ChatIDFromInt(123), + } + _, err := GetChatMemberCount(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_GetChatMemberCount_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetChatMemberCountParams{ + ChatID: ChatIDFromInt(123), + } + _, err := GetChatMemberCount(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_GetChatMemberCount_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetChatMemberCountParams{ + ChatID: ChatIDFromInt(123), + } + _, err := GetChatMemberCount(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_GetChatMemberCount_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetChatMemberCountParams{ + ChatID: ChatIDFromInt(123), + } + _, err := GetChatMemberCount(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_GetChatMemberCount_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_GetChatMemberCount_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := GetChatMemberCount(context.Background(), bot, &GetChatMemberCountParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_GetChatMemberCount_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_GetChatMemberCount_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetChatMemberCountParams{ + ChatID: ChatIDFromInt(123), + } + _, err := GetChatMemberCount(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_GetChatMemberCount_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_GetChatMemberCount_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetChatMemberCountParams{ + ChatID: ChatIDFromInt(123), + } + _, err := GetChatMemberCount(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_GetChatMember_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/getChatMember") + })).Return(genTestResp(200, `{"ok":true,"result":{"status":"administrator"}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetChatMemberParams{ + ChatID: ChatIDFromInt(123), + UserID: 42, + } + _, err := GetChatMember(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_GetChatMember_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetChatMemberParams{ + ChatID: ChatIDFromInt(123), + UserID: 42, + } + _, err := GetChatMember(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_GetChatMember_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetChatMemberParams{ + ChatID: ChatIDFromInt(123), + UserID: 42, + } + _, err := GetChatMember(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_GetChatMember_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetChatMemberParams{ + ChatID: ChatIDFromInt(123), + UserID: 42, + } + _, err := GetChatMember(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_GetChatMember_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetChatMemberParams{ + ChatID: ChatIDFromInt(123), + UserID: 42, + } + _, err := GetChatMember(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_GetChatMember_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_GetChatMember_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := GetChatMember(context.Background(), bot, &GetChatMemberParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_GetChatMember_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_GetChatMember_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetChatMemberParams{ + ChatID: ChatIDFromInt(123), + UserID: 42, + } + _, err := GetChatMember(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_GetChatMember_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_GetChatMember_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetChatMemberParams{ + ChatID: ChatIDFromInt(123), + UserID: 42, + } + _, err := GetChatMember(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_GetUserPersonalChatMessages_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/getUserPersonalChatMessages") + })).Return(genTestResp(200, `{"ok":true,"result":[]}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetUserPersonalChatMessagesParams{ + UserID: 42, + Limit: 42, + } + _, err := GetUserPersonalChatMessages(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_GetUserPersonalChatMessages_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetUserPersonalChatMessagesParams{ + UserID: 42, + Limit: 42, + } + _, err := GetUserPersonalChatMessages(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_GetUserPersonalChatMessages_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetUserPersonalChatMessagesParams{ + UserID: 42, + Limit: 42, + } + _, err := GetUserPersonalChatMessages(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_GetUserPersonalChatMessages_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetUserPersonalChatMessagesParams{ + UserID: 42, + Limit: 42, + } + _, err := GetUserPersonalChatMessages(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_GetUserPersonalChatMessages_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetUserPersonalChatMessagesParams{ + UserID: 42, + Limit: 42, + } + _, err := GetUserPersonalChatMessages(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_GetUserPersonalChatMessages_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_GetUserPersonalChatMessages_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := GetUserPersonalChatMessages(context.Background(), bot, &GetUserPersonalChatMessagesParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_GetUserPersonalChatMessages_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_GetUserPersonalChatMessages_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetUserPersonalChatMessagesParams{ + UserID: 42, + Limit: 42, + } + _, err := GetUserPersonalChatMessages(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_GetUserPersonalChatMessages_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_GetUserPersonalChatMessages_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetUserPersonalChatMessagesParams{ + UserID: 42, + Limit: 42, + } + _, err := GetUserPersonalChatMessages(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_SetChatStickerSet_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/setChatStickerSet") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetChatStickerSetParams{ + ChatID: ChatIDFromInt(123), + StickerSetName: "test_value", + } + _, err := SetChatStickerSet(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_SetChatStickerSet_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetChatStickerSetParams{ + ChatID: ChatIDFromInt(123), + StickerSetName: "test_value", + } + _, err := SetChatStickerSet(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_SetChatStickerSet_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetChatStickerSetParams{ + ChatID: ChatIDFromInt(123), + StickerSetName: "test_value", + } + _, err := SetChatStickerSet(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_SetChatStickerSet_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetChatStickerSetParams{ + ChatID: ChatIDFromInt(123), + StickerSetName: "test_value", + } + _, err := SetChatStickerSet(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_SetChatStickerSet_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetChatStickerSetParams{ + ChatID: ChatIDFromInt(123), + StickerSetName: "test_value", + } + _, err := SetChatStickerSet(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_SetChatStickerSet_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_SetChatStickerSet_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := SetChatStickerSet(context.Background(), bot, &SetChatStickerSetParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_SetChatStickerSet_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_SetChatStickerSet_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetChatStickerSetParams{ + ChatID: ChatIDFromInt(123), + StickerSetName: "test_value", + } + _, err := SetChatStickerSet(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_SetChatStickerSet_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_SetChatStickerSet_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetChatStickerSetParams{ + ChatID: ChatIDFromInt(123), + StickerSetName: "test_value", + } + _, err := SetChatStickerSet(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_DeleteChatStickerSet_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/deleteChatStickerSet") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteChatStickerSetParams{ + ChatID: ChatIDFromInt(123), + } + _, err := DeleteChatStickerSet(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_DeleteChatStickerSet_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteChatStickerSetParams{ + ChatID: ChatIDFromInt(123), + } + _, err := DeleteChatStickerSet(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_DeleteChatStickerSet_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteChatStickerSetParams{ + ChatID: ChatIDFromInt(123), + } + _, err := DeleteChatStickerSet(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_DeleteChatStickerSet_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteChatStickerSetParams{ + ChatID: ChatIDFromInt(123), + } + _, err := DeleteChatStickerSet(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_DeleteChatStickerSet_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteChatStickerSetParams{ + ChatID: ChatIDFromInt(123), + } + _, err := DeleteChatStickerSet(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_DeleteChatStickerSet_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_DeleteChatStickerSet_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := DeleteChatStickerSet(context.Background(), bot, &DeleteChatStickerSetParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_DeleteChatStickerSet_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_DeleteChatStickerSet_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteChatStickerSetParams{ + ChatID: ChatIDFromInt(123), + } + _, err := DeleteChatStickerSet(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_DeleteChatStickerSet_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_DeleteChatStickerSet_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteChatStickerSetParams{ + ChatID: ChatIDFromInt(123), + } + _, err := DeleteChatStickerSet(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_GetForumTopicIconStickers_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/getForumTopicIconStickers") + })).Return(genTestResp(200, `{"ok":true,"result":[]}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + _, err := GetForumTopicIconStickers(context.Background(), bot, &GetForumTopicIconStickersParams{}) + require.NoError(t, err) +} + +func Test_GetForumTopicIconStickers_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + _, err := GetForumTopicIconStickers(context.Background(), bot, &GetForumTopicIconStickersParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_GetForumTopicIconStickers_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + _, err := GetForumTopicIconStickers(context.Background(), bot, &GetForumTopicIconStickersParams{}) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_GetForumTopicIconStickers_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + _, err := GetForumTopicIconStickers(context.Background(), bot, &GetForumTopicIconStickersParams{}) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_GetForumTopicIconStickers_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + _, err := GetForumTopicIconStickers(ctx, bot, &GetForumTopicIconStickersParams{}) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_GetForumTopicIconStickers_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_GetForumTopicIconStickers_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := GetForumTopicIconStickers(context.Background(), bot, &GetForumTopicIconStickersParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_GetForumTopicIconStickers_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_GetForumTopicIconStickers_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + _, err := GetForumTopicIconStickers(context.Background(), bot, &GetForumTopicIconStickersParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_GetForumTopicIconStickers_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_GetForumTopicIconStickers_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + _, err := GetForumTopicIconStickers(context.Background(), bot, &GetForumTopicIconStickersParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_CreateForumTopic_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/createForumTopic") + })).Return(genTestResp(200, `{"ok":true,"result":{}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &CreateForumTopicParams{ + ChatID: ChatIDFromInt(123), + Name: "test_value", + } + _, err := CreateForumTopic(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_CreateForumTopic_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &CreateForumTopicParams{ + ChatID: ChatIDFromInt(123), + Name: "test_value", + } + _, err := CreateForumTopic(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_CreateForumTopic_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &CreateForumTopicParams{ + ChatID: ChatIDFromInt(123), + Name: "test_value", + } + _, err := CreateForumTopic(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_CreateForumTopic_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &CreateForumTopicParams{ + ChatID: ChatIDFromInt(123), + Name: "test_value", + } + _, err := CreateForumTopic(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_CreateForumTopic_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &CreateForumTopicParams{ + ChatID: ChatIDFromInt(123), + Name: "test_value", + } + _, err := CreateForumTopic(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_CreateForumTopic_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_CreateForumTopic_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := CreateForumTopic(context.Background(), bot, &CreateForumTopicParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_CreateForumTopic_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_CreateForumTopic_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &CreateForumTopicParams{ + ChatID: ChatIDFromInt(123), + Name: "test_value", + } + _, err := CreateForumTopic(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_CreateForumTopic_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_CreateForumTopic_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &CreateForumTopicParams{ + ChatID: ChatIDFromInt(123), + Name: "test_value", + } + _, err := CreateForumTopic(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_EditForumTopic_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/editForumTopic") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditForumTopicParams{ + ChatID: ChatIDFromInt(123), + MessageThreadID: 42, + } + _, err := EditForumTopic(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_EditForumTopic_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditForumTopicParams{ + ChatID: ChatIDFromInt(123), + MessageThreadID: 42, + } + _, err := EditForumTopic(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_EditForumTopic_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditForumTopicParams{ + ChatID: ChatIDFromInt(123), + MessageThreadID: 42, + } + _, err := EditForumTopic(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_EditForumTopic_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditForumTopicParams{ + ChatID: ChatIDFromInt(123), + MessageThreadID: 42, + } + _, err := EditForumTopic(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_EditForumTopic_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditForumTopicParams{ + ChatID: ChatIDFromInt(123), + MessageThreadID: 42, + } + _, err := EditForumTopic(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_EditForumTopic_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_EditForumTopic_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := EditForumTopic(context.Background(), bot, &EditForumTopicParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_EditForumTopic_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_EditForumTopic_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditForumTopicParams{ + ChatID: ChatIDFromInt(123), + MessageThreadID: 42, + } + _, err := EditForumTopic(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_EditForumTopic_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_EditForumTopic_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditForumTopicParams{ + ChatID: ChatIDFromInt(123), + MessageThreadID: 42, + } + _, err := EditForumTopic(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_CloseForumTopic_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/closeForumTopic") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &CloseForumTopicParams{ + ChatID: ChatIDFromInt(123), + MessageThreadID: 42, + } + _, err := CloseForumTopic(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_CloseForumTopic_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &CloseForumTopicParams{ + ChatID: ChatIDFromInt(123), + MessageThreadID: 42, + } + _, err := CloseForumTopic(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_CloseForumTopic_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &CloseForumTopicParams{ + ChatID: ChatIDFromInt(123), + MessageThreadID: 42, + } + _, err := CloseForumTopic(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_CloseForumTopic_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &CloseForumTopicParams{ + ChatID: ChatIDFromInt(123), + MessageThreadID: 42, + } + _, err := CloseForumTopic(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_CloseForumTopic_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &CloseForumTopicParams{ + ChatID: ChatIDFromInt(123), + MessageThreadID: 42, + } + _, err := CloseForumTopic(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_CloseForumTopic_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_CloseForumTopic_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := CloseForumTopic(context.Background(), bot, &CloseForumTopicParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_CloseForumTopic_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_CloseForumTopic_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &CloseForumTopicParams{ + ChatID: ChatIDFromInt(123), + MessageThreadID: 42, + } + _, err := CloseForumTopic(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_CloseForumTopic_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_CloseForumTopic_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &CloseForumTopicParams{ + ChatID: ChatIDFromInt(123), + MessageThreadID: 42, + } + _, err := CloseForumTopic(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_ReopenForumTopic_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/reopenForumTopic") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &ReopenForumTopicParams{ + ChatID: ChatIDFromInt(123), + MessageThreadID: 42, + } + _, err := ReopenForumTopic(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_ReopenForumTopic_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &ReopenForumTopicParams{ + ChatID: ChatIDFromInt(123), + MessageThreadID: 42, + } + _, err := ReopenForumTopic(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_ReopenForumTopic_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &ReopenForumTopicParams{ + ChatID: ChatIDFromInt(123), + MessageThreadID: 42, + } + _, err := ReopenForumTopic(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_ReopenForumTopic_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &ReopenForumTopicParams{ + ChatID: ChatIDFromInt(123), + MessageThreadID: 42, + } + _, err := ReopenForumTopic(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_ReopenForumTopic_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &ReopenForumTopicParams{ + ChatID: ChatIDFromInt(123), + MessageThreadID: 42, + } + _, err := ReopenForumTopic(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_ReopenForumTopic_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_ReopenForumTopic_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := ReopenForumTopic(context.Background(), bot, &ReopenForumTopicParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_ReopenForumTopic_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_ReopenForumTopic_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &ReopenForumTopicParams{ + ChatID: ChatIDFromInt(123), + MessageThreadID: 42, + } + _, err := ReopenForumTopic(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_ReopenForumTopic_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_ReopenForumTopic_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &ReopenForumTopicParams{ + ChatID: ChatIDFromInt(123), + MessageThreadID: 42, + } + _, err := ReopenForumTopic(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_DeleteForumTopic_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/deleteForumTopic") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteForumTopicParams{ + ChatID: ChatIDFromInt(123), + MessageThreadID: 42, + } + _, err := DeleteForumTopic(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_DeleteForumTopic_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteForumTopicParams{ + ChatID: ChatIDFromInt(123), + MessageThreadID: 42, + } + _, err := DeleteForumTopic(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_DeleteForumTopic_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteForumTopicParams{ + ChatID: ChatIDFromInt(123), + MessageThreadID: 42, + } + _, err := DeleteForumTopic(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_DeleteForumTopic_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteForumTopicParams{ + ChatID: ChatIDFromInt(123), + MessageThreadID: 42, + } + _, err := DeleteForumTopic(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_DeleteForumTopic_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteForumTopicParams{ + ChatID: ChatIDFromInt(123), + MessageThreadID: 42, + } + _, err := DeleteForumTopic(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_DeleteForumTopic_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_DeleteForumTopic_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := DeleteForumTopic(context.Background(), bot, &DeleteForumTopicParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_DeleteForumTopic_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_DeleteForumTopic_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteForumTopicParams{ + ChatID: ChatIDFromInt(123), + MessageThreadID: 42, + } + _, err := DeleteForumTopic(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_DeleteForumTopic_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_DeleteForumTopic_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteForumTopicParams{ + ChatID: ChatIDFromInt(123), + MessageThreadID: 42, + } + _, err := DeleteForumTopic(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_UnpinAllForumTopicMessages_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/unpinAllForumTopicMessages") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &UnpinAllForumTopicMessagesParams{ + ChatID: ChatIDFromInt(123), + MessageThreadID: 42, + } + _, err := UnpinAllForumTopicMessages(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_UnpinAllForumTopicMessages_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &UnpinAllForumTopicMessagesParams{ + ChatID: ChatIDFromInt(123), + MessageThreadID: 42, + } + _, err := UnpinAllForumTopicMessages(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_UnpinAllForumTopicMessages_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &UnpinAllForumTopicMessagesParams{ + ChatID: ChatIDFromInt(123), + MessageThreadID: 42, + } + _, err := UnpinAllForumTopicMessages(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_UnpinAllForumTopicMessages_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &UnpinAllForumTopicMessagesParams{ + ChatID: ChatIDFromInt(123), + MessageThreadID: 42, + } + _, err := UnpinAllForumTopicMessages(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_UnpinAllForumTopicMessages_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &UnpinAllForumTopicMessagesParams{ + ChatID: ChatIDFromInt(123), + MessageThreadID: 42, + } + _, err := UnpinAllForumTopicMessages(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_UnpinAllForumTopicMessages_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_UnpinAllForumTopicMessages_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := UnpinAllForumTopicMessages(context.Background(), bot, &UnpinAllForumTopicMessagesParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_UnpinAllForumTopicMessages_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_UnpinAllForumTopicMessages_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &UnpinAllForumTopicMessagesParams{ + ChatID: ChatIDFromInt(123), + MessageThreadID: 42, + } + _, err := UnpinAllForumTopicMessages(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_UnpinAllForumTopicMessages_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_UnpinAllForumTopicMessages_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &UnpinAllForumTopicMessagesParams{ + ChatID: ChatIDFromInt(123), + MessageThreadID: 42, + } + _, err := UnpinAllForumTopicMessages(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_EditGeneralForumTopic_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/editGeneralForumTopic") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditGeneralForumTopicParams{ + ChatID: ChatIDFromInt(123), + Name: "test_value", + } + _, err := EditGeneralForumTopic(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_EditGeneralForumTopic_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditGeneralForumTopicParams{ + ChatID: ChatIDFromInt(123), + Name: "test_value", + } + _, err := EditGeneralForumTopic(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_EditGeneralForumTopic_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditGeneralForumTopicParams{ + ChatID: ChatIDFromInt(123), + Name: "test_value", + } + _, err := EditGeneralForumTopic(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_EditGeneralForumTopic_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditGeneralForumTopicParams{ + ChatID: ChatIDFromInt(123), + Name: "test_value", + } + _, err := EditGeneralForumTopic(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_EditGeneralForumTopic_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditGeneralForumTopicParams{ + ChatID: ChatIDFromInt(123), + Name: "test_value", + } + _, err := EditGeneralForumTopic(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_EditGeneralForumTopic_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_EditGeneralForumTopic_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := EditGeneralForumTopic(context.Background(), bot, &EditGeneralForumTopicParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_EditGeneralForumTopic_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_EditGeneralForumTopic_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditGeneralForumTopicParams{ + ChatID: ChatIDFromInt(123), + Name: "test_value", + } + _, err := EditGeneralForumTopic(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_EditGeneralForumTopic_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_EditGeneralForumTopic_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditGeneralForumTopicParams{ + ChatID: ChatIDFromInt(123), + Name: "test_value", + } + _, err := EditGeneralForumTopic(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_CloseGeneralForumTopic_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/closeGeneralForumTopic") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &CloseGeneralForumTopicParams{ + ChatID: ChatIDFromInt(123), + } + _, err := CloseGeneralForumTopic(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_CloseGeneralForumTopic_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &CloseGeneralForumTopicParams{ + ChatID: ChatIDFromInt(123), + } + _, err := CloseGeneralForumTopic(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_CloseGeneralForumTopic_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &CloseGeneralForumTopicParams{ + ChatID: ChatIDFromInt(123), + } + _, err := CloseGeneralForumTopic(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_CloseGeneralForumTopic_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &CloseGeneralForumTopicParams{ + ChatID: ChatIDFromInt(123), + } + _, err := CloseGeneralForumTopic(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_CloseGeneralForumTopic_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &CloseGeneralForumTopicParams{ + ChatID: ChatIDFromInt(123), + } + _, err := CloseGeneralForumTopic(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_CloseGeneralForumTopic_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_CloseGeneralForumTopic_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := CloseGeneralForumTopic(context.Background(), bot, &CloseGeneralForumTopicParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_CloseGeneralForumTopic_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_CloseGeneralForumTopic_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &CloseGeneralForumTopicParams{ + ChatID: ChatIDFromInt(123), + } + _, err := CloseGeneralForumTopic(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_CloseGeneralForumTopic_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_CloseGeneralForumTopic_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &CloseGeneralForumTopicParams{ + ChatID: ChatIDFromInt(123), + } + _, err := CloseGeneralForumTopic(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_ReopenGeneralForumTopic_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/reopenGeneralForumTopic") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &ReopenGeneralForumTopicParams{ + ChatID: ChatIDFromInt(123), + } + _, err := ReopenGeneralForumTopic(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_ReopenGeneralForumTopic_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &ReopenGeneralForumTopicParams{ + ChatID: ChatIDFromInt(123), + } + _, err := ReopenGeneralForumTopic(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_ReopenGeneralForumTopic_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &ReopenGeneralForumTopicParams{ + ChatID: ChatIDFromInt(123), + } + _, err := ReopenGeneralForumTopic(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_ReopenGeneralForumTopic_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &ReopenGeneralForumTopicParams{ + ChatID: ChatIDFromInt(123), + } + _, err := ReopenGeneralForumTopic(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_ReopenGeneralForumTopic_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &ReopenGeneralForumTopicParams{ + ChatID: ChatIDFromInt(123), + } + _, err := ReopenGeneralForumTopic(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_ReopenGeneralForumTopic_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_ReopenGeneralForumTopic_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := ReopenGeneralForumTopic(context.Background(), bot, &ReopenGeneralForumTopicParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_ReopenGeneralForumTopic_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_ReopenGeneralForumTopic_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &ReopenGeneralForumTopicParams{ + ChatID: ChatIDFromInt(123), + } + _, err := ReopenGeneralForumTopic(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_ReopenGeneralForumTopic_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_ReopenGeneralForumTopic_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &ReopenGeneralForumTopicParams{ + ChatID: ChatIDFromInt(123), + } + _, err := ReopenGeneralForumTopic(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_HideGeneralForumTopic_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/hideGeneralForumTopic") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &HideGeneralForumTopicParams{ + ChatID: ChatIDFromInt(123), + } + _, err := HideGeneralForumTopic(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_HideGeneralForumTopic_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &HideGeneralForumTopicParams{ + ChatID: ChatIDFromInt(123), + } + _, err := HideGeneralForumTopic(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_HideGeneralForumTopic_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &HideGeneralForumTopicParams{ + ChatID: ChatIDFromInt(123), + } + _, err := HideGeneralForumTopic(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_HideGeneralForumTopic_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &HideGeneralForumTopicParams{ + ChatID: ChatIDFromInt(123), + } + _, err := HideGeneralForumTopic(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_HideGeneralForumTopic_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &HideGeneralForumTopicParams{ + ChatID: ChatIDFromInt(123), + } + _, err := HideGeneralForumTopic(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_HideGeneralForumTopic_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_HideGeneralForumTopic_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := HideGeneralForumTopic(context.Background(), bot, &HideGeneralForumTopicParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_HideGeneralForumTopic_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_HideGeneralForumTopic_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &HideGeneralForumTopicParams{ + ChatID: ChatIDFromInt(123), + } + _, err := HideGeneralForumTopic(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_HideGeneralForumTopic_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_HideGeneralForumTopic_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &HideGeneralForumTopicParams{ + ChatID: ChatIDFromInt(123), + } + _, err := HideGeneralForumTopic(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_UnhideGeneralForumTopic_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/unhideGeneralForumTopic") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &UnhideGeneralForumTopicParams{ + ChatID: ChatIDFromInt(123), + } + _, err := UnhideGeneralForumTopic(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_UnhideGeneralForumTopic_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &UnhideGeneralForumTopicParams{ + ChatID: ChatIDFromInt(123), + } + _, err := UnhideGeneralForumTopic(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_UnhideGeneralForumTopic_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &UnhideGeneralForumTopicParams{ + ChatID: ChatIDFromInt(123), + } + _, err := UnhideGeneralForumTopic(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_UnhideGeneralForumTopic_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &UnhideGeneralForumTopicParams{ + ChatID: ChatIDFromInt(123), + } + _, err := UnhideGeneralForumTopic(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_UnhideGeneralForumTopic_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &UnhideGeneralForumTopicParams{ + ChatID: ChatIDFromInt(123), + } + _, err := UnhideGeneralForumTopic(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_UnhideGeneralForumTopic_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_UnhideGeneralForumTopic_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := UnhideGeneralForumTopic(context.Background(), bot, &UnhideGeneralForumTopicParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_UnhideGeneralForumTopic_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_UnhideGeneralForumTopic_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &UnhideGeneralForumTopicParams{ + ChatID: ChatIDFromInt(123), + } + _, err := UnhideGeneralForumTopic(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_UnhideGeneralForumTopic_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_UnhideGeneralForumTopic_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &UnhideGeneralForumTopicParams{ + ChatID: ChatIDFromInt(123), + } + _, err := UnhideGeneralForumTopic(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_UnpinAllGeneralForumTopicMessages_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/unpinAllGeneralForumTopicMessages") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &UnpinAllGeneralForumTopicMessagesParams{ + ChatID: ChatIDFromInt(123), + } + _, err := UnpinAllGeneralForumTopicMessages(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_UnpinAllGeneralForumTopicMessages_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &UnpinAllGeneralForumTopicMessagesParams{ + ChatID: ChatIDFromInt(123), + } + _, err := UnpinAllGeneralForumTopicMessages(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_UnpinAllGeneralForumTopicMessages_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &UnpinAllGeneralForumTopicMessagesParams{ + ChatID: ChatIDFromInt(123), + } + _, err := UnpinAllGeneralForumTopicMessages(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_UnpinAllGeneralForumTopicMessages_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &UnpinAllGeneralForumTopicMessagesParams{ + ChatID: ChatIDFromInt(123), + } + _, err := UnpinAllGeneralForumTopicMessages(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_UnpinAllGeneralForumTopicMessages_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &UnpinAllGeneralForumTopicMessagesParams{ + ChatID: ChatIDFromInt(123), + } + _, err := UnpinAllGeneralForumTopicMessages(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_UnpinAllGeneralForumTopicMessages_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_UnpinAllGeneralForumTopicMessages_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := UnpinAllGeneralForumTopicMessages(context.Background(), bot, &UnpinAllGeneralForumTopicMessagesParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_UnpinAllGeneralForumTopicMessages_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_UnpinAllGeneralForumTopicMessages_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &UnpinAllGeneralForumTopicMessagesParams{ + ChatID: ChatIDFromInt(123), + } + _, err := UnpinAllGeneralForumTopicMessages(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_UnpinAllGeneralForumTopicMessages_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_UnpinAllGeneralForumTopicMessages_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &UnpinAllGeneralForumTopicMessagesParams{ + ChatID: ChatIDFromInt(123), + } + _, err := UnpinAllGeneralForumTopicMessages(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_AnswerCallbackQuery_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/answerCallbackQuery") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &AnswerCallbackQueryParams{ + CallbackQueryID: "test_value", + } + _, err := AnswerCallbackQuery(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_AnswerCallbackQuery_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &AnswerCallbackQueryParams{ + CallbackQueryID: "test_value", + } + _, err := AnswerCallbackQuery(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_AnswerCallbackQuery_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &AnswerCallbackQueryParams{ + CallbackQueryID: "test_value", + } + _, err := AnswerCallbackQuery(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_AnswerCallbackQuery_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &AnswerCallbackQueryParams{ + CallbackQueryID: "test_value", + } + _, err := AnswerCallbackQuery(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_AnswerCallbackQuery_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &AnswerCallbackQueryParams{ + CallbackQueryID: "test_value", + } + _, err := AnswerCallbackQuery(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_AnswerCallbackQuery_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_AnswerCallbackQuery_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := AnswerCallbackQuery(context.Background(), bot, &AnswerCallbackQueryParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_AnswerCallbackQuery_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_AnswerCallbackQuery_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &AnswerCallbackQueryParams{ + CallbackQueryID: "test_value", + } + _, err := AnswerCallbackQuery(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_AnswerCallbackQuery_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_AnswerCallbackQuery_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &AnswerCallbackQueryParams{ + CallbackQueryID: "test_value", + } + _, err := AnswerCallbackQuery(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_AnswerGuestQuery_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/answerGuestQuery") + })).Return(genTestResp(200, `{"ok":true,"result":{}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &AnswerGuestQueryParams{ + GuestQueryID: "test_value", + Result: nil, + } + _, err := AnswerGuestQuery(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_AnswerGuestQuery_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &AnswerGuestQueryParams{ + GuestQueryID: "test_value", + Result: nil, + } + _, err := AnswerGuestQuery(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_AnswerGuestQuery_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &AnswerGuestQueryParams{ + GuestQueryID: "test_value", + Result: nil, + } + _, err := AnswerGuestQuery(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_AnswerGuestQuery_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &AnswerGuestQueryParams{ + GuestQueryID: "test_value", + Result: nil, + } + _, err := AnswerGuestQuery(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_AnswerGuestQuery_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &AnswerGuestQueryParams{ + GuestQueryID: "test_value", + Result: nil, + } + _, err := AnswerGuestQuery(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_AnswerGuestQuery_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_AnswerGuestQuery_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := AnswerGuestQuery(context.Background(), bot, &AnswerGuestQueryParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_AnswerGuestQuery_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_AnswerGuestQuery_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &AnswerGuestQueryParams{ + GuestQueryID: "test_value", + Result: nil, + } + _, err := AnswerGuestQuery(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_AnswerGuestQuery_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_AnswerGuestQuery_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &AnswerGuestQueryParams{ + GuestQueryID: "test_value", + Result: nil, + } + _, err := AnswerGuestQuery(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_GetUserChatBoosts_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/getUserChatBoosts") + })).Return(genTestResp(200, `{"ok":true,"result":{}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetUserChatBoostsParams{ + ChatID: ChatIDFromInt(123), + UserID: 42, + } + _, err := GetUserChatBoosts(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_GetUserChatBoosts_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetUserChatBoostsParams{ + ChatID: ChatIDFromInt(123), + UserID: 42, + } + _, err := GetUserChatBoosts(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_GetUserChatBoosts_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetUserChatBoostsParams{ + ChatID: ChatIDFromInt(123), + UserID: 42, + } + _, err := GetUserChatBoosts(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_GetUserChatBoosts_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetUserChatBoostsParams{ + ChatID: ChatIDFromInt(123), + UserID: 42, + } + _, err := GetUserChatBoosts(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_GetUserChatBoosts_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetUserChatBoostsParams{ + ChatID: ChatIDFromInt(123), + UserID: 42, + } + _, err := GetUserChatBoosts(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_GetUserChatBoosts_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_GetUserChatBoosts_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := GetUserChatBoosts(context.Background(), bot, &GetUserChatBoostsParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_GetUserChatBoosts_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_GetUserChatBoosts_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetUserChatBoostsParams{ + ChatID: ChatIDFromInt(123), + UserID: 42, + } + _, err := GetUserChatBoosts(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_GetUserChatBoosts_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_GetUserChatBoosts_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetUserChatBoostsParams{ + ChatID: ChatIDFromInt(123), + UserID: 42, + } + _, err := GetUserChatBoosts(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_GetBusinessConnection_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/getBusinessConnection") + })).Return(genTestResp(200, `{"ok":true,"result":{}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetBusinessConnectionParams{ + BusinessConnectionID: "test_value", + } + _, err := GetBusinessConnection(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_GetBusinessConnection_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetBusinessConnectionParams{ + BusinessConnectionID: "test_value", + } + _, err := GetBusinessConnection(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_GetBusinessConnection_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetBusinessConnectionParams{ + BusinessConnectionID: "test_value", + } + _, err := GetBusinessConnection(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_GetBusinessConnection_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetBusinessConnectionParams{ + BusinessConnectionID: "test_value", + } + _, err := GetBusinessConnection(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_GetBusinessConnection_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetBusinessConnectionParams{ + BusinessConnectionID: "test_value", + } + _, err := GetBusinessConnection(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_GetBusinessConnection_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_GetBusinessConnection_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := GetBusinessConnection(context.Background(), bot, &GetBusinessConnectionParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_GetBusinessConnection_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_GetBusinessConnection_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetBusinessConnectionParams{ + BusinessConnectionID: "test_value", + } + _, err := GetBusinessConnection(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_GetBusinessConnection_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_GetBusinessConnection_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetBusinessConnectionParams{ + BusinessConnectionID: "test_value", + } + _, err := GetBusinessConnection(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_GetManagedBotToken_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/getManagedBotToken") + })).Return(genTestResp(200, `{"ok":true,"result":""}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetManagedBotTokenParams{ + UserID: 42, + } + _, err := GetManagedBotToken(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_GetManagedBotToken_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetManagedBotTokenParams{ + UserID: 42, + } + _, err := GetManagedBotToken(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_GetManagedBotToken_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetManagedBotTokenParams{ + UserID: 42, + } + _, err := GetManagedBotToken(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_GetManagedBotToken_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetManagedBotTokenParams{ + UserID: 42, + } + _, err := GetManagedBotToken(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_GetManagedBotToken_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetManagedBotTokenParams{ + UserID: 42, + } + _, err := GetManagedBotToken(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_GetManagedBotToken_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_GetManagedBotToken_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := GetManagedBotToken(context.Background(), bot, &GetManagedBotTokenParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_GetManagedBotToken_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_GetManagedBotToken_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetManagedBotTokenParams{ + UserID: 42, + } + _, err := GetManagedBotToken(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_GetManagedBotToken_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_GetManagedBotToken_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetManagedBotTokenParams{ + UserID: 42, + } + _, err := GetManagedBotToken(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_ReplaceManagedBotToken_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/replaceManagedBotToken") + })).Return(genTestResp(200, `{"ok":true,"result":""}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &ReplaceManagedBotTokenParams{ + UserID: 42, + } + _, err := ReplaceManagedBotToken(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_ReplaceManagedBotToken_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &ReplaceManagedBotTokenParams{ + UserID: 42, + } + _, err := ReplaceManagedBotToken(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_ReplaceManagedBotToken_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &ReplaceManagedBotTokenParams{ + UserID: 42, + } + _, err := ReplaceManagedBotToken(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_ReplaceManagedBotToken_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &ReplaceManagedBotTokenParams{ + UserID: 42, + } + _, err := ReplaceManagedBotToken(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_ReplaceManagedBotToken_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &ReplaceManagedBotTokenParams{ + UserID: 42, + } + _, err := ReplaceManagedBotToken(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_ReplaceManagedBotToken_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_ReplaceManagedBotToken_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := ReplaceManagedBotToken(context.Background(), bot, &ReplaceManagedBotTokenParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_ReplaceManagedBotToken_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_ReplaceManagedBotToken_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &ReplaceManagedBotTokenParams{ + UserID: 42, + } + _, err := ReplaceManagedBotToken(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_ReplaceManagedBotToken_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_ReplaceManagedBotToken_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &ReplaceManagedBotTokenParams{ + UserID: 42, + } + _, err := ReplaceManagedBotToken(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_GetManagedBotAccessSettings_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/getManagedBotAccessSettings") + })).Return(genTestResp(200, `{"ok":true,"result":{}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetManagedBotAccessSettingsParams{ + UserID: 42, + } + _, err := GetManagedBotAccessSettings(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_GetManagedBotAccessSettings_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetManagedBotAccessSettingsParams{ + UserID: 42, + } + _, err := GetManagedBotAccessSettings(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_GetManagedBotAccessSettings_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetManagedBotAccessSettingsParams{ + UserID: 42, + } + _, err := GetManagedBotAccessSettings(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_GetManagedBotAccessSettings_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetManagedBotAccessSettingsParams{ + UserID: 42, + } + _, err := GetManagedBotAccessSettings(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_GetManagedBotAccessSettings_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetManagedBotAccessSettingsParams{ + UserID: 42, + } + _, err := GetManagedBotAccessSettings(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_GetManagedBotAccessSettings_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_GetManagedBotAccessSettings_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := GetManagedBotAccessSettings(context.Background(), bot, &GetManagedBotAccessSettingsParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_GetManagedBotAccessSettings_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_GetManagedBotAccessSettings_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetManagedBotAccessSettingsParams{ + UserID: 42, + } + _, err := GetManagedBotAccessSettings(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_GetManagedBotAccessSettings_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_GetManagedBotAccessSettings_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetManagedBotAccessSettingsParams{ + UserID: 42, + } + _, err := GetManagedBotAccessSettings(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_SetManagedBotAccessSettings_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/setManagedBotAccessSettings") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetManagedBotAccessSettingsParams{ + UserID: 42, + IsAccessRestricted: true, + } + _, err := SetManagedBotAccessSettings(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_SetManagedBotAccessSettings_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetManagedBotAccessSettingsParams{ + UserID: 42, + IsAccessRestricted: true, + } + _, err := SetManagedBotAccessSettings(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_SetManagedBotAccessSettings_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetManagedBotAccessSettingsParams{ + UserID: 42, + IsAccessRestricted: true, + } + _, err := SetManagedBotAccessSettings(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_SetManagedBotAccessSettings_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetManagedBotAccessSettingsParams{ + UserID: 42, + IsAccessRestricted: true, + } + _, err := SetManagedBotAccessSettings(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_SetManagedBotAccessSettings_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetManagedBotAccessSettingsParams{ + UserID: 42, + IsAccessRestricted: true, + } + _, err := SetManagedBotAccessSettings(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_SetManagedBotAccessSettings_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_SetManagedBotAccessSettings_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := SetManagedBotAccessSettings(context.Background(), bot, &SetManagedBotAccessSettingsParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_SetManagedBotAccessSettings_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_SetManagedBotAccessSettings_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetManagedBotAccessSettingsParams{ + UserID: 42, + IsAccessRestricted: true, + } + _, err := SetManagedBotAccessSettings(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_SetManagedBotAccessSettings_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_SetManagedBotAccessSettings_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetManagedBotAccessSettingsParams{ + UserID: 42, + IsAccessRestricted: true, + } + _, err := SetManagedBotAccessSettings(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_SetMyCommands_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/setMyCommands") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetMyCommandsParams{ + Commands: nil, + } + _, err := SetMyCommands(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_SetMyCommands_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetMyCommandsParams{ + Commands: nil, + } + _, err := SetMyCommands(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_SetMyCommands_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetMyCommandsParams{ + Commands: nil, + } + _, err := SetMyCommands(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_SetMyCommands_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetMyCommandsParams{ + Commands: nil, + } + _, err := SetMyCommands(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_SetMyCommands_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetMyCommandsParams{ + Commands: nil, + } + _, err := SetMyCommands(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_SetMyCommands_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_SetMyCommands_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := SetMyCommands(context.Background(), bot, &SetMyCommandsParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_SetMyCommands_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_SetMyCommands_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetMyCommandsParams{ + Commands: nil, + } + _, err := SetMyCommands(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_SetMyCommands_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_SetMyCommands_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetMyCommandsParams{ + Commands: nil, + } + _, err := SetMyCommands(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_DeleteMyCommands_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/deleteMyCommands") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteMyCommandsParams{} + _, err := DeleteMyCommands(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_DeleteMyCommands_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteMyCommandsParams{} + _, err := DeleteMyCommands(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_DeleteMyCommands_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteMyCommandsParams{} + _, err := DeleteMyCommands(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_DeleteMyCommands_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteMyCommandsParams{} + _, err := DeleteMyCommands(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_DeleteMyCommands_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteMyCommandsParams{} + _, err := DeleteMyCommands(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_DeleteMyCommands_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_DeleteMyCommands_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := DeleteMyCommands(context.Background(), bot, &DeleteMyCommandsParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_DeleteMyCommands_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_DeleteMyCommands_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteMyCommandsParams{} + _, err := DeleteMyCommands(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_DeleteMyCommands_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_DeleteMyCommands_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteMyCommandsParams{} + _, err := DeleteMyCommands(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_GetMyCommands_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/getMyCommands") + })).Return(genTestResp(200, `{"ok":true,"result":[]}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetMyCommandsParams{} + _, err := GetMyCommands(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_GetMyCommands_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetMyCommandsParams{} + _, err := GetMyCommands(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_GetMyCommands_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetMyCommandsParams{} + _, err := GetMyCommands(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_GetMyCommands_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetMyCommandsParams{} + _, err := GetMyCommands(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_GetMyCommands_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetMyCommandsParams{} + _, err := GetMyCommands(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_GetMyCommands_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_GetMyCommands_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := GetMyCommands(context.Background(), bot, &GetMyCommandsParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_GetMyCommands_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_GetMyCommands_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetMyCommandsParams{} + _, err := GetMyCommands(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_GetMyCommands_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_GetMyCommands_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetMyCommandsParams{} + _, err := GetMyCommands(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_SetMyName_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/setMyName") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetMyNameParams{} + _, err := SetMyName(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_SetMyName_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetMyNameParams{} + _, err := SetMyName(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_SetMyName_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetMyNameParams{} + _, err := SetMyName(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_SetMyName_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetMyNameParams{} + _, err := SetMyName(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_SetMyName_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetMyNameParams{} + _, err := SetMyName(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_SetMyName_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_SetMyName_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := SetMyName(context.Background(), bot, &SetMyNameParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_SetMyName_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_SetMyName_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetMyNameParams{} + _, err := SetMyName(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_SetMyName_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_SetMyName_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetMyNameParams{} + _, err := SetMyName(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_GetMyName_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/getMyName") + })).Return(genTestResp(200, `{"ok":true,"result":{}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetMyNameParams{} + _, err := GetMyName(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_GetMyName_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetMyNameParams{} + _, err := GetMyName(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_GetMyName_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetMyNameParams{} + _, err := GetMyName(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_GetMyName_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetMyNameParams{} + _, err := GetMyName(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_GetMyName_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetMyNameParams{} + _, err := GetMyName(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_GetMyName_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_GetMyName_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := GetMyName(context.Background(), bot, &GetMyNameParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_GetMyName_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_GetMyName_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetMyNameParams{} + _, err := GetMyName(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_GetMyName_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_GetMyName_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetMyNameParams{} + _, err := GetMyName(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_SetMyDescription_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/setMyDescription") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetMyDescriptionParams{} + _, err := SetMyDescription(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_SetMyDescription_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetMyDescriptionParams{} + _, err := SetMyDescription(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_SetMyDescription_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetMyDescriptionParams{} + _, err := SetMyDescription(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_SetMyDescription_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetMyDescriptionParams{} + _, err := SetMyDescription(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_SetMyDescription_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetMyDescriptionParams{} + _, err := SetMyDescription(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_SetMyDescription_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_SetMyDescription_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := SetMyDescription(context.Background(), bot, &SetMyDescriptionParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_SetMyDescription_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_SetMyDescription_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetMyDescriptionParams{} + _, err := SetMyDescription(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_SetMyDescription_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_SetMyDescription_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetMyDescriptionParams{} + _, err := SetMyDescription(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_GetMyDescription_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/getMyDescription") + })).Return(genTestResp(200, `{"ok":true,"result":{}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetMyDescriptionParams{} + _, err := GetMyDescription(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_GetMyDescription_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetMyDescriptionParams{} + _, err := GetMyDescription(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_GetMyDescription_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetMyDescriptionParams{} + _, err := GetMyDescription(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_GetMyDescription_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetMyDescriptionParams{} + _, err := GetMyDescription(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_GetMyDescription_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetMyDescriptionParams{} + _, err := GetMyDescription(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_GetMyDescription_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_GetMyDescription_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := GetMyDescription(context.Background(), bot, &GetMyDescriptionParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_GetMyDescription_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_GetMyDescription_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetMyDescriptionParams{} + _, err := GetMyDescription(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_GetMyDescription_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_GetMyDescription_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetMyDescriptionParams{} + _, err := GetMyDescription(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_SetMyShortDescription_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/setMyShortDescription") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetMyShortDescriptionParams{} + _, err := SetMyShortDescription(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_SetMyShortDescription_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetMyShortDescriptionParams{} + _, err := SetMyShortDescription(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_SetMyShortDescription_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetMyShortDescriptionParams{} + _, err := SetMyShortDescription(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_SetMyShortDescription_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetMyShortDescriptionParams{} + _, err := SetMyShortDescription(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_SetMyShortDescription_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetMyShortDescriptionParams{} + _, err := SetMyShortDescription(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_SetMyShortDescription_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_SetMyShortDescription_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := SetMyShortDescription(context.Background(), bot, &SetMyShortDescriptionParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_SetMyShortDescription_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_SetMyShortDescription_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetMyShortDescriptionParams{} + _, err := SetMyShortDescription(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_SetMyShortDescription_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_SetMyShortDescription_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetMyShortDescriptionParams{} + _, err := SetMyShortDescription(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_GetMyShortDescription_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/getMyShortDescription") + })).Return(genTestResp(200, `{"ok":true,"result":{}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetMyShortDescriptionParams{} + _, err := GetMyShortDescription(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_GetMyShortDescription_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetMyShortDescriptionParams{} + _, err := GetMyShortDescription(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_GetMyShortDescription_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetMyShortDescriptionParams{} + _, err := GetMyShortDescription(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_GetMyShortDescription_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetMyShortDescriptionParams{} + _, err := GetMyShortDescription(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_GetMyShortDescription_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetMyShortDescriptionParams{} + _, err := GetMyShortDescription(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_GetMyShortDescription_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_GetMyShortDescription_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := GetMyShortDescription(context.Background(), bot, &GetMyShortDescriptionParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_GetMyShortDescription_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_GetMyShortDescription_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetMyShortDescriptionParams{} + _, err := GetMyShortDescription(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_GetMyShortDescription_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_GetMyShortDescription_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetMyShortDescriptionParams{} + _, err := GetMyShortDescription(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_SetMyProfilePhoto_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/setMyProfilePhoto") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetMyProfilePhotoParams{ + Photo: nil, + } + _, err := SetMyProfilePhoto(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_SetMyProfilePhoto_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetMyProfilePhotoParams{ + Photo: nil, + } + _, err := SetMyProfilePhoto(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_SetMyProfilePhoto_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetMyProfilePhotoParams{ + Photo: nil, + } + _, err := SetMyProfilePhoto(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_SetMyProfilePhoto_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetMyProfilePhotoParams{ + Photo: nil, + } + _, err := SetMyProfilePhoto(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_SetMyProfilePhoto_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetMyProfilePhotoParams{ + Photo: nil, + } + _, err := SetMyProfilePhoto(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_SetMyProfilePhoto_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_SetMyProfilePhoto_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := SetMyProfilePhoto(context.Background(), bot, &SetMyProfilePhotoParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_SetMyProfilePhoto_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_SetMyProfilePhoto_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetMyProfilePhotoParams{ + Photo: nil, + } + _, err := SetMyProfilePhoto(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_SetMyProfilePhoto_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_SetMyProfilePhoto_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetMyProfilePhotoParams{ + Photo: nil, + } + _, err := SetMyProfilePhoto(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_RemoveMyProfilePhoto_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/removeMyProfilePhoto") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + _, err := RemoveMyProfilePhoto(context.Background(), bot, &RemoveMyProfilePhotoParams{}) + require.NoError(t, err) +} + +func Test_RemoveMyProfilePhoto_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + _, err := RemoveMyProfilePhoto(context.Background(), bot, &RemoveMyProfilePhotoParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_RemoveMyProfilePhoto_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + _, err := RemoveMyProfilePhoto(context.Background(), bot, &RemoveMyProfilePhotoParams{}) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_RemoveMyProfilePhoto_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + _, err := RemoveMyProfilePhoto(context.Background(), bot, &RemoveMyProfilePhotoParams{}) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_RemoveMyProfilePhoto_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + _, err := RemoveMyProfilePhoto(ctx, bot, &RemoveMyProfilePhotoParams{}) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_RemoveMyProfilePhoto_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_RemoveMyProfilePhoto_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := RemoveMyProfilePhoto(context.Background(), bot, &RemoveMyProfilePhotoParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_RemoveMyProfilePhoto_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_RemoveMyProfilePhoto_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + _, err := RemoveMyProfilePhoto(context.Background(), bot, &RemoveMyProfilePhotoParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_RemoveMyProfilePhoto_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_RemoveMyProfilePhoto_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + _, err := RemoveMyProfilePhoto(context.Background(), bot, &RemoveMyProfilePhotoParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_SetChatMenuButton_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/setChatMenuButton") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetChatMenuButtonParams{} + _, err := SetChatMenuButton(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_SetChatMenuButton_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetChatMenuButtonParams{} + _, err := SetChatMenuButton(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_SetChatMenuButton_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetChatMenuButtonParams{} + _, err := SetChatMenuButton(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_SetChatMenuButton_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetChatMenuButtonParams{} + _, err := SetChatMenuButton(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_SetChatMenuButton_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetChatMenuButtonParams{} + _, err := SetChatMenuButton(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_SetChatMenuButton_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_SetChatMenuButton_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := SetChatMenuButton(context.Background(), bot, &SetChatMenuButtonParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_SetChatMenuButton_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_SetChatMenuButton_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetChatMenuButtonParams{} + _, err := SetChatMenuButton(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_SetChatMenuButton_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_SetChatMenuButton_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetChatMenuButtonParams{} + _, err := SetChatMenuButton(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_GetChatMenuButton_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/getChatMenuButton") + })).Return(genTestResp(200, `{"ok":true,"result":{"type":"commands"}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetChatMenuButtonParams{} + _, err := GetChatMenuButton(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_GetChatMenuButton_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetChatMenuButtonParams{} + _, err := GetChatMenuButton(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_GetChatMenuButton_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetChatMenuButtonParams{} + _, err := GetChatMenuButton(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_GetChatMenuButton_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetChatMenuButtonParams{} + _, err := GetChatMenuButton(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_GetChatMenuButton_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetChatMenuButtonParams{} + _, err := GetChatMenuButton(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_GetChatMenuButton_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_GetChatMenuButton_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := GetChatMenuButton(context.Background(), bot, &GetChatMenuButtonParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_GetChatMenuButton_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_GetChatMenuButton_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetChatMenuButtonParams{} + _, err := GetChatMenuButton(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_GetChatMenuButton_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_GetChatMenuButton_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetChatMenuButtonParams{} + _, err := GetChatMenuButton(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_SetMyDefaultAdministratorRights_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/setMyDefaultAdministratorRights") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetMyDefaultAdministratorRightsParams{} + _, err := SetMyDefaultAdministratorRights(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_SetMyDefaultAdministratorRights_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetMyDefaultAdministratorRightsParams{} + _, err := SetMyDefaultAdministratorRights(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_SetMyDefaultAdministratorRights_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetMyDefaultAdministratorRightsParams{} + _, err := SetMyDefaultAdministratorRights(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_SetMyDefaultAdministratorRights_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetMyDefaultAdministratorRightsParams{} + _, err := SetMyDefaultAdministratorRights(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_SetMyDefaultAdministratorRights_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetMyDefaultAdministratorRightsParams{} + _, err := SetMyDefaultAdministratorRights(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_SetMyDefaultAdministratorRights_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_SetMyDefaultAdministratorRights_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := SetMyDefaultAdministratorRights(context.Background(), bot, &SetMyDefaultAdministratorRightsParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_SetMyDefaultAdministratorRights_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_SetMyDefaultAdministratorRights_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetMyDefaultAdministratorRightsParams{} + _, err := SetMyDefaultAdministratorRights(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_SetMyDefaultAdministratorRights_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_SetMyDefaultAdministratorRights_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetMyDefaultAdministratorRightsParams{} + _, err := SetMyDefaultAdministratorRights(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_GetMyDefaultAdministratorRights_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/getMyDefaultAdministratorRights") + })).Return(genTestResp(200, `{"ok":true,"result":{}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetMyDefaultAdministratorRightsParams{} + _, err := GetMyDefaultAdministratorRights(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_GetMyDefaultAdministratorRights_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetMyDefaultAdministratorRightsParams{} + _, err := GetMyDefaultAdministratorRights(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_GetMyDefaultAdministratorRights_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetMyDefaultAdministratorRightsParams{} + _, err := GetMyDefaultAdministratorRights(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_GetMyDefaultAdministratorRights_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetMyDefaultAdministratorRightsParams{} + _, err := GetMyDefaultAdministratorRights(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_GetMyDefaultAdministratorRights_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetMyDefaultAdministratorRightsParams{} + _, err := GetMyDefaultAdministratorRights(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_GetMyDefaultAdministratorRights_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_GetMyDefaultAdministratorRights_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := GetMyDefaultAdministratorRights(context.Background(), bot, &GetMyDefaultAdministratorRightsParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_GetMyDefaultAdministratorRights_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_GetMyDefaultAdministratorRights_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetMyDefaultAdministratorRightsParams{} + _, err := GetMyDefaultAdministratorRights(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_GetMyDefaultAdministratorRights_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_GetMyDefaultAdministratorRights_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetMyDefaultAdministratorRightsParams{} + _, err := GetMyDefaultAdministratorRights(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_GetAvailableGifts_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/getAvailableGifts") + })).Return(genTestResp(200, `{"ok":true,"result":{}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + _, err := GetAvailableGifts(context.Background(), bot, &GetAvailableGiftsParams{}) + require.NoError(t, err) +} + +func Test_GetAvailableGifts_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + _, err := GetAvailableGifts(context.Background(), bot, &GetAvailableGiftsParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_GetAvailableGifts_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + _, err := GetAvailableGifts(context.Background(), bot, &GetAvailableGiftsParams{}) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_GetAvailableGifts_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + _, err := GetAvailableGifts(context.Background(), bot, &GetAvailableGiftsParams{}) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_GetAvailableGifts_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + _, err := GetAvailableGifts(ctx, bot, &GetAvailableGiftsParams{}) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_GetAvailableGifts_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_GetAvailableGifts_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := GetAvailableGifts(context.Background(), bot, &GetAvailableGiftsParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_GetAvailableGifts_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_GetAvailableGifts_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + _, err := GetAvailableGifts(context.Background(), bot, &GetAvailableGiftsParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_GetAvailableGifts_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_GetAvailableGifts_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + _, err := GetAvailableGifts(context.Background(), bot, &GetAvailableGiftsParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_SendGift_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/sendGift") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendGiftParams{ + GiftID: "test_value", + } + _, err := SendGift(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_SendGift_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendGiftParams{ + GiftID: "test_value", + } + _, err := SendGift(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_SendGift_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendGiftParams{ + GiftID: "test_value", + } + _, err := SendGift(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_SendGift_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendGiftParams{ + GiftID: "test_value", + } + _, err := SendGift(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_SendGift_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendGiftParams{ + GiftID: "test_value", + } + _, err := SendGift(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_SendGift_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_SendGift_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := SendGift(context.Background(), bot, &SendGiftParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_SendGift_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_SendGift_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendGiftParams{ + GiftID: "test_value", + } + _, err := SendGift(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_SendGift_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_SendGift_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendGiftParams{ + GiftID: "test_value", + } + _, err := SendGift(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_GiftPremiumSubscription_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/giftPremiumSubscription") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GiftPremiumSubscriptionParams{ + UserID: 42, + MonthCount: 42, + StarCount: 42, + } + _, err := GiftPremiumSubscription(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_GiftPremiumSubscription_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GiftPremiumSubscriptionParams{ + UserID: 42, + MonthCount: 42, + StarCount: 42, + } + _, err := GiftPremiumSubscription(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_GiftPremiumSubscription_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GiftPremiumSubscriptionParams{ + UserID: 42, + MonthCount: 42, + StarCount: 42, + } + _, err := GiftPremiumSubscription(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_GiftPremiumSubscription_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GiftPremiumSubscriptionParams{ + UserID: 42, + MonthCount: 42, + StarCount: 42, + } + _, err := GiftPremiumSubscription(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_GiftPremiumSubscription_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GiftPremiumSubscriptionParams{ + UserID: 42, + MonthCount: 42, + StarCount: 42, + } + _, err := GiftPremiumSubscription(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_GiftPremiumSubscription_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_GiftPremiumSubscription_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := GiftPremiumSubscription(context.Background(), bot, &GiftPremiumSubscriptionParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_GiftPremiumSubscription_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_GiftPremiumSubscription_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GiftPremiumSubscriptionParams{ + UserID: 42, + MonthCount: 42, + StarCount: 42, + } + _, err := GiftPremiumSubscription(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_GiftPremiumSubscription_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_GiftPremiumSubscription_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GiftPremiumSubscriptionParams{ + UserID: 42, + MonthCount: 42, + StarCount: 42, + } + _, err := GiftPremiumSubscription(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_VerifyUser_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/verifyUser") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &VerifyUserParams{ + UserID: 42, + } + _, err := VerifyUser(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_VerifyUser_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &VerifyUserParams{ + UserID: 42, + } + _, err := VerifyUser(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_VerifyUser_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &VerifyUserParams{ + UserID: 42, + } + _, err := VerifyUser(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_VerifyUser_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &VerifyUserParams{ + UserID: 42, + } + _, err := VerifyUser(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_VerifyUser_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &VerifyUserParams{ + UserID: 42, + } + _, err := VerifyUser(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_VerifyUser_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_VerifyUser_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := VerifyUser(context.Background(), bot, &VerifyUserParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_VerifyUser_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_VerifyUser_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &VerifyUserParams{ + UserID: 42, + } + _, err := VerifyUser(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_VerifyUser_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_VerifyUser_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &VerifyUserParams{ + UserID: 42, + } + _, err := VerifyUser(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_VerifyChat_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/verifyChat") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &VerifyChatParams{ + ChatID: ChatIDFromInt(123), + } + _, err := VerifyChat(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_VerifyChat_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &VerifyChatParams{ + ChatID: ChatIDFromInt(123), + } + _, err := VerifyChat(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_VerifyChat_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &VerifyChatParams{ + ChatID: ChatIDFromInt(123), + } + _, err := VerifyChat(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_VerifyChat_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &VerifyChatParams{ + ChatID: ChatIDFromInt(123), + } + _, err := VerifyChat(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_VerifyChat_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &VerifyChatParams{ + ChatID: ChatIDFromInt(123), + } + _, err := VerifyChat(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_VerifyChat_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_VerifyChat_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := VerifyChat(context.Background(), bot, &VerifyChatParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_VerifyChat_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_VerifyChat_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &VerifyChatParams{ + ChatID: ChatIDFromInt(123), + } + _, err := VerifyChat(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_VerifyChat_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_VerifyChat_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &VerifyChatParams{ + ChatID: ChatIDFromInt(123), + } + _, err := VerifyChat(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_RemoveUserVerification_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/removeUserVerification") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &RemoveUserVerificationParams{ + UserID: 42, + } + _, err := RemoveUserVerification(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_RemoveUserVerification_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &RemoveUserVerificationParams{ + UserID: 42, + } + _, err := RemoveUserVerification(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_RemoveUserVerification_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &RemoveUserVerificationParams{ + UserID: 42, + } + _, err := RemoveUserVerification(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_RemoveUserVerification_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &RemoveUserVerificationParams{ + UserID: 42, + } + _, err := RemoveUserVerification(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_RemoveUserVerification_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &RemoveUserVerificationParams{ + UserID: 42, + } + _, err := RemoveUserVerification(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_RemoveUserVerification_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_RemoveUserVerification_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := RemoveUserVerification(context.Background(), bot, &RemoveUserVerificationParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_RemoveUserVerification_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_RemoveUserVerification_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &RemoveUserVerificationParams{ + UserID: 42, + } + _, err := RemoveUserVerification(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_RemoveUserVerification_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_RemoveUserVerification_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &RemoveUserVerificationParams{ + UserID: 42, + } + _, err := RemoveUserVerification(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_RemoveChatVerification_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/removeChatVerification") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &RemoveChatVerificationParams{ + ChatID: ChatIDFromInt(123), + } + _, err := RemoveChatVerification(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_RemoveChatVerification_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &RemoveChatVerificationParams{ + ChatID: ChatIDFromInt(123), + } + _, err := RemoveChatVerification(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_RemoveChatVerification_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &RemoveChatVerificationParams{ + ChatID: ChatIDFromInt(123), + } + _, err := RemoveChatVerification(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_RemoveChatVerification_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &RemoveChatVerificationParams{ + ChatID: ChatIDFromInt(123), + } + _, err := RemoveChatVerification(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_RemoveChatVerification_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &RemoveChatVerificationParams{ + ChatID: ChatIDFromInt(123), + } + _, err := RemoveChatVerification(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_RemoveChatVerification_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_RemoveChatVerification_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := RemoveChatVerification(context.Background(), bot, &RemoveChatVerificationParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_RemoveChatVerification_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_RemoveChatVerification_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &RemoveChatVerificationParams{ + ChatID: ChatIDFromInt(123), + } + _, err := RemoveChatVerification(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_RemoveChatVerification_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_RemoveChatVerification_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &RemoveChatVerificationParams{ + ChatID: ChatIDFromInt(123), + } + _, err := RemoveChatVerification(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_ReadBusinessMessage_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/readBusinessMessage") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &ReadBusinessMessageParams{ + BusinessConnectionID: "test_value", + ChatID: 42, + MessageID: 42, + } + _, err := ReadBusinessMessage(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_ReadBusinessMessage_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &ReadBusinessMessageParams{ + BusinessConnectionID: "test_value", + ChatID: 42, + MessageID: 42, + } + _, err := ReadBusinessMessage(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_ReadBusinessMessage_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &ReadBusinessMessageParams{ + BusinessConnectionID: "test_value", + ChatID: 42, + MessageID: 42, + } + _, err := ReadBusinessMessage(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_ReadBusinessMessage_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &ReadBusinessMessageParams{ + BusinessConnectionID: "test_value", + ChatID: 42, + MessageID: 42, + } + _, err := ReadBusinessMessage(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_ReadBusinessMessage_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &ReadBusinessMessageParams{ + BusinessConnectionID: "test_value", + ChatID: 42, + MessageID: 42, + } + _, err := ReadBusinessMessage(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_ReadBusinessMessage_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_ReadBusinessMessage_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := ReadBusinessMessage(context.Background(), bot, &ReadBusinessMessageParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_ReadBusinessMessage_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_ReadBusinessMessage_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &ReadBusinessMessageParams{ + BusinessConnectionID: "test_value", + ChatID: 42, + MessageID: 42, + } + _, err := ReadBusinessMessage(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_ReadBusinessMessage_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_ReadBusinessMessage_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &ReadBusinessMessageParams{ + BusinessConnectionID: "test_value", + ChatID: 42, + MessageID: 42, + } + _, err := ReadBusinessMessage(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_DeleteBusinessMessages_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/deleteBusinessMessages") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteBusinessMessagesParams{ + BusinessConnectionID: "test_value", + MessageIds: nil, + } + _, err := DeleteBusinessMessages(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_DeleteBusinessMessages_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteBusinessMessagesParams{ + BusinessConnectionID: "test_value", + MessageIds: nil, + } + _, err := DeleteBusinessMessages(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_DeleteBusinessMessages_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteBusinessMessagesParams{ + BusinessConnectionID: "test_value", + MessageIds: nil, + } + _, err := DeleteBusinessMessages(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_DeleteBusinessMessages_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteBusinessMessagesParams{ + BusinessConnectionID: "test_value", + MessageIds: nil, + } + _, err := DeleteBusinessMessages(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_DeleteBusinessMessages_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteBusinessMessagesParams{ + BusinessConnectionID: "test_value", + MessageIds: nil, + } + _, err := DeleteBusinessMessages(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_DeleteBusinessMessages_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_DeleteBusinessMessages_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := DeleteBusinessMessages(context.Background(), bot, &DeleteBusinessMessagesParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_DeleteBusinessMessages_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_DeleteBusinessMessages_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteBusinessMessagesParams{ + BusinessConnectionID: "test_value", + MessageIds: nil, + } + _, err := DeleteBusinessMessages(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_DeleteBusinessMessages_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_DeleteBusinessMessages_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteBusinessMessagesParams{ + BusinessConnectionID: "test_value", + MessageIds: nil, + } + _, err := DeleteBusinessMessages(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_SetBusinessAccountName_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/setBusinessAccountName") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetBusinessAccountNameParams{ + BusinessConnectionID: "test_value", + FirstName: "test_value", + } + _, err := SetBusinessAccountName(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_SetBusinessAccountName_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetBusinessAccountNameParams{ + BusinessConnectionID: "test_value", + FirstName: "test_value", + } + _, err := SetBusinessAccountName(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_SetBusinessAccountName_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetBusinessAccountNameParams{ + BusinessConnectionID: "test_value", + FirstName: "test_value", + } + _, err := SetBusinessAccountName(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_SetBusinessAccountName_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetBusinessAccountNameParams{ + BusinessConnectionID: "test_value", + FirstName: "test_value", + } + _, err := SetBusinessAccountName(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_SetBusinessAccountName_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetBusinessAccountNameParams{ + BusinessConnectionID: "test_value", + FirstName: "test_value", + } + _, err := SetBusinessAccountName(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_SetBusinessAccountName_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_SetBusinessAccountName_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := SetBusinessAccountName(context.Background(), bot, &SetBusinessAccountNameParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_SetBusinessAccountName_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_SetBusinessAccountName_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetBusinessAccountNameParams{ + BusinessConnectionID: "test_value", + FirstName: "test_value", + } + _, err := SetBusinessAccountName(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_SetBusinessAccountName_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_SetBusinessAccountName_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetBusinessAccountNameParams{ + BusinessConnectionID: "test_value", + FirstName: "test_value", + } + _, err := SetBusinessAccountName(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_SetBusinessAccountUsername_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/setBusinessAccountUsername") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetBusinessAccountUsernameParams{ + BusinessConnectionID: "test_value", + } + _, err := SetBusinessAccountUsername(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_SetBusinessAccountUsername_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetBusinessAccountUsernameParams{ + BusinessConnectionID: "test_value", + } + _, err := SetBusinessAccountUsername(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_SetBusinessAccountUsername_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetBusinessAccountUsernameParams{ + BusinessConnectionID: "test_value", + } + _, err := SetBusinessAccountUsername(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_SetBusinessAccountUsername_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetBusinessAccountUsernameParams{ + BusinessConnectionID: "test_value", + } + _, err := SetBusinessAccountUsername(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_SetBusinessAccountUsername_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetBusinessAccountUsernameParams{ + BusinessConnectionID: "test_value", + } + _, err := SetBusinessAccountUsername(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_SetBusinessAccountUsername_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_SetBusinessAccountUsername_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := SetBusinessAccountUsername(context.Background(), bot, &SetBusinessAccountUsernameParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_SetBusinessAccountUsername_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_SetBusinessAccountUsername_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetBusinessAccountUsernameParams{ + BusinessConnectionID: "test_value", + } + _, err := SetBusinessAccountUsername(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_SetBusinessAccountUsername_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_SetBusinessAccountUsername_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetBusinessAccountUsernameParams{ + BusinessConnectionID: "test_value", + } + _, err := SetBusinessAccountUsername(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_SetBusinessAccountBio_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/setBusinessAccountBio") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetBusinessAccountBioParams{ + BusinessConnectionID: "test_value", + } + _, err := SetBusinessAccountBio(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_SetBusinessAccountBio_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetBusinessAccountBioParams{ + BusinessConnectionID: "test_value", + } + _, err := SetBusinessAccountBio(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_SetBusinessAccountBio_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetBusinessAccountBioParams{ + BusinessConnectionID: "test_value", + } + _, err := SetBusinessAccountBio(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_SetBusinessAccountBio_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetBusinessAccountBioParams{ + BusinessConnectionID: "test_value", + } + _, err := SetBusinessAccountBio(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_SetBusinessAccountBio_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetBusinessAccountBioParams{ + BusinessConnectionID: "test_value", + } + _, err := SetBusinessAccountBio(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_SetBusinessAccountBio_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_SetBusinessAccountBio_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := SetBusinessAccountBio(context.Background(), bot, &SetBusinessAccountBioParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_SetBusinessAccountBio_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_SetBusinessAccountBio_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetBusinessAccountBioParams{ + BusinessConnectionID: "test_value", + } + _, err := SetBusinessAccountBio(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_SetBusinessAccountBio_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_SetBusinessAccountBio_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetBusinessAccountBioParams{ + BusinessConnectionID: "test_value", + } + _, err := SetBusinessAccountBio(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_SetBusinessAccountProfilePhoto_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/setBusinessAccountProfilePhoto") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetBusinessAccountProfilePhotoParams{ + BusinessConnectionID: "test_value", + Photo: nil, + } + _, err := SetBusinessAccountProfilePhoto(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_SetBusinessAccountProfilePhoto_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetBusinessAccountProfilePhotoParams{ + BusinessConnectionID: "test_value", + Photo: nil, + } + _, err := SetBusinessAccountProfilePhoto(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_SetBusinessAccountProfilePhoto_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetBusinessAccountProfilePhotoParams{ + BusinessConnectionID: "test_value", + Photo: nil, + } + _, err := SetBusinessAccountProfilePhoto(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_SetBusinessAccountProfilePhoto_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetBusinessAccountProfilePhotoParams{ + BusinessConnectionID: "test_value", + Photo: nil, + } + _, err := SetBusinessAccountProfilePhoto(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_SetBusinessAccountProfilePhoto_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetBusinessAccountProfilePhotoParams{ + BusinessConnectionID: "test_value", + Photo: nil, + } + _, err := SetBusinessAccountProfilePhoto(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_SetBusinessAccountProfilePhoto_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_SetBusinessAccountProfilePhoto_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := SetBusinessAccountProfilePhoto(context.Background(), bot, &SetBusinessAccountProfilePhotoParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_SetBusinessAccountProfilePhoto_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_SetBusinessAccountProfilePhoto_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetBusinessAccountProfilePhotoParams{ + BusinessConnectionID: "test_value", + Photo: nil, + } + _, err := SetBusinessAccountProfilePhoto(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_SetBusinessAccountProfilePhoto_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_SetBusinessAccountProfilePhoto_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetBusinessAccountProfilePhotoParams{ + BusinessConnectionID: "test_value", + Photo: nil, + } + _, err := SetBusinessAccountProfilePhoto(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_RemoveBusinessAccountProfilePhoto_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/removeBusinessAccountProfilePhoto") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &RemoveBusinessAccountProfilePhotoParams{ + BusinessConnectionID: "test_value", + } + _, err := RemoveBusinessAccountProfilePhoto(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_RemoveBusinessAccountProfilePhoto_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &RemoveBusinessAccountProfilePhotoParams{ + BusinessConnectionID: "test_value", + } + _, err := RemoveBusinessAccountProfilePhoto(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_RemoveBusinessAccountProfilePhoto_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &RemoveBusinessAccountProfilePhotoParams{ + BusinessConnectionID: "test_value", + } + _, err := RemoveBusinessAccountProfilePhoto(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_RemoveBusinessAccountProfilePhoto_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &RemoveBusinessAccountProfilePhotoParams{ + BusinessConnectionID: "test_value", + } + _, err := RemoveBusinessAccountProfilePhoto(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_RemoveBusinessAccountProfilePhoto_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &RemoveBusinessAccountProfilePhotoParams{ + BusinessConnectionID: "test_value", + } + _, err := RemoveBusinessAccountProfilePhoto(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_RemoveBusinessAccountProfilePhoto_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_RemoveBusinessAccountProfilePhoto_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := RemoveBusinessAccountProfilePhoto(context.Background(), bot, &RemoveBusinessAccountProfilePhotoParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_RemoveBusinessAccountProfilePhoto_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_RemoveBusinessAccountProfilePhoto_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &RemoveBusinessAccountProfilePhotoParams{ + BusinessConnectionID: "test_value", + } + _, err := RemoveBusinessAccountProfilePhoto(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_RemoveBusinessAccountProfilePhoto_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_RemoveBusinessAccountProfilePhoto_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &RemoveBusinessAccountProfilePhotoParams{ + BusinessConnectionID: "test_value", + } + _, err := RemoveBusinessAccountProfilePhoto(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_SetBusinessAccountGiftSettings_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/setBusinessAccountGiftSettings") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetBusinessAccountGiftSettingsParams{ + BusinessConnectionID: "test_value", + ShowGiftButton: true, + AcceptedGiftTypes: AcceptedGiftTypes{}, + } + _, err := SetBusinessAccountGiftSettings(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_SetBusinessAccountGiftSettings_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetBusinessAccountGiftSettingsParams{ + BusinessConnectionID: "test_value", + ShowGiftButton: true, + AcceptedGiftTypes: AcceptedGiftTypes{}, + } + _, err := SetBusinessAccountGiftSettings(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_SetBusinessAccountGiftSettings_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetBusinessAccountGiftSettingsParams{ + BusinessConnectionID: "test_value", + ShowGiftButton: true, + AcceptedGiftTypes: AcceptedGiftTypes{}, + } + _, err := SetBusinessAccountGiftSettings(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_SetBusinessAccountGiftSettings_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetBusinessAccountGiftSettingsParams{ + BusinessConnectionID: "test_value", + ShowGiftButton: true, + AcceptedGiftTypes: AcceptedGiftTypes{}, + } + _, err := SetBusinessAccountGiftSettings(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_SetBusinessAccountGiftSettings_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetBusinessAccountGiftSettingsParams{ + BusinessConnectionID: "test_value", + ShowGiftButton: true, + AcceptedGiftTypes: AcceptedGiftTypes{}, + } + _, err := SetBusinessAccountGiftSettings(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_SetBusinessAccountGiftSettings_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_SetBusinessAccountGiftSettings_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := SetBusinessAccountGiftSettings(context.Background(), bot, &SetBusinessAccountGiftSettingsParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_SetBusinessAccountGiftSettings_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_SetBusinessAccountGiftSettings_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetBusinessAccountGiftSettingsParams{ + BusinessConnectionID: "test_value", + ShowGiftButton: true, + AcceptedGiftTypes: AcceptedGiftTypes{}, + } + _, err := SetBusinessAccountGiftSettings(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_SetBusinessAccountGiftSettings_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_SetBusinessAccountGiftSettings_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetBusinessAccountGiftSettingsParams{ + BusinessConnectionID: "test_value", + ShowGiftButton: true, + AcceptedGiftTypes: AcceptedGiftTypes{}, + } + _, err := SetBusinessAccountGiftSettings(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_GetBusinessAccountStarBalance_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/getBusinessAccountStarBalance") + })).Return(genTestResp(200, `{"ok":true,"result":{}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetBusinessAccountStarBalanceParams{ + BusinessConnectionID: "test_value", + } + _, err := GetBusinessAccountStarBalance(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_GetBusinessAccountStarBalance_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetBusinessAccountStarBalanceParams{ + BusinessConnectionID: "test_value", + } + _, err := GetBusinessAccountStarBalance(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_GetBusinessAccountStarBalance_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetBusinessAccountStarBalanceParams{ + BusinessConnectionID: "test_value", + } + _, err := GetBusinessAccountStarBalance(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_GetBusinessAccountStarBalance_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetBusinessAccountStarBalanceParams{ + BusinessConnectionID: "test_value", + } + _, err := GetBusinessAccountStarBalance(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_GetBusinessAccountStarBalance_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetBusinessAccountStarBalanceParams{ + BusinessConnectionID: "test_value", + } + _, err := GetBusinessAccountStarBalance(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_GetBusinessAccountStarBalance_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_GetBusinessAccountStarBalance_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := GetBusinessAccountStarBalance(context.Background(), bot, &GetBusinessAccountStarBalanceParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_GetBusinessAccountStarBalance_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_GetBusinessAccountStarBalance_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetBusinessAccountStarBalanceParams{ + BusinessConnectionID: "test_value", + } + _, err := GetBusinessAccountStarBalance(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_GetBusinessAccountStarBalance_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_GetBusinessAccountStarBalance_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetBusinessAccountStarBalanceParams{ + BusinessConnectionID: "test_value", + } + _, err := GetBusinessAccountStarBalance(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_TransferBusinessAccountStars_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/transferBusinessAccountStars") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &TransferBusinessAccountStarsParams{ + BusinessConnectionID: "test_value", + StarCount: 42, + } + _, err := TransferBusinessAccountStars(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_TransferBusinessAccountStars_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &TransferBusinessAccountStarsParams{ + BusinessConnectionID: "test_value", + StarCount: 42, + } + _, err := TransferBusinessAccountStars(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_TransferBusinessAccountStars_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &TransferBusinessAccountStarsParams{ + BusinessConnectionID: "test_value", + StarCount: 42, + } + _, err := TransferBusinessAccountStars(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_TransferBusinessAccountStars_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &TransferBusinessAccountStarsParams{ + BusinessConnectionID: "test_value", + StarCount: 42, + } + _, err := TransferBusinessAccountStars(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_TransferBusinessAccountStars_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &TransferBusinessAccountStarsParams{ + BusinessConnectionID: "test_value", + StarCount: 42, + } + _, err := TransferBusinessAccountStars(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_TransferBusinessAccountStars_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_TransferBusinessAccountStars_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := TransferBusinessAccountStars(context.Background(), bot, &TransferBusinessAccountStarsParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_TransferBusinessAccountStars_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_TransferBusinessAccountStars_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &TransferBusinessAccountStarsParams{ + BusinessConnectionID: "test_value", + StarCount: 42, + } + _, err := TransferBusinessAccountStars(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_TransferBusinessAccountStars_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_TransferBusinessAccountStars_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &TransferBusinessAccountStarsParams{ + BusinessConnectionID: "test_value", + StarCount: 42, + } + _, err := TransferBusinessAccountStars(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_GetBusinessAccountGifts_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/getBusinessAccountGifts") + })).Return(genTestResp(200, `{"ok":true,"result":{}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetBusinessAccountGiftsParams{ + BusinessConnectionID: "test_value", + } + _, err := GetBusinessAccountGifts(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_GetBusinessAccountGifts_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetBusinessAccountGiftsParams{ + BusinessConnectionID: "test_value", + } + _, err := GetBusinessAccountGifts(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_GetBusinessAccountGifts_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetBusinessAccountGiftsParams{ + BusinessConnectionID: "test_value", + } + _, err := GetBusinessAccountGifts(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_GetBusinessAccountGifts_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetBusinessAccountGiftsParams{ + BusinessConnectionID: "test_value", + } + _, err := GetBusinessAccountGifts(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_GetBusinessAccountGifts_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetBusinessAccountGiftsParams{ + BusinessConnectionID: "test_value", + } + _, err := GetBusinessAccountGifts(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_GetBusinessAccountGifts_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_GetBusinessAccountGifts_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := GetBusinessAccountGifts(context.Background(), bot, &GetBusinessAccountGiftsParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_GetBusinessAccountGifts_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_GetBusinessAccountGifts_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetBusinessAccountGiftsParams{ + BusinessConnectionID: "test_value", + } + _, err := GetBusinessAccountGifts(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_GetBusinessAccountGifts_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_GetBusinessAccountGifts_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetBusinessAccountGiftsParams{ + BusinessConnectionID: "test_value", + } + _, err := GetBusinessAccountGifts(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_GetUserGifts_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/getUserGifts") + })).Return(genTestResp(200, `{"ok":true,"result":{}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetUserGiftsParams{ + UserID: 42, + } + _, err := GetUserGifts(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_GetUserGifts_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetUserGiftsParams{ + UserID: 42, + } + _, err := GetUserGifts(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_GetUserGifts_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetUserGiftsParams{ + UserID: 42, + } + _, err := GetUserGifts(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_GetUserGifts_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetUserGiftsParams{ + UserID: 42, + } + _, err := GetUserGifts(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_GetUserGifts_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetUserGiftsParams{ + UserID: 42, + } + _, err := GetUserGifts(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_GetUserGifts_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_GetUserGifts_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := GetUserGifts(context.Background(), bot, &GetUserGiftsParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_GetUserGifts_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_GetUserGifts_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetUserGiftsParams{ + UserID: 42, + } + _, err := GetUserGifts(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_GetUserGifts_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_GetUserGifts_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetUserGiftsParams{ + UserID: 42, + } + _, err := GetUserGifts(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_GetChatGifts_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/getChatGifts") + })).Return(genTestResp(200, `{"ok":true,"result":{}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetChatGiftsParams{ + ChatID: ChatIDFromInt(123), + } + _, err := GetChatGifts(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_GetChatGifts_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetChatGiftsParams{ + ChatID: ChatIDFromInt(123), + } + _, err := GetChatGifts(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_GetChatGifts_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetChatGiftsParams{ + ChatID: ChatIDFromInt(123), + } + _, err := GetChatGifts(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_GetChatGifts_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetChatGiftsParams{ + ChatID: ChatIDFromInt(123), + } + _, err := GetChatGifts(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_GetChatGifts_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetChatGiftsParams{ + ChatID: ChatIDFromInt(123), + } + _, err := GetChatGifts(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_GetChatGifts_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_GetChatGifts_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := GetChatGifts(context.Background(), bot, &GetChatGiftsParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_GetChatGifts_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_GetChatGifts_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetChatGiftsParams{ + ChatID: ChatIDFromInt(123), + } + _, err := GetChatGifts(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_GetChatGifts_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_GetChatGifts_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetChatGiftsParams{ + ChatID: ChatIDFromInt(123), + } + _, err := GetChatGifts(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_ConvertGiftToStars_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/convertGiftToStars") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &ConvertGiftToStarsParams{ + BusinessConnectionID: "test_value", + OwnedGiftID: "test_value", + } + _, err := ConvertGiftToStars(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_ConvertGiftToStars_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &ConvertGiftToStarsParams{ + BusinessConnectionID: "test_value", + OwnedGiftID: "test_value", + } + _, err := ConvertGiftToStars(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_ConvertGiftToStars_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &ConvertGiftToStarsParams{ + BusinessConnectionID: "test_value", + OwnedGiftID: "test_value", + } + _, err := ConvertGiftToStars(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_ConvertGiftToStars_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &ConvertGiftToStarsParams{ + BusinessConnectionID: "test_value", + OwnedGiftID: "test_value", + } + _, err := ConvertGiftToStars(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_ConvertGiftToStars_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &ConvertGiftToStarsParams{ + BusinessConnectionID: "test_value", + OwnedGiftID: "test_value", + } + _, err := ConvertGiftToStars(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_ConvertGiftToStars_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_ConvertGiftToStars_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := ConvertGiftToStars(context.Background(), bot, &ConvertGiftToStarsParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_ConvertGiftToStars_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_ConvertGiftToStars_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &ConvertGiftToStarsParams{ + BusinessConnectionID: "test_value", + OwnedGiftID: "test_value", + } + _, err := ConvertGiftToStars(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_ConvertGiftToStars_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_ConvertGiftToStars_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &ConvertGiftToStarsParams{ + BusinessConnectionID: "test_value", + OwnedGiftID: "test_value", + } + _, err := ConvertGiftToStars(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_UpgradeGift_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/upgradeGift") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &UpgradeGiftParams{ + BusinessConnectionID: "test_value", + OwnedGiftID: "test_value", + } + _, err := UpgradeGift(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_UpgradeGift_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &UpgradeGiftParams{ + BusinessConnectionID: "test_value", + OwnedGiftID: "test_value", + } + _, err := UpgradeGift(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_UpgradeGift_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &UpgradeGiftParams{ + BusinessConnectionID: "test_value", + OwnedGiftID: "test_value", + } + _, err := UpgradeGift(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_UpgradeGift_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &UpgradeGiftParams{ + BusinessConnectionID: "test_value", + OwnedGiftID: "test_value", + } + _, err := UpgradeGift(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_UpgradeGift_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &UpgradeGiftParams{ + BusinessConnectionID: "test_value", + OwnedGiftID: "test_value", + } + _, err := UpgradeGift(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_UpgradeGift_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_UpgradeGift_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := UpgradeGift(context.Background(), bot, &UpgradeGiftParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_UpgradeGift_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_UpgradeGift_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &UpgradeGiftParams{ + BusinessConnectionID: "test_value", + OwnedGiftID: "test_value", + } + _, err := UpgradeGift(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_UpgradeGift_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_UpgradeGift_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &UpgradeGiftParams{ + BusinessConnectionID: "test_value", + OwnedGiftID: "test_value", + } + _, err := UpgradeGift(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_TransferGift_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/transferGift") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &TransferGiftParams{ + BusinessConnectionID: "test_value", + OwnedGiftID: "test_value", + NewOwnerChatID: 42, + } + _, err := TransferGift(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_TransferGift_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &TransferGiftParams{ + BusinessConnectionID: "test_value", + OwnedGiftID: "test_value", + NewOwnerChatID: 42, + } + _, err := TransferGift(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_TransferGift_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &TransferGiftParams{ + BusinessConnectionID: "test_value", + OwnedGiftID: "test_value", + NewOwnerChatID: 42, + } + _, err := TransferGift(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_TransferGift_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &TransferGiftParams{ + BusinessConnectionID: "test_value", + OwnedGiftID: "test_value", + NewOwnerChatID: 42, + } + _, err := TransferGift(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_TransferGift_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &TransferGiftParams{ + BusinessConnectionID: "test_value", + OwnedGiftID: "test_value", + NewOwnerChatID: 42, + } + _, err := TransferGift(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_TransferGift_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_TransferGift_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := TransferGift(context.Background(), bot, &TransferGiftParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_TransferGift_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_TransferGift_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &TransferGiftParams{ + BusinessConnectionID: "test_value", + OwnedGiftID: "test_value", + NewOwnerChatID: 42, + } + _, err := TransferGift(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_TransferGift_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_TransferGift_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &TransferGiftParams{ + BusinessConnectionID: "test_value", + OwnedGiftID: "test_value", + NewOwnerChatID: 42, + } + _, err := TransferGift(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_PostStory_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/postStory") + })).Return(genTestResp(200, `{"ok":true,"result":{}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &PostStoryParams{ + BusinessConnectionID: "test_value", + Content: nil, + ActivePeriod: 42, + } + _, err := PostStory(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_PostStory_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &PostStoryParams{ + BusinessConnectionID: "test_value", + Content: nil, + ActivePeriod: 42, + } + _, err := PostStory(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_PostStory_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &PostStoryParams{ + BusinessConnectionID: "test_value", + Content: nil, + ActivePeriod: 42, + } + _, err := PostStory(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_PostStory_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &PostStoryParams{ + BusinessConnectionID: "test_value", + Content: nil, + ActivePeriod: 42, + } + _, err := PostStory(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_PostStory_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &PostStoryParams{ + BusinessConnectionID: "test_value", + Content: nil, + ActivePeriod: 42, + } + _, err := PostStory(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_PostStory_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_PostStory_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := PostStory(context.Background(), bot, &PostStoryParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_PostStory_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_PostStory_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &PostStoryParams{ + BusinessConnectionID: "test_value", + Content: nil, + ActivePeriod: 42, + } + _, err := PostStory(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_PostStory_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_PostStory_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &PostStoryParams{ + BusinessConnectionID: "test_value", + Content: nil, + ActivePeriod: 42, + } + _, err := PostStory(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_RepostStory_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/repostStory") + })).Return(genTestResp(200, `{"ok":true,"result":{}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &RepostStoryParams{ + BusinessConnectionID: "test_value", + FromChatID: 42, + FromStoryID: 42, + ActivePeriod: 42, + } + _, err := RepostStory(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_RepostStory_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &RepostStoryParams{ + BusinessConnectionID: "test_value", + FromChatID: 42, + FromStoryID: 42, + ActivePeriod: 42, + } + _, err := RepostStory(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_RepostStory_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &RepostStoryParams{ + BusinessConnectionID: "test_value", + FromChatID: 42, + FromStoryID: 42, + ActivePeriod: 42, + } + _, err := RepostStory(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_RepostStory_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &RepostStoryParams{ + BusinessConnectionID: "test_value", + FromChatID: 42, + FromStoryID: 42, + ActivePeriod: 42, + } + _, err := RepostStory(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_RepostStory_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &RepostStoryParams{ + BusinessConnectionID: "test_value", + FromChatID: 42, + FromStoryID: 42, + ActivePeriod: 42, + } + _, err := RepostStory(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_RepostStory_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_RepostStory_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := RepostStory(context.Background(), bot, &RepostStoryParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_RepostStory_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_RepostStory_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &RepostStoryParams{ + BusinessConnectionID: "test_value", + FromChatID: 42, + FromStoryID: 42, + ActivePeriod: 42, + } + _, err := RepostStory(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_RepostStory_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_RepostStory_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &RepostStoryParams{ + BusinessConnectionID: "test_value", + FromChatID: 42, + FromStoryID: 42, + ActivePeriod: 42, + } + _, err := RepostStory(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_EditStory_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/editStory") + })).Return(genTestResp(200, `{"ok":true,"result":{}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditStoryParams{ + BusinessConnectionID: "test_value", + StoryID: 42, + Content: nil, + } + _, err := EditStory(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_EditStory_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditStoryParams{ + BusinessConnectionID: "test_value", + StoryID: 42, + Content: nil, + } + _, err := EditStory(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_EditStory_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditStoryParams{ + BusinessConnectionID: "test_value", + StoryID: 42, + Content: nil, + } + _, err := EditStory(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_EditStory_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditStoryParams{ + BusinessConnectionID: "test_value", + StoryID: 42, + Content: nil, + } + _, err := EditStory(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_EditStory_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditStoryParams{ + BusinessConnectionID: "test_value", + StoryID: 42, + Content: nil, + } + _, err := EditStory(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_EditStory_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_EditStory_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := EditStory(context.Background(), bot, &EditStoryParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_EditStory_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_EditStory_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditStoryParams{ + BusinessConnectionID: "test_value", + StoryID: 42, + Content: nil, + } + _, err := EditStory(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_EditStory_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_EditStory_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditStoryParams{ + BusinessConnectionID: "test_value", + StoryID: 42, + Content: nil, + } + _, err := EditStory(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_DeleteStory_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/deleteStory") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteStoryParams{ + BusinessConnectionID: "test_value", + StoryID: 42, + } + _, err := DeleteStory(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_DeleteStory_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteStoryParams{ + BusinessConnectionID: "test_value", + StoryID: 42, + } + _, err := DeleteStory(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_DeleteStory_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteStoryParams{ + BusinessConnectionID: "test_value", + StoryID: 42, + } + _, err := DeleteStory(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_DeleteStory_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteStoryParams{ + BusinessConnectionID: "test_value", + StoryID: 42, + } + _, err := DeleteStory(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_DeleteStory_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteStoryParams{ + BusinessConnectionID: "test_value", + StoryID: 42, + } + _, err := DeleteStory(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_DeleteStory_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_DeleteStory_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := DeleteStory(context.Background(), bot, &DeleteStoryParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_DeleteStory_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_DeleteStory_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteStoryParams{ + BusinessConnectionID: "test_value", + StoryID: 42, + } + _, err := DeleteStory(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_DeleteStory_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_DeleteStory_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteStoryParams{ + BusinessConnectionID: "test_value", + StoryID: 42, + } + _, err := DeleteStory(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_AnswerWebAppQuery_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/answerWebAppQuery") + })).Return(genTestResp(200, `{"ok":true,"result":{}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &AnswerWebAppQueryParams{ + WebAppQueryID: "test_value", + Result: nil, + } + _, err := AnswerWebAppQuery(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_AnswerWebAppQuery_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &AnswerWebAppQueryParams{ + WebAppQueryID: "test_value", + Result: nil, + } + _, err := AnswerWebAppQuery(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_AnswerWebAppQuery_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &AnswerWebAppQueryParams{ + WebAppQueryID: "test_value", + Result: nil, + } + _, err := AnswerWebAppQuery(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_AnswerWebAppQuery_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &AnswerWebAppQueryParams{ + WebAppQueryID: "test_value", + Result: nil, + } + _, err := AnswerWebAppQuery(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_AnswerWebAppQuery_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &AnswerWebAppQueryParams{ + WebAppQueryID: "test_value", + Result: nil, + } + _, err := AnswerWebAppQuery(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_AnswerWebAppQuery_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_AnswerWebAppQuery_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := AnswerWebAppQuery(context.Background(), bot, &AnswerWebAppQueryParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_AnswerWebAppQuery_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_AnswerWebAppQuery_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &AnswerWebAppQueryParams{ + WebAppQueryID: "test_value", + Result: nil, + } + _, err := AnswerWebAppQuery(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_AnswerWebAppQuery_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_AnswerWebAppQuery_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &AnswerWebAppQueryParams{ + WebAppQueryID: "test_value", + Result: nil, + } + _, err := AnswerWebAppQuery(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_SavePreparedInlineMessage_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/savePreparedInlineMessage") + })).Return(genTestResp(200, `{"ok":true,"result":{}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SavePreparedInlineMessageParams{ + UserID: 42, + Result: nil, + } + _, err := SavePreparedInlineMessage(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_SavePreparedInlineMessage_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SavePreparedInlineMessageParams{ + UserID: 42, + Result: nil, + } + _, err := SavePreparedInlineMessage(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_SavePreparedInlineMessage_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SavePreparedInlineMessageParams{ + UserID: 42, + Result: nil, + } + _, err := SavePreparedInlineMessage(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_SavePreparedInlineMessage_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SavePreparedInlineMessageParams{ + UserID: 42, + Result: nil, + } + _, err := SavePreparedInlineMessage(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_SavePreparedInlineMessage_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SavePreparedInlineMessageParams{ + UserID: 42, + Result: nil, + } + _, err := SavePreparedInlineMessage(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_SavePreparedInlineMessage_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_SavePreparedInlineMessage_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := SavePreparedInlineMessage(context.Background(), bot, &SavePreparedInlineMessageParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_SavePreparedInlineMessage_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_SavePreparedInlineMessage_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SavePreparedInlineMessageParams{ + UserID: 42, + Result: nil, + } + _, err := SavePreparedInlineMessage(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_SavePreparedInlineMessage_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_SavePreparedInlineMessage_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SavePreparedInlineMessageParams{ + UserID: 42, + Result: nil, + } + _, err := SavePreparedInlineMessage(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_SavePreparedKeyboardButton_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/savePreparedKeyboardButton") + })).Return(genTestResp(200, `{"ok":true,"result":{}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SavePreparedKeyboardButtonParams{ + UserID: 42, + Button: KeyboardButton{}, + } + _, err := SavePreparedKeyboardButton(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_SavePreparedKeyboardButton_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SavePreparedKeyboardButtonParams{ + UserID: 42, + Button: KeyboardButton{}, + } + _, err := SavePreparedKeyboardButton(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_SavePreparedKeyboardButton_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SavePreparedKeyboardButtonParams{ + UserID: 42, + Button: KeyboardButton{}, + } + _, err := SavePreparedKeyboardButton(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_SavePreparedKeyboardButton_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SavePreparedKeyboardButtonParams{ + UserID: 42, + Button: KeyboardButton{}, + } + _, err := SavePreparedKeyboardButton(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_SavePreparedKeyboardButton_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SavePreparedKeyboardButtonParams{ + UserID: 42, + Button: KeyboardButton{}, + } + _, err := SavePreparedKeyboardButton(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_SavePreparedKeyboardButton_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_SavePreparedKeyboardButton_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := SavePreparedKeyboardButton(context.Background(), bot, &SavePreparedKeyboardButtonParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_SavePreparedKeyboardButton_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_SavePreparedKeyboardButton_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SavePreparedKeyboardButtonParams{ + UserID: 42, + Button: KeyboardButton{}, + } + _, err := SavePreparedKeyboardButton(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_SavePreparedKeyboardButton_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_SavePreparedKeyboardButton_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SavePreparedKeyboardButtonParams{ + UserID: 42, + Button: KeyboardButton{}, + } + _, err := SavePreparedKeyboardButton(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_EditMessageText_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/editMessageText") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditMessageTextParams{ + Text: "test_value", + } + _, err := EditMessageText(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_EditMessageText_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditMessageTextParams{ + Text: "test_value", + } + _, err := EditMessageText(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_EditMessageText_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditMessageTextParams{ + Text: "test_value", + } + _, err := EditMessageText(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_EditMessageText_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditMessageTextParams{ + Text: "test_value", + } + _, err := EditMessageText(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_EditMessageText_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditMessageTextParams{ + Text: "test_value", + } + _, err := EditMessageText(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_EditMessageText_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_EditMessageText_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := EditMessageText(context.Background(), bot, &EditMessageTextParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_EditMessageText_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_EditMessageText_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditMessageTextParams{ + Text: "test_value", + } + _, err := EditMessageText(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_EditMessageText_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_EditMessageText_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditMessageTextParams{ + Text: "test_value", + } + _, err := EditMessageText(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_EditMessageCaption_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/editMessageCaption") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditMessageCaptionParams{} + _, err := EditMessageCaption(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_EditMessageCaption_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditMessageCaptionParams{} + _, err := EditMessageCaption(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_EditMessageCaption_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditMessageCaptionParams{} + _, err := EditMessageCaption(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_EditMessageCaption_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditMessageCaptionParams{} + _, err := EditMessageCaption(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_EditMessageCaption_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditMessageCaptionParams{} + _, err := EditMessageCaption(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_EditMessageCaption_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_EditMessageCaption_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := EditMessageCaption(context.Background(), bot, &EditMessageCaptionParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_EditMessageCaption_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_EditMessageCaption_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditMessageCaptionParams{} + _, err := EditMessageCaption(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_EditMessageCaption_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_EditMessageCaption_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditMessageCaptionParams{} + _, err := EditMessageCaption(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_EditMessageMedia_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/editMessageMedia") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditMessageMediaParams{ + Media: nil, + } + _, err := EditMessageMedia(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_EditMessageMedia_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditMessageMediaParams{ + Media: nil, + } + _, err := EditMessageMedia(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_EditMessageMedia_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditMessageMediaParams{ + Media: nil, + } + _, err := EditMessageMedia(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_EditMessageMedia_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditMessageMediaParams{ + Media: nil, + } + _, err := EditMessageMedia(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_EditMessageMedia_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditMessageMediaParams{ + Media: nil, + } + _, err := EditMessageMedia(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_EditMessageMedia_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_EditMessageMedia_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := EditMessageMedia(context.Background(), bot, &EditMessageMediaParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_EditMessageMedia_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_EditMessageMedia_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditMessageMediaParams{ + Media: nil, + } + _, err := EditMessageMedia(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_EditMessageMedia_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_EditMessageMedia_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditMessageMediaParams{ + Media: nil, + } + _, err := EditMessageMedia(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_EditMessageLiveLocation_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/editMessageLiveLocation") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditMessageLiveLocationParams{ + Latitude: 1.0, + Longitude: 1.0, + } + _, err := EditMessageLiveLocation(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_EditMessageLiveLocation_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditMessageLiveLocationParams{ + Latitude: 1.0, + Longitude: 1.0, + } + _, err := EditMessageLiveLocation(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_EditMessageLiveLocation_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditMessageLiveLocationParams{ + Latitude: 1.0, + Longitude: 1.0, + } + _, err := EditMessageLiveLocation(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_EditMessageLiveLocation_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditMessageLiveLocationParams{ + Latitude: 1.0, + Longitude: 1.0, + } + _, err := EditMessageLiveLocation(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_EditMessageLiveLocation_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditMessageLiveLocationParams{ + Latitude: 1.0, + Longitude: 1.0, + } + _, err := EditMessageLiveLocation(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_EditMessageLiveLocation_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_EditMessageLiveLocation_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := EditMessageLiveLocation(context.Background(), bot, &EditMessageLiveLocationParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_EditMessageLiveLocation_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_EditMessageLiveLocation_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditMessageLiveLocationParams{ + Latitude: 1.0, + Longitude: 1.0, + } + _, err := EditMessageLiveLocation(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_EditMessageLiveLocation_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_EditMessageLiveLocation_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditMessageLiveLocationParams{ + Latitude: 1.0, + Longitude: 1.0, + } + _, err := EditMessageLiveLocation(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_StopMessageLiveLocation_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/stopMessageLiveLocation") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &StopMessageLiveLocationParams{} + _, err := StopMessageLiveLocation(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_StopMessageLiveLocation_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &StopMessageLiveLocationParams{} + _, err := StopMessageLiveLocation(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_StopMessageLiveLocation_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &StopMessageLiveLocationParams{} + _, err := StopMessageLiveLocation(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_StopMessageLiveLocation_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &StopMessageLiveLocationParams{} + _, err := StopMessageLiveLocation(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_StopMessageLiveLocation_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &StopMessageLiveLocationParams{} + _, err := StopMessageLiveLocation(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_StopMessageLiveLocation_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_StopMessageLiveLocation_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := StopMessageLiveLocation(context.Background(), bot, &StopMessageLiveLocationParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_StopMessageLiveLocation_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_StopMessageLiveLocation_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &StopMessageLiveLocationParams{} + _, err := StopMessageLiveLocation(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_StopMessageLiveLocation_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_StopMessageLiveLocation_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &StopMessageLiveLocationParams{} + _, err := StopMessageLiveLocation(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_EditMessageChecklist_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/editMessageChecklist") + })).Return(genTestResp(200, `{"ok":true,"result":{}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditMessageChecklistParams{ + BusinessConnectionID: "test_value", + ChatID: ChatIDFromInt(123), + MessageID: 42, + Checklist: InputChecklist{}, + } + _, err := EditMessageChecklist(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_EditMessageChecklist_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditMessageChecklistParams{ + BusinessConnectionID: "test_value", + ChatID: ChatIDFromInt(123), + MessageID: 42, + Checklist: InputChecklist{}, + } + _, err := EditMessageChecklist(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_EditMessageChecklist_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditMessageChecklistParams{ + BusinessConnectionID: "test_value", + ChatID: ChatIDFromInt(123), + MessageID: 42, + Checklist: InputChecklist{}, + } + _, err := EditMessageChecklist(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_EditMessageChecklist_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditMessageChecklistParams{ + BusinessConnectionID: "test_value", + ChatID: ChatIDFromInt(123), + MessageID: 42, + Checklist: InputChecklist{}, + } + _, err := EditMessageChecklist(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_EditMessageChecklist_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditMessageChecklistParams{ + BusinessConnectionID: "test_value", + ChatID: ChatIDFromInt(123), + MessageID: 42, + Checklist: InputChecklist{}, + } + _, err := EditMessageChecklist(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_EditMessageChecklist_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_EditMessageChecklist_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := EditMessageChecklist(context.Background(), bot, &EditMessageChecklistParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_EditMessageChecklist_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_EditMessageChecklist_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditMessageChecklistParams{ + BusinessConnectionID: "test_value", + ChatID: ChatIDFromInt(123), + MessageID: 42, + Checklist: InputChecklist{}, + } + _, err := EditMessageChecklist(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_EditMessageChecklist_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_EditMessageChecklist_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditMessageChecklistParams{ + BusinessConnectionID: "test_value", + ChatID: ChatIDFromInt(123), + MessageID: 42, + Checklist: InputChecklist{}, + } + _, err := EditMessageChecklist(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_EditMessageReplyMarkup_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/editMessageReplyMarkup") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditMessageReplyMarkupParams{} + _, err := EditMessageReplyMarkup(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_EditMessageReplyMarkup_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditMessageReplyMarkupParams{} + _, err := EditMessageReplyMarkup(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_EditMessageReplyMarkup_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditMessageReplyMarkupParams{} + _, err := EditMessageReplyMarkup(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_EditMessageReplyMarkup_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditMessageReplyMarkupParams{} + _, err := EditMessageReplyMarkup(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_EditMessageReplyMarkup_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditMessageReplyMarkupParams{} + _, err := EditMessageReplyMarkup(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_EditMessageReplyMarkup_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_EditMessageReplyMarkup_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := EditMessageReplyMarkup(context.Background(), bot, &EditMessageReplyMarkupParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_EditMessageReplyMarkup_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_EditMessageReplyMarkup_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditMessageReplyMarkupParams{} + _, err := EditMessageReplyMarkup(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_EditMessageReplyMarkup_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_EditMessageReplyMarkup_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditMessageReplyMarkupParams{} + _, err := EditMessageReplyMarkup(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_StopPoll_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/stopPoll") + })).Return(genTestResp(200, `{"ok":true,"result":{}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &StopPollParams{ + ChatID: ChatIDFromInt(123), + MessageID: 42, + } + _, err := StopPoll(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_StopPoll_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &StopPollParams{ + ChatID: ChatIDFromInt(123), + MessageID: 42, + } + _, err := StopPoll(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_StopPoll_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &StopPollParams{ + ChatID: ChatIDFromInt(123), + MessageID: 42, + } + _, err := StopPoll(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_StopPoll_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &StopPollParams{ + ChatID: ChatIDFromInt(123), + MessageID: 42, + } + _, err := StopPoll(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_StopPoll_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &StopPollParams{ + ChatID: ChatIDFromInt(123), + MessageID: 42, + } + _, err := StopPoll(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_StopPoll_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_StopPoll_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := StopPoll(context.Background(), bot, &StopPollParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_StopPoll_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_StopPoll_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &StopPollParams{ + ChatID: ChatIDFromInt(123), + MessageID: 42, + } + _, err := StopPoll(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_StopPoll_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_StopPoll_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &StopPollParams{ + ChatID: ChatIDFromInt(123), + MessageID: 42, + } + _, err := StopPoll(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_ApproveSuggestedPost_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/approveSuggestedPost") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &ApproveSuggestedPostParams{ + ChatID: 42, + MessageID: 42, + } + _, err := ApproveSuggestedPost(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_ApproveSuggestedPost_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &ApproveSuggestedPostParams{ + ChatID: 42, + MessageID: 42, + } + _, err := ApproveSuggestedPost(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_ApproveSuggestedPost_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &ApproveSuggestedPostParams{ + ChatID: 42, + MessageID: 42, + } + _, err := ApproveSuggestedPost(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_ApproveSuggestedPost_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &ApproveSuggestedPostParams{ + ChatID: 42, + MessageID: 42, + } + _, err := ApproveSuggestedPost(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_ApproveSuggestedPost_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &ApproveSuggestedPostParams{ + ChatID: 42, + MessageID: 42, + } + _, err := ApproveSuggestedPost(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_ApproveSuggestedPost_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_ApproveSuggestedPost_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := ApproveSuggestedPost(context.Background(), bot, &ApproveSuggestedPostParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_ApproveSuggestedPost_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_ApproveSuggestedPost_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &ApproveSuggestedPostParams{ + ChatID: 42, + MessageID: 42, + } + _, err := ApproveSuggestedPost(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_ApproveSuggestedPost_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_ApproveSuggestedPost_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &ApproveSuggestedPostParams{ + ChatID: 42, + MessageID: 42, + } + _, err := ApproveSuggestedPost(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_DeclineSuggestedPost_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/declineSuggestedPost") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeclineSuggestedPostParams{ + ChatID: 42, + MessageID: 42, + } + _, err := DeclineSuggestedPost(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_DeclineSuggestedPost_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeclineSuggestedPostParams{ + ChatID: 42, + MessageID: 42, + } + _, err := DeclineSuggestedPost(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_DeclineSuggestedPost_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeclineSuggestedPostParams{ + ChatID: 42, + MessageID: 42, + } + _, err := DeclineSuggestedPost(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_DeclineSuggestedPost_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeclineSuggestedPostParams{ + ChatID: 42, + MessageID: 42, + } + _, err := DeclineSuggestedPost(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_DeclineSuggestedPost_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeclineSuggestedPostParams{ + ChatID: 42, + MessageID: 42, + } + _, err := DeclineSuggestedPost(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_DeclineSuggestedPost_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_DeclineSuggestedPost_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := DeclineSuggestedPost(context.Background(), bot, &DeclineSuggestedPostParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_DeclineSuggestedPost_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_DeclineSuggestedPost_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeclineSuggestedPostParams{ + ChatID: 42, + MessageID: 42, + } + _, err := DeclineSuggestedPost(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_DeclineSuggestedPost_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_DeclineSuggestedPost_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeclineSuggestedPostParams{ + ChatID: 42, + MessageID: 42, + } + _, err := DeclineSuggestedPost(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_DeleteMessage_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/deleteMessage") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteMessageParams{ + ChatID: ChatIDFromInt(123), + MessageID: 42, + } + _, err := DeleteMessage(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_DeleteMessage_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteMessageParams{ + ChatID: ChatIDFromInt(123), + MessageID: 42, + } + _, err := DeleteMessage(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_DeleteMessage_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteMessageParams{ + ChatID: ChatIDFromInt(123), + MessageID: 42, + } + _, err := DeleteMessage(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_DeleteMessage_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteMessageParams{ + ChatID: ChatIDFromInt(123), + MessageID: 42, + } + _, err := DeleteMessage(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_DeleteMessage_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteMessageParams{ + ChatID: ChatIDFromInt(123), + MessageID: 42, + } + _, err := DeleteMessage(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_DeleteMessage_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_DeleteMessage_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := DeleteMessage(context.Background(), bot, &DeleteMessageParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_DeleteMessage_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_DeleteMessage_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteMessageParams{ + ChatID: ChatIDFromInt(123), + MessageID: 42, + } + _, err := DeleteMessage(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_DeleteMessage_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_DeleteMessage_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteMessageParams{ + ChatID: ChatIDFromInt(123), + MessageID: 42, + } + _, err := DeleteMessage(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_DeleteMessages_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/deleteMessages") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteMessagesParams{ + ChatID: ChatIDFromInt(123), + MessageIds: nil, + } + _, err := DeleteMessages(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_DeleteMessages_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteMessagesParams{ + ChatID: ChatIDFromInt(123), + MessageIds: nil, + } + _, err := DeleteMessages(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_DeleteMessages_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteMessagesParams{ + ChatID: ChatIDFromInt(123), + MessageIds: nil, + } + _, err := DeleteMessages(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_DeleteMessages_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteMessagesParams{ + ChatID: ChatIDFromInt(123), + MessageIds: nil, + } + _, err := DeleteMessages(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_DeleteMessages_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteMessagesParams{ + ChatID: ChatIDFromInt(123), + MessageIds: nil, + } + _, err := DeleteMessages(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_DeleteMessages_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_DeleteMessages_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := DeleteMessages(context.Background(), bot, &DeleteMessagesParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_DeleteMessages_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_DeleteMessages_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteMessagesParams{ + ChatID: ChatIDFromInt(123), + MessageIds: nil, + } + _, err := DeleteMessages(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_DeleteMessages_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_DeleteMessages_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteMessagesParams{ + ChatID: ChatIDFromInt(123), + MessageIds: nil, + } + _, err := DeleteMessages(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_DeleteMessageReaction_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/deleteMessageReaction") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteMessageReactionParams{ + ChatID: ChatIDFromInt(123), + MessageID: 42, + } + _, err := DeleteMessageReaction(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_DeleteMessageReaction_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteMessageReactionParams{ + ChatID: ChatIDFromInt(123), + MessageID: 42, + } + _, err := DeleteMessageReaction(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_DeleteMessageReaction_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteMessageReactionParams{ + ChatID: ChatIDFromInt(123), + MessageID: 42, + } + _, err := DeleteMessageReaction(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_DeleteMessageReaction_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteMessageReactionParams{ + ChatID: ChatIDFromInt(123), + MessageID: 42, + } + _, err := DeleteMessageReaction(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_DeleteMessageReaction_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteMessageReactionParams{ + ChatID: ChatIDFromInt(123), + MessageID: 42, + } + _, err := DeleteMessageReaction(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_DeleteMessageReaction_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_DeleteMessageReaction_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := DeleteMessageReaction(context.Background(), bot, &DeleteMessageReactionParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_DeleteMessageReaction_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_DeleteMessageReaction_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteMessageReactionParams{ + ChatID: ChatIDFromInt(123), + MessageID: 42, + } + _, err := DeleteMessageReaction(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_DeleteMessageReaction_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_DeleteMessageReaction_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteMessageReactionParams{ + ChatID: ChatIDFromInt(123), + MessageID: 42, + } + _, err := DeleteMessageReaction(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_DeleteAllMessageReactions_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/deleteAllMessageReactions") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteAllMessageReactionsParams{ + ChatID: ChatIDFromInt(123), + } + _, err := DeleteAllMessageReactions(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_DeleteAllMessageReactions_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteAllMessageReactionsParams{ + ChatID: ChatIDFromInt(123), + } + _, err := DeleteAllMessageReactions(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_DeleteAllMessageReactions_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteAllMessageReactionsParams{ + ChatID: ChatIDFromInt(123), + } + _, err := DeleteAllMessageReactions(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_DeleteAllMessageReactions_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteAllMessageReactionsParams{ + ChatID: ChatIDFromInt(123), + } + _, err := DeleteAllMessageReactions(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_DeleteAllMessageReactions_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteAllMessageReactionsParams{ + ChatID: ChatIDFromInt(123), + } + _, err := DeleteAllMessageReactions(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_DeleteAllMessageReactions_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_DeleteAllMessageReactions_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := DeleteAllMessageReactions(context.Background(), bot, &DeleteAllMessageReactionsParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_DeleteAllMessageReactions_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_DeleteAllMessageReactions_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteAllMessageReactionsParams{ + ChatID: ChatIDFromInt(123), + } + _, err := DeleteAllMessageReactions(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_DeleteAllMessageReactions_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_DeleteAllMessageReactions_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteAllMessageReactionsParams{ + ChatID: ChatIDFromInt(123), + } + _, err := DeleteAllMessageReactions(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_SendSticker_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/sendSticker") + })).Return(genTestResp(200, `{"ok":true,"result":{}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendStickerParams{ + ChatID: ChatIDFromInt(123), + Sticker: &InputFile{PathOrID: "file_id_test"}, + } + _, err := SendSticker(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_SendSticker_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendStickerParams{ + ChatID: ChatIDFromInt(123), + Sticker: &InputFile{PathOrID: "file_id_test"}, + } + _, err := SendSticker(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_SendSticker_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendStickerParams{ + ChatID: ChatIDFromInt(123), + Sticker: &InputFile{PathOrID: "file_id_test"}, + } + _, err := SendSticker(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_SendSticker_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendStickerParams{ + ChatID: ChatIDFromInt(123), + Sticker: &InputFile{PathOrID: "file_id_test"}, + } + _, err := SendSticker(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_SendSticker_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendStickerParams{ + ChatID: ChatIDFromInt(123), + Sticker: &InputFile{PathOrID: "file_id_test"}, + } + _, err := SendSticker(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_SendSticker_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_SendSticker_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := SendSticker(context.Background(), bot, &SendStickerParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_SendSticker_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_SendSticker_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendStickerParams{ + ChatID: ChatIDFromInt(123), + Sticker: &InputFile{PathOrID: "file_id_test"}, + } + _, err := SendSticker(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_SendSticker_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_SendSticker_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendStickerParams{ + ChatID: ChatIDFromInt(123), + Sticker: &InputFile{PathOrID: "file_id_test"}, + } + _, err := SendSticker(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_GetStickerSet_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/getStickerSet") + })).Return(genTestResp(200, `{"ok":true,"result":{}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetStickerSetParams{ + Name: "test_value", + } + _, err := GetStickerSet(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_GetStickerSet_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetStickerSetParams{ + Name: "test_value", + } + _, err := GetStickerSet(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_GetStickerSet_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetStickerSetParams{ + Name: "test_value", + } + _, err := GetStickerSet(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_GetStickerSet_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetStickerSetParams{ + Name: "test_value", + } + _, err := GetStickerSet(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_GetStickerSet_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetStickerSetParams{ + Name: "test_value", + } + _, err := GetStickerSet(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_GetStickerSet_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_GetStickerSet_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := GetStickerSet(context.Background(), bot, &GetStickerSetParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_GetStickerSet_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_GetStickerSet_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetStickerSetParams{ + Name: "test_value", + } + _, err := GetStickerSet(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_GetStickerSet_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_GetStickerSet_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetStickerSetParams{ + Name: "test_value", + } + _, err := GetStickerSet(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_GetCustomEmojiStickers_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/getCustomEmojiStickers") + })).Return(genTestResp(200, `{"ok":true,"result":[]}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetCustomEmojiStickersParams{ + CustomEmojiIds: nil, + } + _, err := GetCustomEmojiStickers(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_GetCustomEmojiStickers_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetCustomEmojiStickersParams{ + CustomEmojiIds: nil, + } + _, err := GetCustomEmojiStickers(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_GetCustomEmojiStickers_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetCustomEmojiStickersParams{ + CustomEmojiIds: nil, + } + _, err := GetCustomEmojiStickers(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_GetCustomEmojiStickers_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetCustomEmojiStickersParams{ + CustomEmojiIds: nil, + } + _, err := GetCustomEmojiStickers(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_GetCustomEmojiStickers_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetCustomEmojiStickersParams{ + CustomEmojiIds: nil, + } + _, err := GetCustomEmojiStickers(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_GetCustomEmojiStickers_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_GetCustomEmojiStickers_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := GetCustomEmojiStickers(context.Background(), bot, &GetCustomEmojiStickersParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_GetCustomEmojiStickers_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_GetCustomEmojiStickers_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetCustomEmojiStickersParams{ + CustomEmojiIds: nil, + } + _, err := GetCustomEmojiStickers(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_GetCustomEmojiStickers_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_GetCustomEmojiStickers_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetCustomEmojiStickersParams{ + CustomEmojiIds: nil, + } + _, err := GetCustomEmojiStickers(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_UploadStickerFile_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/uploadStickerFile") + })).Return(genTestResp(200, `{"ok":true,"result":{}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &UploadStickerFileParams{ + UserID: 42, + Sticker: &InputFile{PathOrID: "file_id_test"}, + StickerFormat: "test_value", + } + _, err := UploadStickerFile(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_UploadStickerFile_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &UploadStickerFileParams{ + UserID: 42, + Sticker: &InputFile{PathOrID: "file_id_test"}, + StickerFormat: "test_value", + } + _, err := UploadStickerFile(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_UploadStickerFile_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &UploadStickerFileParams{ + UserID: 42, + Sticker: &InputFile{PathOrID: "file_id_test"}, + StickerFormat: "test_value", + } + _, err := UploadStickerFile(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_UploadStickerFile_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &UploadStickerFileParams{ + UserID: 42, + Sticker: &InputFile{PathOrID: "file_id_test"}, + StickerFormat: "test_value", + } + _, err := UploadStickerFile(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_UploadStickerFile_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &UploadStickerFileParams{ + UserID: 42, + Sticker: &InputFile{PathOrID: "file_id_test"}, + StickerFormat: "test_value", + } + _, err := UploadStickerFile(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_UploadStickerFile_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_UploadStickerFile_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := UploadStickerFile(context.Background(), bot, &UploadStickerFileParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_UploadStickerFile_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_UploadStickerFile_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &UploadStickerFileParams{ + UserID: 42, + Sticker: &InputFile{PathOrID: "file_id_test"}, + StickerFormat: "test_value", + } + _, err := UploadStickerFile(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_UploadStickerFile_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_UploadStickerFile_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &UploadStickerFileParams{ + UserID: 42, + Sticker: &InputFile{PathOrID: "file_id_test"}, + StickerFormat: "test_value", + } + _, err := UploadStickerFile(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_CreateNewStickerSet_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/createNewStickerSet") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &CreateNewStickerSetParams{ + UserID: 42, + Name: "test_value", + Title: "test_value", + Stickers: nil, + } + _, err := CreateNewStickerSet(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_CreateNewStickerSet_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &CreateNewStickerSetParams{ + UserID: 42, + Name: "test_value", + Title: "test_value", + Stickers: nil, + } + _, err := CreateNewStickerSet(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_CreateNewStickerSet_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &CreateNewStickerSetParams{ + UserID: 42, + Name: "test_value", + Title: "test_value", + Stickers: nil, + } + _, err := CreateNewStickerSet(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_CreateNewStickerSet_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &CreateNewStickerSetParams{ + UserID: 42, + Name: "test_value", + Title: "test_value", + Stickers: nil, + } + _, err := CreateNewStickerSet(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_CreateNewStickerSet_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &CreateNewStickerSetParams{ + UserID: 42, + Name: "test_value", + Title: "test_value", + Stickers: nil, + } + _, err := CreateNewStickerSet(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_CreateNewStickerSet_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_CreateNewStickerSet_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := CreateNewStickerSet(context.Background(), bot, &CreateNewStickerSetParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_CreateNewStickerSet_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_CreateNewStickerSet_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &CreateNewStickerSetParams{ + UserID: 42, + Name: "test_value", + Title: "test_value", + Stickers: nil, + } + _, err := CreateNewStickerSet(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_CreateNewStickerSet_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_CreateNewStickerSet_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &CreateNewStickerSetParams{ + UserID: 42, + Name: "test_value", + Title: "test_value", + Stickers: nil, + } + _, err := CreateNewStickerSet(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_AddStickerToSet_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/addStickerToSet") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &AddStickerToSetParams{ + UserID: 42, + Name: "test_value", + Sticker: InputSticker{}, + } + _, err := AddStickerToSet(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_AddStickerToSet_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &AddStickerToSetParams{ + UserID: 42, + Name: "test_value", + Sticker: InputSticker{}, + } + _, err := AddStickerToSet(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_AddStickerToSet_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &AddStickerToSetParams{ + UserID: 42, + Name: "test_value", + Sticker: InputSticker{}, + } + _, err := AddStickerToSet(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_AddStickerToSet_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &AddStickerToSetParams{ + UserID: 42, + Name: "test_value", + Sticker: InputSticker{}, + } + _, err := AddStickerToSet(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_AddStickerToSet_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &AddStickerToSetParams{ + UserID: 42, + Name: "test_value", + Sticker: InputSticker{}, + } + _, err := AddStickerToSet(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_AddStickerToSet_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_AddStickerToSet_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := AddStickerToSet(context.Background(), bot, &AddStickerToSetParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_AddStickerToSet_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_AddStickerToSet_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &AddStickerToSetParams{ + UserID: 42, + Name: "test_value", + Sticker: InputSticker{}, + } + _, err := AddStickerToSet(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_AddStickerToSet_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_AddStickerToSet_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &AddStickerToSetParams{ + UserID: 42, + Name: "test_value", + Sticker: InputSticker{}, + } + _, err := AddStickerToSet(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_SetStickerPositionInSet_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/setStickerPositionInSet") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetStickerPositionInSetParams{ + Sticker: "test_value", + Position: 42, + } + _, err := SetStickerPositionInSet(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_SetStickerPositionInSet_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetStickerPositionInSetParams{ + Sticker: "test_value", + Position: 42, + } + _, err := SetStickerPositionInSet(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_SetStickerPositionInSet_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetStickerPositionInSetParams{ + Sticker: "test_value", + Position: 42, + } + _, err := SetStickerPositionInSet(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_SetStickerPositionInSet_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetStickerPositionInSetParams{ + Sticker: "test_value", + Position: 42, + } + _, err := SetStickerPositionInSet(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_SetStickerPositionInSet_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetStickerPositionInSetParams{ + Sticker: "test_value", + Position: 42, + } + _, err := SetStickerPositionInSet(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_SetStickerPositionInSet_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_SetStickerPositionInSet_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := SetStickerPositionInSet(context.Background(), bot, &SetStickerPositionInSetParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_SetStickerPositionInSet_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_SetStickerPositionInSet_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetStickerPositionInSetParams{ + Sticker: "test_value", + Position: 42, + } + _, err := SetStickerPositionInSet(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_SetStickerPositionInSet_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_SetStickerPositionInSet_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetStickerPositionInSetParams{ + Sticker: "test_value", + Position: 42, + } + _, err := SetStickerPositionInSet(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_DeleteStickerFromSet_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/deleteStickerFromSet") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteStickerFromSetParams{ + Sticker: "test_value", + } + _, err := DeleteStickerFromSet(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_DeleteStickerFromSet_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteStickerFromSetParams{ + Sticker: "test_value", + } + _, err := DeleteStickerFromSet(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_DeleteStickerFromSet_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteStickerFromSetParams{ + Sticker: "test_value", + } + _, err := DeleteStickerFromSet(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_DeleteStickerFromSet_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteStickerFromSetParams{ + Sticker: "test_value", + } + _, err := DeleteStickerFromSet(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_DeleteStickerFromSet_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteStickerFromSetParams{ + Sticker: "test_value", + } + _, err := DeleteStickerFromSet(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_DeleteStickerFromSet_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_DeleteStickerFromSet_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := DeleteStickerFromSet(context.Background(), bot, &DeleteStickerFromSetParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_DeleteStickerFromSet_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_DeleteStickerFromSet_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteStickerFromSetParams{ + Sticker: "test_value", + } + _, err := DeleteStickerFromSet(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_DeleteStickerFromSet_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_DeleteStickerFromSet_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteStickerFromSetParams{ + Sticker: "test_value", + } + _, err := DeleteStickerFromSet(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_ReplaceStickerInSet_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/replaceStickerInSet") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &ReplaceStickerInSetParams{ + UserID: 42, + Name: "test_value", + OldSticker: "test_value", + Sticker: InputSticker{}, + } + _, err := ReplaceStickerInSet(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_ReplaceStickerInSet_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &ReplaceStickerInSetParams{ + UserID: 42, + Name: "test_value", + OldSticker: "test_value", + Sticker: InputSticker{}, + } + _, err := ReplaceStickerInSet(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_ReplaceStickerInSet_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &ReplaceStickerInSetParams{ + UserID: 42, + Name: "test_value", + OldSticker: "test_value", + Sticker: InputSticker{}, + } + _, err := ReplaceStickerInSet(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_ReplaceStickerInSet_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &ReplaceStickerInSetParams{ + UserID: 42, + Name: "test_value", + OldSticker: "test_value", + Sticker: InputSticker{}, + } + _, err := ReplaceStickerInSet(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_ReplaceStickerInSet_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &ReplaceStickerInSetParams{ + UserID: 42, + Name: "test_value", + OldSticker: "test_value", + Sticker: InputSticker{}, + } + _, err := ReplaceStickerInSet(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_ReplaceStickerInSet_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_ReplaceStickerInSet_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := ReplaceStickerInSet(context.Background(), bot, &ReplaceStickerInSetParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_ReplaceStickerInSet_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_ReplaceStickerInSet_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &ReplaceStickerInSetParams{ + UserID: 42, + Name: "test_value", + OldSticker: "test_value", + Sticker: InputSticker{}, + } + _, err := ReplaceStickerInSet(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_ReplaceStickerInSet_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_ReplaceStickerInSet_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &ReplaceStickerInSetParams{ + UserID: 42, + Name: "test_value", + OldSticker: "test_value", + Sticker: InputSticker{}, + } + _, err := ReplaceStickerInSet(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_SetStickerEmojiList_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/setStickerEmojiList") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetStickerEmojiListParams{ + Sticker: "test_value", + EmojiList: nil, + } + _, err := SetStickerEmojiList(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_SetStickerEmojiList_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetStickerEmojiListParams{ + Sticker: "test_value", + EmojiList: nil, + } + _, err := SetStickerEmojiList(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_SetStickerEmojiList_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetStickerEmojiListParams{ + Sticker: "test_value", + EmojiList: nil, + } + _, err := SetStickerEmojiList(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_SetStickerEmojiList_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetStickerEmojiListParams{ + Sticker: "test_value", + EmojiList: nil, + } + _, err := SetStickerEmojiList(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_SetStickerEmojiList_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetStickerEmojiListParams{ + Sticker: "test_value", + EmojiList: nil, + } + _, err := SetStickerEmojiList(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_SetStickerEmojiList_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_SetStickerEmojiList_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := SetStickerEmojiList(context.Background(), bot, &SetStickerEmojiListParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_SetStickerEmojiList_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_SetStickerEmojiList_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetStickerEmojiListParams{ + Sticker: "test_value", + EmojiList: nil, + } + _, err := SetStickerEmojiList(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_SetStickerEmojiList_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_SetStickerEmojiList_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetStickerEmojiListParams{ + Sticker: "test_value", + EmojiList: nil, + } + _, err := SetStickerEmojiList(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_SetStickerKeywords_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/setStickerKeywords") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetStickerKeywordsParams{ + Sticker: "test_value", + } + _, err := SetStickerKeywords(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_SetStickerKeywords_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetStickerKeywordsParams{ + Sticker: "test_value", + } + _, err := SetStickerKeywords(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_SetStickerKeywords_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetStickerKeywordsParams{ + Sticker: "test_value", + } + _, err := SetStickerKeywords(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_SetStickerKeywords_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetStickerKeywordsParams{ + Sticker: "test_value", + } + _, err := SetStickerKeywords(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_SetStickerKeywords_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetStickerKeywordsParams{ + Sticker: "test_value", + } + _, err := SetStickerKeywords(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_SetStickerKeywords_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_SetStickerKeywords_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := SetStickerKeywords(context.Background(), bot, &SetStickerKeywordsParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_SetStickerKeywords_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_SetStickerKeywords_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetStickerKeywordsParams{ + Sticker: "test_value", + } + _, err := SetStickerKeywords(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_SetStickerKeywords_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_SetStickerKeywords_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetStickerKeywordsParams{ + Sticker: "test_value", + } + _, err := SetStickerKeywords(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_SetStickerMaskPosition_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/setStickerMaskPosition") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetStickerMaskPositionParams{ + Sticker: "test_value", + } + _, err := SetStickerMaskPosition(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_SetStickerMaskPosition_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetStickerMaskPositionParams{ + Sticker: "test_value", + } + _, err := SetStickerMaskPosition(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_SetStickerMaskPosition_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetStickerMaskPositionParams{ + Sticker: "test_value", + } + _, err := SetStickerMaskPosition(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_SetStickerMaskPosition_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetStickerMaskPositionParams{ + Sticker: "test_value", + } + _, err := SetStickerMaskPosition(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_SetStickerMaskPosition_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetStickerMaskPositionParams{ + Sticker: "test_value", + } + _, err := SetStickerMaskPosition(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_SetStickerMaskPosition_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_SetStickerMaskPosition_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := SetStickerMaskPosition(context.Background(), bot, &SetStickerMaskPositionParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_SetStickerMaskPosition_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_SetStickerMaskPosition_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetStickerMaskPositionParams{ + Sticker: "test_value", + } + _, err := SetStickerMaskPosition(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_SetStickerMaskPosition_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_SetStickerMaskPosition_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetStickerMaskPositionParams{ + Sticker: "test_value", + } + _, err := SetStickerMaskPosition(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_SetStickerSetTitle_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/setStickerSetTitle") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetStickerSetTitleParams{ + Name: "test_value", + Title: "test_value", + } + _, err := SetStickerSetTitle(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_SetStickerSetTitle_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetStickerSetTitleParams{ + Name: "test_value", + Title: "test_value", + } + _, err := SetStickerSetTitle(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_SetStickerSetTitle_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetStickerSetTitleParams{ + Name: "test_value", + Title: "test_value", + } + _, err := SetStickerSetTitle(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_SetStickerSetTitle_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetStickerSetTitleParams{ + Name: "test_value", + Title: "test_value", + } + _, err := SetStickerSetTitle(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_SetStickerSetTitle_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetStickerSetTitleParams{ + Name: "test_value", + Title: "test_value", + } + _, err := SetStickerSetTitle(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_SetStickerSetTitle_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_SetStickerSetTitle_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := SetStickerSetTitle(context.Background(), bot, &SetStickerSetTitleParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_SetStickerSetTitle_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_SetStickerSetTitle_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetStickerSetTitleParams{ + Name: "test_value", + Title: "test_value", + } + _, err := SetStickerSetTitle(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_SetStickerSetTitle_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_SetStickerSetTitle_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetStickerSetTitleParams{ + Name: "test_value", + Title: "test_value", + } + _, err := SetStickerSetTitle(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_SetStickerSetThumbnail_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/setStickerSetThumbnail") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetStickerSetThumbnailParams{ + Name: "test_value", + UserID: 42, + Format: "test_value", + } + _, err := SetStickerSetThumbnail(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_SetStickerSetThumbnail_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetStickerSetThumbnailParams{ + Name: "test_value", + UserID: 42, + Format: "test_value", + } + _, err := SetStickerSetThumbnail(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_SetStickerSetThumbnail_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetStickerSetThumbnailParams{ + Name: "test_value", + UserID: 42, + Format: "test_value", + } + _, err := SetStickerSetThumbnail(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_SetStickerSetThumbnail_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetStickerSetThumbnailParams{ + Name: "test_value", + UserID: 42, + Format: "test_value", + } + _, err := SetStickerSetThumbnail(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_SetStickerSetThumbnail_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetStickerSetThumbnailParams{ + Name: "test_value", + UserID: 42, + Format: "test_value", + } + _, err := SetStickerSetThumbnail(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_SetStickerSetThumbnail_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_SetStickerSetThumbnail_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := SetStickerSetThumbnail(context.Background(), bot, &SetStickerSetThumbnailParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_SetStickerSetThumbnail_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_SetStickerSetThumbnail_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetStickerSetThumbnailParams{ + Name: "test_value", + UserID: 42, + Format: "test_value", + } + _, err := SetStickerSetThumbnail(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_SetStickerSetThumbnail_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_SetStickerSetThumbnail_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetStickerSetThumbnailParams{ + Name: "test_value", + UserID: 42, + Format: "test_value", + } + _, err := SetStickerSetThumbnail(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_SetCustomEmojiStickerSetThumbnail_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/setCustomEmojiStickerSetThumbnail") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetCustomEmojiStickerSetThumbnailParams{ + Name: "test_value", + } + _, err := SetCustomEmojiStickerSetThumbnail(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_SetCustomEmojiStickerSetThumbnail_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetCustomEmojiStickerSetThumbnailParams{ + Name: "test_value", + } + _, err := SetCustomEmojiStickerSetThumbnail(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_SetCustomEmojiStickerSetThumbnail_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetCustomEmojiStickerSetThumbnailParams{ + Name: "test_value", + } + _, err := SetCustomEmojiStickerSetThumbnail(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_SetCustomEmojiStickerSetThumbnail_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetCustomEmojiStickerSetThumbnailParams{ + Name: "test_value", + } + _, err := SetCustomEmojiStickerSetThumbnail(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_SetCustomEmojiStickerSetThumbnail_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetCustomEmojiStickerSetThumbnailParams{ + Name: "test_value", + } + _, err := SetCustomEmojiStickerSetThumbnail(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_SetCustomEmojiStickerSetThumbnail_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_SetCustomEmojiStickerSetThumbnail_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := SetCustomEmojiStickerSetThumbnail(context.Background(), bot, &SetCustomEmojiStickerSetThumbnailParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_SetCustomEmojiStickerSetThumbnail_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_SetCustomEmojiStickerSetThumbnail_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetCustomEmojiStickerSetThumbnailParams{ + Name: "test_value", + } + _, err := SetCustomEmojiStickerSetThumbnail(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_SetCustomEmojiStickerSetThumbnail_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_SetCustomEmojiStickerSetThumbnail_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetCustomEmojiStickerSetThumbnailParams{ + Name: "test_value", + } + _, err := SetCustomEmojiStickerSetThumbnail(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_DeleteStickerSet_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/deleteStickerSet") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteStickerSetParams{ + Name: "test_value", + } + _, err := DeleteStickerSet(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_DeleteStickerSet_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteStickerSetParams{ + Name: "test_value", + } + _, err := DeleteStickerSet(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_DeleteStickerSet_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteStickerSetParams{ + Name: "test_value", + } + _, err := DeleteStickerSet(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_DeleteStickerSet_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteStickerSetParams{ + Name: "test_value", + } + _, err := DeleteStickerSet(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_DeleteStickerSet_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteStickerSetParams{ + Name: "test_value", + } + _, err := DeleteStickerSet(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_DeleteStickerSet_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_DeleteStickerSet_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := DeleteStickerSet(context.Background(), bot, &DeleteStickerSetParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_DeleteStickerSet_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_DeleteStickerSet_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteStickerSetParams{ + Name: "test_value", + } + _, err := DeleteStickerSet(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_DeleteStickerSet_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_DeleteStickerSet_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &DeleteStickerSetParams{ + Name: "test_value", + } + _, err := DeleteStickerSet(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_AnswerInlineQuery_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/answerInlineQuery") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &AnswerInlineQueryParams{ + InlineQueryID: "test_value", + Results: nil, + } + _, err := AnswerInlineQuery(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_AnswerInlineQuery_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &AnswerInlineQueryParams{ + InlineQueryID: "test_value", + Results: nil, + } + _, err := AnswerInlineQuery(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_AnswerInlineQuery_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &AnswerInlineQueryParams{ + InlineQueryID: "test_value", + Results: nil, + } + _, err := AnswerInlineQuery(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_AnswerInlineQuery_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &AnswerInlineQueryParams{ + InlineQueryID: "test_value", + Results: nil, + } + _, err := AnswerInlineQuery(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_AnswerInlineQuery_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &AnswerInlineQueryParams{ + InlineQueryID: "test_value", + Results: nil, + } + _, err := AnswerInlineQuery(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_AnswerInlineQuery_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_AnswerInlineQuery_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := AnswerInlineQuery(context.Background(), bot, &AnswerInlineQueryParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_AnswerInlineQuery_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_AnswerInlineQuery_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &AnswerInlineQueryParams{ + InlineQueryID: "test_value", + Results: nil, + } + _, err := AnswerInlineQuery(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_AnswerInlineQuery_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_AnswerInlineQuery_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &AnswerInlineQueryParams{ + InlineQueryID: "test_value", + Results: nil, + } + _, err := AnswerInlineQuery(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_SendInvoice_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/sendInvoice") + })).Return(genTestResp(200, `{"ok":true,"result":{}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendInvoiceParams{ + ChatID: ChatIDFromInt(123), + Title: "test_value", + Description: "test_value", + Payload: "test_value", + Currency: "test_value", + Prices: nil, + } + _, err := SendInvoice(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_SendInvoice_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendInvoiceParams{ + ChatID: ChatIDFromInt(123), + Title: "test_value", + Description: "test_value", + Payload: "test_value", + Currency: "test_value", + Prices: nil, + } + _, err := SendInvoice(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_SendInvoice_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendInvoiceParams{ + ChatID: ChatIDFromInt(123), + Title: "test_value", + Description: "test_value", + Payload: "test_value", + Currency: "test_value", + Prices: nil, + } + _, err := SendInvoice(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_SendInvoice_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendInvoiceParams{ + ChatID: ChatIDFromInt(123), + Title: "test_value", + Description: "test_value", + Payload: "test_value", + Currency: "test_value", + Prices: nil, + } + _, err := SendInvoice(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_SendInvoice_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendInvoiceParams{ + ChatID: ChatIDFromInt(123), + Title: "test_value", + Description: "test_value", + Payload: "test_value", + Currency: "test_value", + Prices: nil, + } + _, err := SendInvoice(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_SendInvoice_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_SendInvoice_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := SendInvoice(context.Background(), bot, &SendInvoiceParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_SendInvoice_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_SendInvoice_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendInvoiceParams{ + ChatID: ChatIDFromInt(123), + Title: "test_value", + Description: "test_value", + Payload: "test_value", + Currency: "test_value", + Prices: nil, + } + _, err := SendInvoice(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_SendInvoice_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_SendInvoice_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendInvoiceParams{ + ChatID: ChatIDFromInt(123), + Title: "test_value", + Description: "test_value", + Payload: "test_value", + Currency: "test_value", + Prices: nil, + } + _, err := SendInvoice(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_CreateInvoiceLink_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/createInvoiceLink") + })).Return(genTestResp(200, `{"ok":true,"result":""}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &CreateInvoiceLinkParams{ + Title: "test_value", + Description: "test_value", + Payload: "test_value", + Currency: "test_value", + Prices: nil, + } + _, err := CreateInvoiceLink(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_CreateInvoiceLink_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &CreateInvoiceLinkParams{ + Title: "test_value", + Description: "test_value", + Payload: "test_value", + Currency: "test_value", + Prices: nil, + } + _, err := CreateInvoiceLink(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_CreateInvoiceLink_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &CreateInvoiceLinkParams{ + Title: "test_value", + Description: "test_value", + Payload: "test_value", + Currency: "test_value", + Prices: nil, + } + _, err := CreateInvoiceLink(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_CreateInvoiceLink_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &CreateInvoiceLinkParams{ + Title: "test_value", + Description: "test_value", + Payload: "test_value", + Currency: "test_value", + Prices: nil, + } + _, err := CreateInvoiceLink(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_CreateInvoiceLink_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &CreateInvoiceLinkParams{ + Title: "test_value", + Description: "test_value", + Payload: "test_value", + Currency: "test_value", + Prices: nil, + } + _, err := CreateInvoiceLink(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_CreateInvoiceLink_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_CreateInvoiceLink_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := CreateInvoiceLink(context.Background(), bot, &CreateInvoiceLinkParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_CreateInvoiceLink_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_CreateInvoiceLink_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &CreateInvoiceLinkParams{ + Title: "test_value", + Description: "test_value", + Payload: "test_value", + Currency: "test_value", + Prices: nil, + } + _, err := CreateInvoiceLink(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_CreateInvoiceLink_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_CreateInvoiceLink_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &CreateInvoiceLinkParams{ + Title: "test_value", + Description: "test_value", + Payload: "test_value", + Currency: "test_value", + Prices: nil, + } + _, err := CreateInvoiceLink(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_AnswerShippingQuery_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/answerShippingQuery") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &AnswerShippingQueryParams{ + ShippingQueryID: "test_value", + Ok: true, + } + _, err := AnswerShippingQuery(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_AnswerShippingQuery_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &AnswerShippingQueryParams{ + ShippingQueryID: "test_value", + Ok: true, + } + _, err := AnswerShippingQuery(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_AnswerShippingQuery_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &AnswerShippingQueryParams{ + ShippingQueryID: "test_value", + Ok: true, + } + _, err := AnswerShippingQuery(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_AnswerShippingQuery_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &AnswerShippingQueryParams{ + ShippingQueryID: "test_value", + Ok: true, + } + _, err := AnswerShippingQuery(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_AnswerShippingQuery_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &AnswerShippingQueryParams{ + ShippingQueryID: "test_value", + Ok: true, + } + _, err := AnswerShippingQuery(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_AnswerShippingQuery_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_AnswerShippingQuery_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := AnswerShippingQuery(context.Background(), bot, &AnswerShippingQueryParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_AnswerShippingQuery_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_AnswerShippingQuery_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &AnswerShippingQueryParams{ + ShippingQueryID: "test_value", + Ok: true, + } + _, err := AnswerShippingQuery(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_AnswerShippingQuery_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_AnswerShippingQuery_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &AnswerShippingQueryParams{ + ShippingQueryID: "test_value", + Ok: true, + } + _, err := AnswerShippingQuery(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_AnswerPreCheckoutQuery_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/answerPreCheckoutQuery") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &AnswerPreCheckoutQueryParams{ + PreCheckoutQueryID: "test_value", + Ok: true, + } + _, err := AnswerPreCheckoutQuery(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_AnswerPreCheckoutQuery_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &AnswerPreCheckoutQueryParams{ + PreCheckoutQueryID: "test_value", + Ok: true, + } + _, err := AnswerPreCheckoutQuery(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_AnswerPreCheckoutQuery_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &AnswerPreCheckoutQueryParams{ + PreCheckoutQueryID: "test_value", + Ok: true, + } + _, err := AnswerPreCheckoutQuery(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_AnswerPreCheckoutQuery_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &AnswerPreCheckoutQueryParams{ + PreCheckoutQueryID: "test_value", + Ok: true, + } + _, err := AnswerPreCheckoutQuery(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_AnswerPreCheckoutQuery_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &AnswerPreCheckoutQueryParams{ + PreCheckoutQueryID: "test_value", + Ok: true, + } + _, err := AnswerPreCheckoutQuery(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_AnswerPreCheckoutQuery_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_AnswerPreCheckoutQuery_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := AnswerPreCheckoutQuery(context.Background(), bot, &AnswerPreCheckoutQueryParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_AnswerPreCheckoutQuery_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_AnswerPreCheckoutQuery_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &AnswerPreCheckoutQueryParams{ + PreCheckoutQueryID: "test_value", + Ok: true, + } + _, err := AnswerPreCheckoutQuery(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_AnswerPreCheckoutQuery_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_AnswerPreCheckoutQuery_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &AnswerPreCheckoutQueryParams{ + PreCheckoutQueryID: "test_value", + Ok: true, + } + _, err := AnswerPreCheckoutQuery(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_GetMyStarBalance_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/getMyStarBalance") + })).Return(genTestResp(200, `{"ok":true,"result":{}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + _, err := GetMyStarBalance(context.Background(), bot, &GetMyStarBalanceParams{}) + require.NoError(t, err) +} + +func Test_GetMyStarBalance_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + _, err := GetMyStarBalance(context.Background(), bot, &GetMyStarBalanceParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_GetMyStarBalance_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + _, err := GetMyStarBalance(context.Background(), bot, &GetMyStarBalanceParams{}) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_GetMyStarBalance_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + _, err := GetMyStarBalance(context.Background(), bot, &GetMyStarBalanceParams{}) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_GetMyStarBalance_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + _, err := GetMyStarBalance(ctx, bot, &GetMyStarBalanceParams{}) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_GetMyStarBalance_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_GetMyStarBalance_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := GetMyStarBalance(context.Background(), bot, &GetMyStarBalanceParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_GetMyStarBalance_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_GetMyStarBalance_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + _, err := GetMyStarBalance(context.Background(), bot, &GetMyStarBalanceParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_GetMyStarBalance_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_GetMyStarBalance_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + _, err := GetMyStarBalance(context.Background(), bot, &GetMyStarBalanceParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_GetStarTransactions_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/getStarTransactions") + })).Return(genTestResp(200, `{"ok":true,"result":{}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetStarTransactionsParams{} + _, err := GetStarTransactions(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_GetStarTransactions_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetStarTransactionsParams{} + _, err := GetStarTransactions(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_GetStarTransactions_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetStarTransactionsParams{} + _, err := GetStarTransactions(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_GetStarTransactions_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetStarTransactionsParams{} + _, err := GetStarTransactions(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_GetStarTransactions_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetStarTransactionsParams{} + _, err := GetStarTransactions(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_GetStarTransactions_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_GetStarTransactions_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := GetStarTransactions(context.Background(), bot, &GetStarTransactionsParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_GetStarTransactions_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_GetStarTransactions_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetStarTransactionsParams{} + _, err := GetStarTransactions(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_GetStarTransactions_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_GetStarTransactions_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetStarTransactionsParams{} + _, err := GetStarTransactions(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_RefundStarPayment_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/refundStarPayment") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &RefundStarPaymentParams{ + UserID: 42, + TelegramPaymentChargeID: "test_value", + } + _, err := RefundStarPayment(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_RefundStarPayment_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &RefundStarPaymentParams{ + UserID: 42, + TelegramPaymentChargeID: "test_value", + } + _, err := RefundStarPayment(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_RefundStarPayment_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &RefundStarPaymentParams{ + UserID: 42, + TelegramPaymentChargeID: "test_value", + } + _, err := RefundStarPayment(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_RefundStarPayment_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &RefundStarPaymentParams{ + UserID: 42, + TelegramPaymentChargeID: "test_value", + } + _, err := RefundStarPayment(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_RefundStarPayment_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &RefundStarPaymentParams{ + UserID: 42, + TelegramPaymentChargeID: "test_value", + } + _, err := RefundStarPayment(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_RefundStarPayment_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_RefundStarPayment_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := RefundStarPayment(context.Background(), bot, &RefundStarPaymentParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_RefundStarPayment_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_RefundStarPayment_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &RefundStarPaymentParams{ + UserID: 42, + TelegramPaymentChargeID: "test_value", + } + _, err := RefundStarPayment(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_RefundStarPayment_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_RefundStarPayment_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &RefundStarPaymentParams{ + UserID: 42, + TelegramPaymentChargeID: "test_value", + } + _, err := RefundStarPayment(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_EditUserStarSubscription_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/editUserStarSubscription") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditUserStarSubscriptionParams{ + UserID: 42, + TelegramPaymentChargeID: "test_value", + IsCanceled: true, + } + _, err := EditUserStarSubscription(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_EditUserStarSubscription_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditUserStarSubscriptionParams{ + UserID: 42, + TelegramPaymentChargeID: "test_value", + IsCanceled: true, + } + _, err := EditUserStarSubscription(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_EditUserStarSubscription_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditUserStarSubscriptionParams{ + UserID: 42, + TelegramPaymentChargeID: "test_value", + IsCanceled: true, + } + _, err := EditUserStarSubscription(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_EditUserStarSubscription_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditUserStarSubscriptionParams{ + UserID: 42, + TelegramPaymentChargeID: "test_value", + IsCanceled: true, + } + _, err := EditUserStarSubscription(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_EditUserStarSubscription_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditUserStarSubscriptionParams{ + UserID: 42, + TelegramPaymentChargeID: "test_value", + IsCanceled: true, + } + _, err := EditUserStarSubscription(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_EditUserStarSubscription_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_EditUserStarSubscription_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := EditUserStarSubscription(context.Background(), bot, &EditUserStarSubscriptionParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_EditUserStarSubscription_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_EditUserStarSubscription_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditUserStarSubscriptionParams{ + UserID: 42, + TelegramPaymentChargeID: "test_value", + IsCanceled: true, + } + _, err := EditUserStarSubscription(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_EditUserStarSubscription_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_EditUserStarSubscription_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &EditUserStarSubscriptionParams{ + UserID: 42, + TelegramPaymentChargeID: "test_value", + IsCanceled: true, + } + _, err := EditUserStarSubscription(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_SetPassportDataErrors_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/setPassportDataErrors") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetPassportDataErrorsParams{ + UserID: 42, + Errors: nil, + } + _, err := SetPassportDataErrors(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_SetPassportDataErrors_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetPassportDataErrorsParams{ + UserID: 42, + Errors: nil, + } + _, err := SetPassportDataErrors(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_SetPassportDataErrors_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetPassportDataErrorsParams{ + UserID: 42, + Errors: nil, + } + _, err := SetPassportDataErrors(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_SetPassportDataErrors_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetPassportDataErrorsParams{ + UserID: 42, + Errors: nil, + } + _, err := SetPassportDataErrors(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_SetPassportDataErrors_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetPassportDataErrorsParams{ + UserID: 42, + Errors: nil, + } + _, err := SetPassportDataErrors(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_SetPassportDataErrors_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_SetPassportDataErrors_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := SetPassportDataErrors(context.Background(), bot, &SetPassportDataErrorsParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_SetPassportDataErrors_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_SetPassportDataErrors_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetPassportDataErrorsParams{ + UserID: 42, + Errors: nil, + } + _, err := SetPassportDataErrors(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_SetPassportDataErrors_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_SetPassportDataErrors_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetPassportDataErrorsParams{ + UserID: 42, + Errors: nil, + } + _, err := SetPassportDataErrors(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_SendGame_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/sendGame") + })).Return(genTestResp(200, `{"ok":true,"result":{}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendGameParams{ + ChatID: ChatIDFromInt(123), + GameShortName: "test_value", + } + _, err := SendGame(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_SendGame_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendGameParams{ + ChatID: ChatIDFromInt(123), + GameShortName: "test_value", + } + _, err := SendGame(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_SendGame_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendGameParams{ + ChatID: ChatIDFromInt(123), + GameShortName: "test_value", + } + _, err := SendGame(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_SendGame_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendGameParams{ + ChatID: ChatIDFromInt(123), + GameShortName: "test_value", + } + _, err := SendGame(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_SendGame_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendGameParams{ + ChatID: ChatIDFromInt(123), + GameShortName: "test_value", + } + _, err := SendGame(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_SendGame_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_SendGame_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := SendGame(context.Background(), bot, &SendGameParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_SendGame_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_SendGame_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendGameParams{ + ChatID: ChatIDFromInt(123), + GameShortName: "test_value", + } + _, err := SendGame(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_SendGame_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_SendGame_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendGameParams{ + ChatID: ChatIDFromInt(123), + GameShortName: "test_value", + } + _, err := SendGame(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_SetGameScore_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/setGameScore") + })).Return(genTestResp(200, `{"ok":true,"result":true}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetGameScoreParams{ + UserID: 42, + Score: 42, + } + _, err := SetGameScore(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_SetGameScore_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetGameScoreParams{ + UserID: 42, + Score: 42, + } + _, err := SetGameScore(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_SetGameScore_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetGameScoreParams{ + UserID: 42, + Score: 42, + } + _, err := SetGameScore(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_SetGameScore_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetGameScoreParams{ + UserID: 42, + Score: 42, + } + _, err := SetGameScore(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_SetGameScore_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetGameScoreParams{ + UserID: 42, + Score: 42, + } + _, err := SetGameScore(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_SetGameScore_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_SetGameScore_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := SetGameScore(context.Background(), bot, &SetGameScoreParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_SetGameScore_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_SetGameScore_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetGameScoreParams{ + UserID: 42, + Score: 42, + } + _, err := SetGameScore(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_SetGameScore_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_SetGameScore_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SetGameScoreParams{ + UserID: 42, + Score: 42, + } + _, err := SetGameScore(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_GetGameHighScores_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/getGameHighScores") + })).Return(genTestResp(200, `{"ok":true,"result":[]}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetGameHighScoresParams{ + UserID: 42, + } + _, err := GetGameHighScores(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_GetGameHighScores_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetGameHighScoresParams{ + UserID: 42, + } + _, err := GetGameHighScores(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_GetGameHighScores_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetGameHighScoresParams{ + UserID: 42, + } + _, err := GetGameHighScores(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_GetGameHighScores_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetGameHighScoresParams{ + UserID: 42, + } + _, err := GetGameHighScores(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_GetGameHighScores_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetGameHighScoresParams{ + UserID: 42, + } + _, err := GetGameHighScores(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_GetGameHighScores_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_GetGameHighScores_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := GetGameHighScores(context.Background(), bot, &GetGameHighScoresParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_GetGameHighScores_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_GetGameHighScores_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetGameHighScoresParams{ + UserID: 42, + } + _, err := GetGameHighScores(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_GetGameHighScores_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_GetGameHighScores_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetGameHighScoresParams{ + UserID: 42, + } + _, err := GetGameHighScores(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} diff --git a/api/runtime.go b/api/runtime.go new file mode 100644 index 0000000..a430c38 --- /dev/null +++ b/api/runtime.go @@ -0,0 +1,143 @@ +// Package api contains the Telegram Bot API types and method wrappers. +// Most of the package is generated by cmd/genapi from internal/spec/api.json; +// this file holds the runtime types that are intentionally hand-coded. +// +// InputFile carries either a local upload (Reader+Filename) or a reference +// to a previously-uploaded file (file_id) / URL Telegram can fetch. It is +// not a pure JSON type, so the codegen skips it (see runtimeTypes in +// cmd/genapi/emitter.go). +// +// ResponseParameters mirrors client.ResponseParameters so callers importing +// only `api` can access retry_after and migrate_to_chat_id without pulling +// in the client package. +package api + +import ( + "bytes" + "fmt" + "github.com/goccy/go-json" + "io" + "strconv" +) + +// InputFile carries either a file path (for upload) or a Telegram file_id +// / URL string (for reuse). When PathOrID names a local file, the request +// is sent as multipart/form-data; otherwise the value is sent inline. +type InputFile struct { + // PathOrID is one of: an absolute or relative filesystem path, a + // previously-uploaded Telegram file_id, or an HTTPS URL Telegram + // can fetch. + PathOrID string + // Reader, when non-nil, is used as the file content (Filename names it). + Reader io.Reader + // Filename is the upload filename used when Reader is set. + Filename string +} + +// IsLocalUpload reports whether this InputFile triggers a multipart upload. +func (f *InputFile) IsLocalUpload() bool { + if f == nil { + return false + } + return f.Reader != nil +} + +// ResponseParameters is the optional metadata Telegram includes on certain +// failures. The most common is RetryAfter (seconds) on 429 responses. +// +// https://core.telegram.org/bots/api#responseparameters +type ResponseParameters struct { + MigrateToChatID int64 `json:"migrate_to_chat_id,omitempty"` + RetryAfter int `json:"retry_after,omitempty"` +} + +// ChatID identifies a chat by either numeric id or "@username". The Telegram +// Bot API spells the same field as either an integer or a string; ChatID +// preserves both forms with explicit constructors and a custom MarshalJSON +// so callers never see `any` at the source level. +type ChatID struct { + int64Set bool + intID int64 + username string +} + +// ChatIDFromInt builds a ChatID for a numeric chat identifier (e.g. -1001234567890). +func ChatIDFromInt(id int64) ChatID { return ChatID{int64Set: true, intID: id} } + +// ChatIDFromUsername builds a ChatID for a public chat (e.g. "@channel"). +// The leading "@" is required by Telegram for usernames. +func ChatIDFromUsername(name string) ChatID { return ChatID{username: name} } + +// IsZero reports whether c carries no value. +func (c ChatID) IsZero() bool { return !c.int64Set && c.username == "" } + +// String returns the wire form (decimal integer or "@name") for use in +// multipart bodies. +func (c ChatID) String() string { + if c.int64Set { + return strconv.FormatInt(c.intID, 10) + } + return c.username +} + +// MarshalJSON emits either a JSON number (integer form) or a JSON string +// (@username form). Empty values marshal as "null". +func (c ChatID) MarshalJSON() ([]byte, error) { + if c.int64Set { + return []byte(strconv.FormatInt(c.intID, 10)), nil + } + if c.username != "" { + return json.Marshal(c.username) + } + return []byte("null"), nil +} + +// UnmarshalJSON accepts either a JSON number or a JSON string. +func (c *ChatID) UnmarshalJSON(data []byte) error { + data = bytes.TrimSpace(data) + if len(data) == 0 || bytes.Equal(data, []byte("null")) { + *c = ChatID{} + return nil + } + if data[0] == '"' { + var s string + if err := json.Unmarshal(data, &s); err != nil { + return err + } + *c = ChatIDFromUsername(s) + return nil + } + var n int64 + if err := json.Unmarshal(data, &n); err != nil { + return fmt.Errorf("ChatID: %w", err) + } + *c = ChatIDFromInt(n) + return nil +} + +// MessageOrBool wraps the "Message or True" return shape Telegram uses on +// edit methods (editMessageText, editMessageCaption, etc.). When the bot +// edits a regular chat message, Message is non-nil; when it edits an +// inline message, OK is true. +type MessageOrBool struct { + Message *Message + OK bool +} + +// UnmarshalJSON decodes either {...} into Message or `true`/`false` into OK. +func (m *MessageOrBool) UnmarshalJSON(data []byte) error { + data = bytes.TrimSpace(data) + if len(data) == 0 { + return nil + } + if data[0] == '{' { + m.Message = new(Message) + return json.Unmarshal(data, m.Message) + } + var b bool + if err := json.Unmarshal(data, &b); err != nil { + return fmt.Errorf("MessageOrBool: %w", err) + } + m.OK = b + return nil +} diff --git a/api/runtime_test.go b/api/runtime_test.go new file mode 100644 index 0000000..e4c6ed7 --- /dev/null +++ b/api/runtime_test.go @@ -0,0 +1,93 @@ +package api + +import ( + "encoding/json" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestChatID_IntForm(t *testing.T) { + c := ChatIDFromInt(-1001234567890) + require.False(t, c.IsZero()) + require.Equal(t, "-1001234567890", c.String()) + + data, err := json.Marshal(c) + require.NoError(t, err) + require.Equal(t, "-1001234567890", string(data)) + + var c2 ChatID + require.NoError(t, json.Unmarshal(data, &c2)) + require.Equal(t, c, c2) +} + +func TestChatID_UsernameForm(t *testing.T) { + c := ChatIDFromUsername("@channel") + require.False(t, c.IsZero()) + require.Equal(t, "@channel", c.String()) + + data, err := json.Marshal(c) + require.NoError(t, err) + require.Equal(t, `"@channel"`, string(data)) + + var c2 ChatID + require.NoError(t, json.Unmarshal(data, &c2)) + require.Equal(t, c, c2) +} + +func TestChatID_Zero(t *testing.T) { + var c ChatID + require.True(t, c.IsZero()) + require.Equal(t, "", c.String()) + + data, err := json.Marshal(c) + require.NoError(t, err) + require.Equal(t, "null", string(data)) + + var c2 ChatID + require.NoError(t, json.Unmarshal([]byte("null"), &c2)) + require.True(t, c2.IsZero()) +} + +func TestChatID_UnmarshalInvalid(t *testing.T) { + var c ChatID + err := json.Unmarshal([]byte(`"not-a-number"`), &c) + require.NoError(t, err) // string always succeeds as username + require.Equal(t, "not-a-number", c.username) +} + +func TestMessageOrBool_TrueForm(t *testing.T) { + var m MessageOrBool + require.NoError(t, json.Unmarshal([]byte("true"), &m)) + require.True(t, m.OK) + require.Nil(t, m.Message) +} + +func TestMessageOrBool_FalseForm(t *testing.T) { + var m MessageOrBool + require.NoError(t, json.Unmarshal([]byte("false"), &m)) + require.False(t, m.OK) + require.Nil(t, m.Message) +} + +func TestMessageOrBool_MessageForm(t *testing.T) { + // Message is a generated type; we can only test that it unmarshals without + // error into the struct — the generated api/*.gen.go is not available in + // the test build unless built. Use build tag !ignore_autogenerated default. + // Skip if Message type is not yet present (bootstrap phase). + data := []byte(`{"message_id":42,"date":0,"chat":{"id":1,"type":"private"}}`) + var m MessageOrBool + require.NoError(t, json.Unmarshal(data, &m)) + require.NotNil(t, m.Message) + require.False(t, m.OK) +} + +func TestInputFile_IsLocalUpload(t *testing.T) { + require.False(t, (*InputFile)(nil).IsLocalUpload()) + require.False(t, (&InputFile{PathOrID: "AgADAgADu7gxG..."}).IsLocalUpload()) + require.True(t, (&InputFile{Reader: nopReader{}}).IsLocalUpload()) +} + +type nopReader struct{} + +func (nopReader) Read(p []byte) (int, error) { return 0, nil } diff --git a/api/sender.go b/api/sender.go new file mode 100644 index 0000000..ffad909 --- /dev/null +++ b/api/sender.go @@ -0,0 +1,90 @@ +package api + +// Sender condenses the various ways a Telegram update can identify the +// originator of a message or reaction into a single shape. Use the +// GetSender methods on supported types to construct one. +type Sender struct { + // User is the human user who sent the update, when applicable. + User *User + // Chat is the chat that sent the update (channel forwards, + // anonymous group admins, anonymous channel posts). + Chat *Chat + // IsAutomaticForward is true when the update originated as an + // automatic forward from a linked channel. + IsAutomaticForward bool + // ChatID is the chat the update was delivered into. Used to + // distinguish "this user" from "this anonymous admin posting + // in " when User is nil. + ChatID int64 + // AuthorSignature is the custom title of an anonymous group + // administrator. Only meaningful when Chat == this chat. + AuthorSignature string +} + +// ID returns the most-specific identifier available: prefers Chat.ID +// over User.ID. Returns 0 if neither is set. +func (s *Sender) ID() int64 { + if s == nil { + return 0 + } + if s.Chat != nil { + return s.Chat.ID + } + if s.User != nil { + return s.User.ID + } + return 0 +} + +// IsAnonymousAdmin reports whether the sender is a group admin posting +// anonymously (Chat equals the message's own chat). +func (s *Sender) IsAnonymousAdmin() bool { + return s != nil && s.Chat != nil && s.Chat.ID == s.ChatID +} + +// IsAnonymousChannel reports whether the sender is an anonymous +// channel post (Chat differs from the message's own chat). +func (s *Sender) IsAnonymousChannel() bool { + return s != nil && s.Chat != nil && s.Chat.ID != s.ChatID +} + +// GetSender constructs a Sender for a Message. The result is never nil. +func (m *Message) GetSender() *Sender { + if m == nil { + return &Sender{} + } + isAuto := false + if m.IsAutomaticForward != nil { + isAuto = *m.IsAutomaticForward + } + return &Sender{ + User: m.From, + Chat: m.SenderChat, + IsAutomaticForward: isAuto, + ChatID: m.Chat.ID, + AuthorSignature: m.AuthorSignature, + } +} + +// GetSender constructs a Sender for a MessageReactionUpdated. +func (mru *MessageReactionUpdated) GetSender() *Sender { + if mru == nil { + return &Sender{} + } + return &Sender{ + User: mru.User, + Chat: mru.ActorChat, + ChatID: mru.Chat.ID, + } +} + +// GetSender constructs a Sender for a PollAnswer. +func (pa *PollAnswer) GetSender() *Sender { + if pa == nil { + return &Sender{} + } + return &Sender{ + User: pa.User, + Chat: pa.VoterChat, + } +} diff --git a/api/sender_test.go b/api/sender_test.go new file mode 100644 index 0000000..1933297 --- /dev/null +++ b/api/sender_test.go @@ -0,0 +1,366 @@ +package api + +import ( + "testing" +) + +func TestSenderID(t *testing.T) { + tests := []struct { + name string + sender *Sender + want int64 + }{ + { + name: "nil sender", + sender: nil, + want: 0, + }, + { + name: "empty sender", + sender: &Sender{}, + want: 0, + }, + { + name: "user only", + sender: &Sender{ + User: &User{ID: 123}, + }, + want: 123, + }, + { + name: "chat only", + sender: &Sender{ + Chat: &Chat{ID: 456}, + }, + want: 456, + }, + { + name: "chat prefers over user", + sender: &Sender{ + User: &User{ID: 123}, + Chat: &Chat{ID: 456}, + }, + want: 456, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := tt.sender.ID() + if got != tt.want { + t.Errorf("ID() = %d, want %d", got, tt.want) + } + }) + } +} + +func chatEqual(a, b *Chat) bool { + if a == nil && b == nil { + return true + } + if a == nil || b == nil { + return false + } + return a.ID == b.ID +} + +func userEqual(a, b *User) bool { + if a == nil && b == nil { + return true + } + if a == nil || b == nil { + return false + } + return a.ID == b.ID +} + +func TestSenderIsAnonymousAdmin(t *testing.T) { + tests := []struct { + name string + sender *Sender + want bool + }{ + { + name: "nil sender", + sender: nil, + want: false, + }, + { + name: "no chat", + sender: &Sender{User: &User{ID: 123}, ChatID: 456}, + want: false, + }, + { + name: "chat id matches (anonymous admin)", + sender: &Sender{ + Chat: &Chat{ID: 789}, + ChatID: 789, + }, + want: true, + }, + { + name: "chat id differs (not anonymous admin)", + sender: &Sender{ + Chat: &Chat{ID: 789}, + ChatID: 456, + }, + want: false, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := tt.sender.IsAnonymousAdmin() + if got != tt.want { + t.Errorf("IsAnonymousAdmin() = %v, want %v", got, tt.want) + } + }) + } +} + +func TestSenderIsAnonymousChannel(t *testing.T) { + tests := []struct { + name string + sender *Sender + want bool + }{ + { + name: "nil sender", + sender: nil, + want: false, + }, + { + name: "no chat", + sender: &Sender{User: &User{ID: 123}, ChatID: 456}, + want: false, + }, + { + name: "chat id differs (anonymous channel)", + sender: &Sender{ + Chat: &Chat{ID: 789}, + ChatID: 456, + }, + want: true, + }, + { + name: "chat id matches (not anonymous channel)", + sender: &Sender{ + Chat: &Chat{ID: 789}, + ChatID: 789, + }, + want: false, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := tt.sender.IsAnonymousChannel() + if got != tt.want { + t.Errorf("IsAnonymousChannel() = %v, want %v", got, tt.want) + } + }) + } +} + +func TestMessageGetSender(t *testing.T) { + tests := []struct { + name string + msg *Message + want *Sender + }{ + { + name: "nil message", + msg: nil, + want: &Sender{}, + }, + { + name: "regular user message", + msg: &Message{ + From: &User{ID: 123}, + Chat: Chat{ID: 456}, + }, + want: &Sender{ + User: &User{ID: 123}, + ChatID: 456, + }, + }, + { + name: "channel forward", + msg: &Message{ + From: &User{ID: 123}, + SenderChat: &Chat{ID: 789}, + Chat: Chat{ID: 456}, + }, + want: &Sender{ + User: &User{ID: 123}, + Chat: &Chat{ID: 789}, + ChatID: 456, + }, + }, + { + name: "anonymous admin", + msg: &Message{ + SenderChat: &Chat{ID: 456}, + Chat: Chat{ID: 456}, + AuthorSignature: "Admin Signature", + }, + want: &Sender{ + Chat: &Chat{ID: 456}, + ChatID: 456, + AuthorSignature: "Admin Signature", + }, + }, + { + name: "anonymous channel post", + msg: &Message{ + SenderChat: &Chat{ID: 789}, + Chat: Chat{ID: 456}, + }, + want: &Sender{ + Chat: &Chat{ID: 789}, + ChatID: 456, + }, + }, + { + name: "automatic forward", + msg: &Message{ + From: &User{ID: 123}, + IsAutomaticForward: func() *bool { + b := true + return &b + }(), + Chat: Chat{ID: 456}, + }, + want: &Sender{ + User: &User{ID: 123}, + IsAutomaticForward: true, + ChatID: 456, + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := tt.msg.GetSender() + if got == nil { + t.Fatal("GetSender() returned nil") + } + if !userEqual(got.User, tt.want.User) { + t.Errorf("User: got %v, want %v", got.User, tt.want.User) + } + if !chatEqual(got.Chat, tt.want.Chat) { + t.Errorf("Chat: got %v, want %v", got.Chat, tt.want.Chat) + } + if got.IsAutomaticForward != tt.want.IsAutomaticForward { + t.Errorf("IsAutomaticForward: got %v, want %v", got.IsAutomaticForward, tt.want.IsAutomaticForward) + } + if got.ChatID != tt.want.ChatID { + t.Errorf("ChatID: got %d, want %d", got.ChatID, tt.want.ChatID) + } + if got.AuthorSignature != tt.want.AuthorSignature { + t.Errorf("AuthorSignature: got %q, want %q", got.AuthorSignature, tt.want.AuthorSignature) + } + }) + } +} + +func TestMessageReactionUpdatedGetSender(t *testing.T) { + tests := []struct { + name string + mru *MessageReactionUpdated + want *Sender + }{ + { + name: "nil reaction", + mru: nil, + want: &Sender{}, + }, + { + name: "user reaction", + mru: &MessageReactionUpdated{ + User: &User{ID: 123}, + Chat: Chat{ID: 456}, + }, + want: &Sender{ + User: &User{ID: 123}, + ChatID: 456, + }, + }, + { + name: "anonymous reaction", + mru: &MessageReactionUpdated{ + ActorChat: &Chat{ID: 789}, + Chat: Chat{ID: 456}, + }, + want: &Sender{ + Chat: &Chat{ID: 789}, + ChatID: 456, + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := tt.mru.GetSender() + if got == nil { + t.Fatal("GetSender() returned nil") + } + if !userEqual(got.User, tt.want.User) { + t.Errorf("User: got %v, want %v", got.User, tt.want.User) + } + if !chatEqual(got.Chat, tt.want.Chat) { + t.Errorf("Chat: got %v, want %v", got.Chat, tt.want.Chat) + } + if got.ChatID != tt.want.ChatID { + t.Errorf("ChatID: got %d, want %d", got.ChatID, tt.want.ChatID) + } + }) + } +} + +func TestPollAnswerGetSender(t *testing.T) { + tests := []struct { + name string + pa *PollAnswer + want *Sender + }{ + { + name: "nil poll answer", + pa: nil, + want: &Sender{}, + }, + { + name: "user vote", + pa: &PollAnswer{ + User: &User{ID: 123}, + }, + want: &Sender{ + User: &User{ID: 123}, + }, + }, + { + name: "anonymous vote", + pa: &PollAnswer{ + VoterChat: &Chat{ID: 789}, + }, + want: &Sender{ + Chat: &Chat{ID: 789}, + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := tt.pa.GetSender() + if got == nil { + t.Fatal("GetSender() returned nil") + } + if !userEqual(got.User, tt.want.User) { + t.Errorf("User: got %v, want %v", got.User, tt.want.User) + } + if !chatEqual(got.Chat, tt.want.Chat) { + t.Errorf("Chat: got %v, want %v", got.Chat, tt.want.Chat) + } + }) + } +} diff --git a/api/testhelpers_test.go b/api/testhelpers_test.go new file mode 100644 index 0000000..396662b --- /dev/null +++ b/api/testhelpers_test.go @@ -0,0 +1,29 @@ +package api + +import ( + "bytes" + "io" + "net/http" + + "github.com/stretchr/testify/mock" +) + +// mockDoer is a testify-mock HTTPDoer shared by hand-written tests. +type mockDoer struct{ mock.Mock } + +func (m *mockDoer) Do(r *http.Request) (*http.Response, error) { + args := m.Called(r) + if v := args.Get(0); v != nil { + return v.(*http.Response), args.Error(1) + } + return nil, args.Error(1) +} + +// newJSONResp constructs an *http.Response with a JSON body. +func newJSONResp(status int, body string) *http.Response { + return &http.Response{ + StatusCode: status, + Body: io.NopCloser(bytes.NewBufferString(body)), + Header: http.Header{"Content-Type": []string{"application/json"}}, + } +} diff --git a/api/types.gen.go b/api/types.gen.go new file mode 100644 index 0000000..c68500c --- /dev/null +++ b/api/types.gen.go @@ -0,0 +1,5871 @@ +// Code generated by cmd/genapi. DO NOT EDIT. + +//go:build !ignore_autogenerated + +// Package api contains the Telegram Bot API object types and method +// wrappers, generated from the live documentation by cmd/genapi. +package api + +import ( + "fmt" + "github.com/goccy/go-json" + "io" +) + +var _ = io.Discard // keep import even if no fields use io +var _ = json.Marshal // keep import for UnmarshalXxx helpers +var _ = fmt.Errorf // keep import for UnmarshalXxx helpers + +// This object represents an incoming update.At most one of the optional fields can be present in any given update. +type Update struct { + // The update's unique identifier. Update identifiers start from a certain positive number and increase sequentially. This identifier becomes especially handy if you're using webhooks, since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order. If there are no new updates for at least a week, then identifier of the next update will be chosen randomly instead of sequentially. + UpdateID int64 `json:"update_id"` + // Optional. New incoming message of any kind - text, photo, sticker, etc. + Message *Message `json:"message,omitempty"` + // Optional. New version of a message that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot. + EditedMessage *Message `json:"edited_message,omitempty"` + // Optional. New incoming channel post of any kind - text, photo, sticker, etc. + ChannelPost *Message `json:"channel_post,omitempty"` + // Optional. New version of a channel post that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot. + EditedChannelPost *Message `json:"edited_channel_post,omitempty"` + // Optional. The bot was connected to or disconnected from a business account, or a user edited an existing connection with the bot + BusinessConnection *BusinessConnection `json:"business_connection,omitempty"` + // Optional. New message from a connected business account + BusinessMessage *Message `json:"business_message,omitempty"` + // Optional. New version of a message from a connected business account + EditedBusinessMessage *Message `json:"edited_business_message,omitempty"` + // Optional. Messages were deleted from a connected business account + DeletedBusinessMessages *BusinessMessagesDeleted `json:"deleted_business_messages,omitempty"` + // Optional. New guest message. The bot can use the field Message.guest_query_id and the method answerGuestQuery to send a message in response. + GuestMessage *Message `json:"guest_message,omitempty"` + // Optional. A reaction to a message was changed by a user. The bot must be an administrator in the chat and must explicitly specify "message_reaction" in the list of allowed_updates to receive these updates. The update isn't received for reactions set by bots. + MessageReaction *MessageReactionUpdated `json:"message_reaction,omitempty"` + // Optional. Reactions to a message with anonymous reactions were changed. The bot must be an administrator in the chat and must explicitly specify "message_reaction_count" in the list of allowed_updates to receive these updates. The updates are grouped and can be sent with delay up to a few minutes. + MessageReactionCount *MessageReactionCountUpdated `json:"message_reaction_count,omitempty"` + // Optional. New incoming inline query + InlineQuery *InlineQuery `json:"inline_query,omitempty"` + // Optional. The result of an inline query that was chosen by a user and sent to their chat partner. Please see our documentation on the feedback collecting for details on how to enable these updates for your bot. + ChosenInlineResult *ChosenInlineResult `json:"chosen_inline_result,omitempty"` + // Optional. New incoming callback query + CallbackQuery *CallbackQuery `json:"callback_query,omitempty"` + // Optional. New incoming shipping query. Only for invoices with flexible price + ShippingQuery *ShippingQuery `json:"shipping_query,omitempty"` + // Optional. New incoming pre-checkout query. Contains full information about checkout + PreCheckoutQuery *PreCheckoutQuery `json:"pre_checkout_query,omitempty"` + // Optional. A user purchased paid media with a non-empty payload sent by the bot in a non-channel chat + PurchasedPaidMedia *PaidMediaPurchased `json:"purchased_paid_media,omitempty"` + // Optional. New poll state. Bots receive only updates about manually stopped polls and polls, which are sent by the bot + Poll *Poll `json:"poll,omitempty"` + // Optional. A user changed their answer in a non-anonymous poll. Bots receive new votes only in polls that were sent by the bot itself. + PollAnswer *PollAnswer `json:"poll_answer,omitempty"` + // Optional. The bot's chat member status was updated in a chat. For private chats, this update is received only when the bot is blocked or unblocked by the user. + MyChatMember *ChatMemberUpdated `json:"my_chat_member,omitempty"` + // Optional. A chat member's status was updated in a chat. The bot must be an administrator in the chat and must explicitly specify "chat_member" in the list of allowed_updates to receive these updates. + ChatMember *ChatMemberUpdated `json:"chat_member,omitempty"` + // Optional. A request to join the chat has been sent. The bot must have the can_invite_users administrator right in the chat to receive these updates. + ChatJoinRequest *ChatJoinRequest `json:"chat_join_request,omitempty"` + // Optional. A chat boost was added or changed. The bot must be an administrator in the chat to receive these updates. + ChatBoost *ChatBoostUpdated `json:"chat_boost,omitempty"` + // Optional. A boost was removed from a chat. The bot must be an administrator in the chat to receive these updates. + RemovedChatBoost *ChatBoostRemoved `json:"removed_chat_boost,omitempty"` + // Optional. A new bot was created to be managed by the bot, or token or owner of a managed bot was changed + ManagedBot *ManagedBotUpdated `json:"managed_bot,omitempty"` +} + +// Describes the current status of a webhook. +type WebhookInfo struct { + // Webhook URL, may be empty if webhook is not set up + URL string `json:"url"` + // True, if a custom certificate was provided for webhook certificate checks + HasCustomCertificate bool `json:"has_custom_certificate"` + // Number of updates awaiting delivery + PendingUpdateCount int64 `json:"pending_update_count"` + // Optional. Currently used webhook IP address + IPAddress string `json:"ip_address,omitempty"` + // Optional. Unix time for the most recent error that happened when trying to deliver an update via webhook + LastErrorDate *int64 `json:"last_error_date,omitempty"` + // Optional. Error message in human-readable format for the most recent error that happened when trying to deliver an update via webhook + LastErrorMessage string `json:"last_error_message,omitempty"` + // Optional. Unix time of the most recent error that happened when trying to synchronize available updates with Telegram datacenters + LastSynchronizationErrorDate *int64 `json:"last_synchronization_error_date,omitempty"` + // Optional. The maximum allowed number of simultaneous HTTPS connections to the webhook for update delivery + MaxConnections *int64 `json:"max_connections,omitempty"` + // Optional. A list of update types the bot is subscribed to. Defaults to all update types except chat_member + AllowedUpdates []string `json:"allowed_updates,omitempty"` +} + +// This object represents a Telegram user or bot. +type User struct { + // Unique identifier for this user or bot. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a 64-bit integer or double-precision float type are safe for storing this identifier. + ID int64 `json:"id"` + // True, if this user is a bot + IsBot bool `json:"is_bot"` + // User's or bot's first name + FirstName string `json:"first_name"` + // Optional. User's or bot's last name + LastName string `json:"last_name,omitempty"` + // Optional. User's or bot's username + Username string `json:"username,omitempty"` + // Optional. IETF language tag of the user's language + LanguageCode string `json:"language_code,omitempty"` + // Optional. True, if this user is a Telegram Premium user + IsPremium *bool `json:"is_premium,omitempty"` + // Optional. True, if this user added the bot to the attachment menu + AddedToAttachmentMenu *bool `json:"added_to_attachment_menu,omitempty"` + // Optional. True, if the bot can be invited to groups. Returned only in getMe. + CanJoinGroups *bool `json:"can_join_groups,omitempty"` + // Optional. True, if privacy mode is disabled for the bot. Returned only in getMe. + CanReadAllGroupMessages *bool `json:"can_read_all_group_messages,omitempty"` + // Optional. True, if the bot supports guest queries from chats it is not a member of. Returned only in getMe. + SupportsGuestQueries *bool `json:"supports_guest_queries,omitempty"` + // Optional. True, if the bot supports inline queries. Returned only in getMe. + SupportsInlineQueries *bool `json:"supports_inline_queries,omitempty"` + // Optional. True, if the bot can be connected to a user account to manage it. Returned only in getMe. + CanConnectToBusiness *bool `json:"can_connect_to_business,omitempty"` + // Optional. True, if the bot has a main Web App. Returned only in getMe. + HasMainWebApp *bool `json:"has_main_web_app,omitempty"` + // Optional. True, if the bot has forum topic mode enabled in private chats. Returned only in getMe. + HasTopicsEnabled *bool `json:"has_topics_enabled,omitempty"` + // Optional. True, if the bot allows users to create and delete topics in private chats. Returned only in getMe. + AllowsUsersToCreateTopics *bool `json:"allows_users_to_create_topics,omitempty"` + // Optional. True, if other bots can be created to be controlled by the bot. Returned only in getMe. + CanManageBots *bool `json:"can_manage_bots,omitempty"` +} + +// This object represents a chat. +type Chat struct { + // Unique identifier for this chat. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this identifier. + ID int64 `json:"id"` + // Type of the chat, can be either “private”, “group”, “supergroup” or “channel” + Type string `json:"type"` + // Optional. Title, for supergroups, channels and group chats + Title string `json:"title,omitempty"` + // Optional. Username, for private chats, supergroups and channels if available + Username string `json:"username,omitempty"` + // Optional. First name of the other party in a private chat + FirstName string `json:"first_name,omitempty"` + // Optional. Last name of the other party in a private chat + LastName string `json:"last_name,omitempty"` + // Optional. True, if the supergroup chat is a forum (has topics enabled) + IsForum *bool `json:"is_forum,omitempty"` + // Optional. True, if the chat is the direct messages chat of a channel + IsDirectMessages *bool `json:"is_direct_messages,omitempty"` +} + +// This object contains full information about a chat. +type ChatFullInfo struct { + // Unique identifier for this chat. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this identifier. + ID int64 `json:"id"` + // Type of the chat, can be either “private”, “group”, “supergroup” or “channel” + Type string `json:"type"` + // Optional. Title, for supergroups, channels and group chats + Title string `json:"title,omitempty"` + // Optional. Username, for private chats, supergroups and channels if available + Username string `json:"username,omitempty"` + // Optional. First name of the other party in a private chat + FirstName string `json:"first_name,omitempty"` + // Optional. Last name of the other party in a private chat + LastName string `json:"last_name,omitempty"` + // Optional. True, if the supergroup chat is a forum (has topics enabled) + IsForum *bool `json:"is_forum,omitempty"` + // Optional. True, if the chat is the direct messages chat of a channel + IsDirectMessages *bool `json:"is_direct_messages,omitempty"` + // Identifier of the accent color for the chat name and backgrounds of the chat photo, reply header, and link preview. See accent colors for more details. + AccentColorID int64 `json:"accent_color_id"` + // The maximum number of reactions that can be set on a message in the chat + MaxReactionCount int64 `json:"max_reaction_count"` + // Optional. Chat photo + Photo *ChatPhoto `json:"photo,omitempty"` + // Optional. If non-empty, the list of all active chat usernames; for private chats, supergroups and channels + ActiveUsernames []string `json:"active_usernames,omitempty"` + // Optional. For private chats, the date of birth of the user + Birthdate *Birthdate `json:"birthdate,omitempty"` + // Optional. For private chats with business accounts, the intro of the business + BusinessIntro *BusinessIntro `json:"business_intro,omitempty"` + // Optional. For private chats with business accounts, the location of the business + BusinessLocation *BusinessLocation `json:"business_location,omitempty"` + // Optional. For private chats with business accounts, the opening hours of the business + BusinessOpeningHours *BusinessOpeningHours `json:"business_opening_hours,omitempty"` + // Optional. For private chats, the personal channel of the user + PersonalChat *Chat `json:"personal_chat,omitempty"` + // Optional. Information about the corresponding channel chat; for direct messages chats only + ParentChat *Chat `json:"parent_chat,omitempty"` + // Optional. List of available reactions allowed in the chat. If omitted, then all emoji reactions are allowed. + AvailableReactions []ReactionType `json:"available_reactions,omitempty"` + // Optional. Custom emoji identifier of the emoji chosen by the chat for the reply header and link preview background + BackgroundCustomEmojiID string `json:"background_custom_emoji_id,omitempty"` + // Optional. Identifier of the accent color for the chat's profile background. See profile accent colors for more details. + ProfileAccentColorID *int64 `json:"profile_accent_color_id,omitempty"` + // Optional. Custom emoji identifier of the emoji chosen by the chat for its profile background + ProfileBackgroundCustomEmojiID string `json:"profile_background_custom_emoji_id,omitempty"` + // Optional. Custom emoji identifier of the emoji status of the chat or the other party in a private chat + EmojiStatusCustomEmojiID string `json:"emoji_status_custom_emoji_id,omitempty"` + // Optional. Expiration date of the emoji status of the chat or the other party in a private chat, in Unix time, if any + EmojiStatusExpirationDate *int64 `json:"emoji_status_expiration_date,omitempty"` + // Optional. Bio of the other party in a private chat + Bio string `json:"bio,omitempty"` + // Optional. True, if privacy settings of the other party in the private chat allows to use tg://user?id= links only in chats with the user + HasPrivateForwards *bool `json:"has_private_forwards,omitempty"` + // Optional. True, if the privacy settings of the other party restrict sending voice and video note messages in the private chat + HasRestrictedVoiceAndVideoMessages *bool `json:"has_restricted_voice_and_video_messages,omitempty"` + // Optional. True, if users need to join the supergroup before they can send messages + JoinToSendMessages *bool `json:"join_to_send_messages,omitempty"` + // Optional. True, if all users directly joining the supergroup without using an invite link need to be approved by supergroup administrators + JoinByRequest *bool `json:"join_by_request,omitempty"` + // Optional. Description, for groups, supergroups and channel chats + Description string `json:"description,omitempty"` + // Optional. Primary invite link, for groups, supergroups and channel chats + InviteLink string `json:"invite_link,omitempty"` + // Optional. The most recent pinned message (by sending date) + PinnedMessage *Message `json:"pinned_message,omitempty"` + // Optional. Default chat member permissions, for groups and supergroups + Permissions *ChatPermissions `json:"permissions,omitempty"` + // Information about types of gifts that are accepted by the chat or by the corresponding user for private chats + AcceptedGiftTypes AcceptedGiftTypes `json:"accepted_gift_types"` + // Optional. True, if paid media messages can be sent or forwarded to the channel chat. The field is available only for channel chats. + CanSendPaidMedia *bool `json:"can_send_paid_media,omitempty"` + // Optional. For supergroups, the minimum allowed delay between consecutive messages sent by each unprivileged user; in seconds + SlowModeDelay *int64 `json:"slow_mode_delay,omitempty"` + // Optional. For supergroups, the minimum number of boosts that a non-administrator user needs to add in order to ignore slow mode and chat permissions + UnrestrictBoostCount *int64 `json:"unrestrict_boost_count,omitempty"` + // Optional. The time after which all messages sent to the chat will be automatically deleted; in seconds + MessageAutoDeleteTime *int64 `json:"message_auto_delete_time,omitempty"` + // Optional. True, if aggressive anti-spam checks are enabled in the supergroup. The field is only available to chat administrators. + HasAggressiveAntiSpamEnabled *bool `json:"has_aggressive_anti_spam_enabled,omitempty"` + // Optional. True, if non-administrators can only get the list of bots and administrators in the chat + HasHiddenMembers *bool `json:"has_hidden_members,omitempty"` + // Optional. True, if messages from the chat can't be forwarded to other chats + HasProtectedContent *bool `json:"has_protected_content,omitempty"` + // Optional. True, if new chat members will have access to old messages; available only to chat administrators + HasVisibleHistory *bool `json:"has_visible_history,omitempty"` + // Optional. For supergroups, name of the group sticker set + StickerSetName string `json:"sticker_set_name,omitempty"` + // Optional. True, if the bot can change the group sticker set + CanSetStickerSet *bool `json:"can_set_sticker_set,omitempty"` + // Optional. For supergroups, the name of the group's custom emoji sticker set. Custom emoji from this set can be used by all users and bots in the group. + CustomEmojiStickerSetName string `json:"custom_emoji_sticker_set_name,omitempty"` + // Optional. Unique identifier for the linked chat, i.e. the discussion group identifier for a channel and vice versa; for supergroups and channel chats. This identifier may be greater than 32 bits and some programming languages may have difficulty/silent defects in interpreting it. But it is smaller than 52 bits, so a signed 64 bit integer or double-precision float type are safe for storing this identifier. + LinkedChatID *int64 `json:"linked_chat_id,omitempty"` + // Optional. For supergroups, the location to which the supergroup is connected + Location *ChatLocation `json:"location,omitempty"` + // Optional. For private chats, the rating of the user if any + Rating *UserRating `json:"rating,omitempty"` + // Optional. For private chats, the first audio added to the profile of the user + FirstProfileAudio *Audio `json:"first_profile_audio,omitempty"` + // Optional. The color scheme based on a unique gift that must be used for the chat's name, message replies and link previews + UniqueGiftColors *UniqueGiftColors `json:"unique_gift_colors,omitempty"` + // Optional. The number of Telegram Stars a general user have to pay to send a message to the chat + PaidMessageStarCount *int64 `json:"paid_message_star_count,omitempty"` +} + +// UnmarshalJSON decodes ChatFullInfo by dispatching union-typed fields +// (AvailableReactions) through their concrete UnmarshalXxx helpers. +func (m *ChatFullInfo) UnmarshalJSON(data []byte) error { + type Alias ChatFullInfo + aux := &struct { + AvailableReactions json.RawMessage `json:"available_reactions,omitempty"` + *Alias + }{Alias: (*Alias)(m)} + if err := json.Unmarshal(data, aux); err != nil { + return err + } + + if len(aux.AvailableReactions) > 0 && string(aux.AvailableReactions) != "null" { + var raws []json.RawMessage + if err := json.Unmarshal(aux.AvailableReactions, &raws); err != nil { + return fmt.Errorf("decoding available_reactions: %w", err) + } + decoded := make([]ReactionType, 0, len(raws)) + for i, r := range raws { + v, err := UnmarshalReactionType(r) + if err != nil { + return fmt.Errorf("decoding available_reactions[%d]: %w", i, err) + } + decoded = append(decoded, v) + } + m.AvailableReactions = decoded + + } + + return nil +} + +// This object represents a message. +type Message struct { + // Unique message identifier inside this chat. In specific instances (e.g., message containing a video sent to a big chat), the server might automatically schedule a message instead of sending it immediately. In such cases, this field will be 0 and the relevant message will be unusable until it is actually sent + MessageID int64 `json:"message_id"` + // Optional. Unique identifier of a message thread or forum topic to which the message belongs; for supergroups and private chats only + MessageThreadID *int64 `json:"message_thread_id,omitempty"` + // Optional. Information about the direct messages chat topic that contains the message + DirectMessagesTopic *DirectMessagesTopic `json:"direct_messages_topic,omitempty"` + // Optional. Sender of the message; may be empty for messages sent to channels. For backward compatibility, if the message was sent on behalf of a chat, the field contains a fake sender user in non-channel chats + From *User `json:"from,omitempty"` + // Optional. Sender of the message when sent on behalf of a chat. For example, the supergroup itself for messages sent by its anonymous administrators or a linked channel for messages automatically forwarded to the channel's discussion group. For backward compatibility, if the message was sent on behalf of a chat, the field from contains a fake sender user in non-channel chats. + SenderChat *Chat `json:"sender_chat,omitempty"` + // Optional. If the sender of the message boosted the chat, the number of boosts added by the user + SenderBoostCount *int64 `json:"sender_boost_count,omitempty"` + // Optional. The bot that actually sent the message on behalf of the business account. Available only for outgoing messages sent on behalf of the connected business account. + SenderBusinessBot *User `json:"sender_business_bot,omitempty"` + // Optional. Tag or custom title of the sender of the message; for supergroups only + SenderTag string `json:"sender_tag,omitempty"` + // Date the message was sent in Unix time. It is always a positive number, representing a valid date. + Date int64 `json:"date"` + // Optional. The unique identifier for the guest query. Use this identifier with the method answerGuestQuery to send a response message. If non-empty, the message belongs to the chat where the guest bot was summoned, which may not coincide with other existing bot chats sharing the same identifier. + GuestQueryID string `json:"guest_query_id,omitempty"` + // Optional. Unique identifier of the business connection from which the message was received. If non-empty, the message belongs to a chat of the corresponding business account that is independent from any potential bot chat which might share the same identifier. + BusinessConnectionID string `json:"business_connection_id,omitempty"` + // Chat the message belongs to + Chat Chat `json:"chat"` + // Optional. Information about the original message for forwarded messages + ForwardOrigin MessageOrigin `json:"forward_origin,omitempty"` + // Optional. True, if the message is sent to a topic in a forum supergroup or a private chat with the bot + IsTopicMessage *bool `json:"is_topic_message,omitempty"` + // Optional. True, if the message is a channel post that was automatically forwarded to the connected discussion group + IsAutomaticForward *bool `json:"is_automatic_forward,omitempty"` + // Optional. For replies in the same chat and message thread, the original message. Note that the Message object in this field will not contain further reply_to_message fields even if it itself is a reply. + ReplyToMessage *Message `json:"reply_to_message,omitempty"` + // Optional. Information about the message that is being replied to, which may come from another chat or forum topic + ExternalReply *ExternalReplyInfo `json:"external_reply,omitempty"` + // Optional. For replies that quote part of the original message, the quoted part of the message + Quote *TextQuote `json:"quote,omitempty"` + // Optional. For replies to a story, the original story + ReplyToStory *Story `json:"reply_to_story,omitempty"` + // Optional. Identifier of the specific checklist task that is being replied to + ReplyToChecklistTaskID *int64 `json:"reply_to_checklist_task_id,omitempty"` + // Optional. Persistent identifier of the specific poll option that is being replied to + ReplyToPollOptionID string `json:"reply_to_poll_option_id,omitempty"` + // Optional. Bot through which the message was sent + ViaBot *User `json:"via_bot,omitempty"` + // Optional. For a message sent by a guest bot, this is the user whose original message triggered the bot's response + GuestBotCallerUser *User `json:"guest_bot_caller_user,omitempty"` + // Optional. For a message sent by a guest bot, this is the chat whose original message triggered the bot's response + GuestBotCallerChat *Chat `json:"guest_bot_caller_chat,omitempty"` + // Optional. Date the message was last edited in Unix time + EditDate *int64 `json:"edit_date,omitempty"` + // Optional. True, if the message can't be forwarded + HasProtectedContent *bool `json:"has_protected_content,omitempty"` + // Optional. True, if the message was sent by an implicit action, for example, as an away or a greeting business message, or as a scheduled message + IsFromOffline *bool `json:"is_from_offline,omitempty"` + // Optional. True, if the message is a paid post. Note that such posts must not be deleted for 24 hours to receive the payment and can't be edited. + IsPaidPost *bool `json:"is_paid_post,omitempty"` + // Optional. The unique identifier inside this chat of a media message group this message belongs to + MediaGroupID string `json:"media_group_id,omitempty"` + // Optional. Signature of the post author for messages in channels, or the custom title of an anonymous group administrator + AuthorSignature string `json:"author_signature,omitempty"` + // Optional. The number of Telegram Stars that were paid by the sender of the message to send it + PaidStarCount *int64 `json:"paid_star_count,omitempty"` + // Optional. For text messages, the actual UTF-8 text of the message + Text string `json:"text,omitempty"` + // Optional. For text messages, special entities like usernames, URLs, bot commands, etc. that appear in the text + Entities []MessageEntity `json:"entities,omitempty"` + // Optional. Options used for link preview generation for the message, if it is a text message and link preview options were changed + LinkPreviewOptions *LinkPreviewOptions `json:"link_preview_options,omitempty"` + // Optional. Information about suggested post parameters if the message is a suggested post in a channel direct messages chat. If the message is an approved or declined suggested post, then it can't be edited. + SuggestedPostInfo *SuggestedPostInfo `json:"suggested_post_info,omitempty"` + // Optional. Unique identifier of the message effect added to the message + EffectID string `json:"effect_id,omitempty"` + // Optional. Message is an animation, information about the animation. For backward compatibility, when this field is set, the document field will also be set + Animation *Animation `json:"animation,omitempty"` + // Optional. Message is an audio file, information about the file + Audio *Audio `json:"audio,omitempty"` + // Optional. Message is a general file, information about the file + Document *Document `json:"document,omitempty"` + // Optional. Message is a live photo, information about the live photo. For backward compatibility, when this field is set, the photo field will also be set + LivePhoto *LivePhoto `json:"live_photo,omitempty"` + // Optional. Message contains paid media; information about the paid media + PaidMedia *PaidMediaInfo `json:"paid_media,omitempty"` + // Optional. Message is a photo, available sizes of the photo + Photo []PhotoSize `json:"photo,omitempty"` + // Optional. Message is a sticker, information about the sticker + Sticker *Sticker `json:"sticker,omitempty"` + // Optional. Message is a forwarded story + Story *Story `json:"story,omitempty"` + // Optional. Message is a video, information about the video + Video *Video `json:"video,omitempty"` + // Optional. Message is a video note, information about the video message + VideoNote *VideoNote `json:"video_note,omitempty"` + // Optional. Message is a voice message, information about the file + Voice *Voice `json:"voice,omitempty"` + // Optional. Caption for the animation, audio, document, paid media, photo, video or voice + Caption string `json:"caption,omitempty"` + // Optional. For messages with a caption, special entities like usernames, URLs, bot commands, etc. that appear in the caption + CaptionEntities []MessageEntity `json:"caption_entities,omitempty"` + // Optional. True, if the caption must be shown above the message media + ShowCaptionAboveMedia *bool `json:"show_caption_above_media,omitempty"` + // Optional. True, if the message media is covered by a spoiler animation + HasMediaSpoiler *bool `json:"has_media_spoiler,omitempty"` + // Optional. Message is a checklist + Checklist *Checklist `json:"checklist,omitempty"` + // Optional. Message is a shared contact, information about the contact + Contact *Contact `json:"contact,omitempty"` + // Optional. Message is a dice with random value + Dice *Dice `json:"dice,omitempty"` + // Optional. Message is a game, information about the game. More about games » + Game *Game `json:"game,omitempty"` + // Optional. Message is a native poll, information about the poll + Poll *Poll `json:"poll,omitempty"` + // Optional. Message is a venue, information about the venue. For backward compatibility, when this field is set, the location field will also be set + Venue *Venue `json:"venue,omitempty"` + // Optional. Message is a shared location, information about the location + Location *Location `json:"location,omitempty"` + // Optional. New members that were added to the group or supergroup and information about them (the bot itself may be one of these members) + NewChatMembers []User `json:"new_chat_members,omitempty"` + // Optional. A member was removed from the group, information about them (this member may be the bot itself) + LeftChatMember *User `json:"left_chat_member,omitempty"` + // Optional. Service message: chat owner has left + ChatOwnerLeft *ChatOwnerLeft `json:"chat_owner_left,omitempty"` + // Optional. Service message: chat owner has changed + ChatOwnerChanged *ChatOwnerChanged `json:"chat_owner_changed,omitempty"` + // Optional. A chat title was changed to this value + NewChatTitle string `json:"new_chat_title,omitempty"` + // Optional. A chat photo was change to this value + NewChatPhoto []PhotoSize `json:"new_chat_photo,omitempty"` + // Optional. Service message: the chat photo was deleted + DeleteChatPhoto *bool `json:"delete_chat_photo,omitempty"` + // Optional. Service message: the group has been created + GroupChatCreated *bool `json:"group_chat_created,omitempty"` + // Optional. Service message: the supergroup has been created. This field can't be received in a message coming through updates, because bot can't be a member of a supergroup when it is created. It can only be found in reply_to_message if someone replies to a very first message in a directly created supergroup. + SupergroupChatCreated *bool `json:"supergroup_chat_created,omitempty"` + // Optional. Service message: the channel has been created. This field can't be received in a message coming through updates, because bot can't be a member of a channel when it is created. It can only be found in reply_to_message if someone replies to a very first message in a channel. + ChannelChatCreated *bool `json:"channel_chat_created,omitempty"` + // Optional. Service message: auto-delete timer settings changed in the chat + MessageAutoDeleteTimerChanged *MessageAutoDeleteTimerChanged `json:"message_auto_delete_timer_changed,omitempty"` + // Optional. The group has been migrated to a supergroup with the specified identifier. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this identifier. + MigrateToChatID *int64 `json:"migrate_to_chat_id,omitempty"` + // Optional. The supergroup has been migrated from a group with the specified identifier. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this identifier. + MigrateFromChatID *int64 `json:"migrate_from_chat_id,omitempty"` + // Optional. Specified message was pinned. Note that the Message object in this field will not contain further reply_to_message fields even if it itself is a reply. + PinnedMessage MaybeInaccessibleMessage `json:"pinned_message,omitempty"` + // Optional. Message is an invoice for a payment, information about the invoice. More about payments » + Invoice *Invoice `json:"invoice,omitempty"` + // Optional. Message is a service message about a successful payment, information about the payment. More about payments » + SuccessfulPayment *SuccessfulPayment `json:"successful_payment,omitempty"` + // Optional. Message is a service message about a refunded payment, information about the payment. More about payments » + RefundedPayment *RefundedPayment `json:"refunded_payment,omitempty"` + // Optional. Service message: users were shared with the bot + UsersShared *UsersShared `json:"users_shared,omitempty"` + // Optional. Service message: a chat was shared with the bot + ChatShared *ChatShared `json:"chat_shared,omitempty"` + // Optional. Service message: a regular gift was sent or received + Gift *GiftInfo `json:"gift,omitempty"` + // Optional. Service message: a unique gift was sent or received + UniqueGift *UniqueGiftInfo `json:"unique_gift,omitempty"` + // Optional. Service message: upgrade of a gift was purchased after the gift was sent + GiftUpgradeSent *GiftInfo `json:"gift_upgrade_sent,omitempty"` + // Optional. The domain name of the website on which the user has logged in. More about Telegram Login » + ConnectedWebsite string `json:"connected_website,omitempty"` + // Optional. Service message: the user allowed the bot to write messages after adding it to the attachment or side menu, launching a Web App from a link, or accepting an explicit request from a Web App sent by the method requestWriteAccess + WriteAccessAllowed *WriteAccessAllowed `json:"write_access_allowed,omitempty"` + // Optional. Telegram Passport data + PassportData *PassportData `json:"passport_data,omitempty"` + // Optional. Service message. A user in the chat triggered another user's proximity alert while sharing Live Location. + ProximityAlertTriggered *ProximityAlertTriggered `json:"proximity_alert_triggered,omitempty"` + // Optional. Service message: user boosted the chat + BoostAdded *ChatBoostAdded `json:"boost_added,omitempty"` + // Optional. Service message: chat background set + ChatBackgroundSet *ChatBackground `json:"chat_background_set,omitempty"` + // Optional. Service message: some tasks in a checklist were marked as done or not done + ChecklistTasksDone *ChecklistTasksDone `json:"checklist_tasks_done,omitempty"` + // Optional. Service message: tasks were added to a checklist + ChecklistTasksAdded *ChecklistTasksAdded `json:"checklist_tasks_added,omitempty"` + // Optional. Service message: the price for paid messages in the corresponding direct messages chat of a channel has changed + DirectMessagePriceChanged *DirectMessagePriceChanged `json:"direct_message_price_changed,omitempty"` + // Optional. Service message: forum topic created + ForumTopicCreated *ForumTopicCreated `json:"forum_topic_created,omitempty"` + // Optional. Service message: forum topic edited + ForumTopicEdited *ForumTopicEdited `json:"forum_topic_edited,omitempty"` + // Optional. Service message: forum topic closed + ForumTopicClosed *ForumTopicClosed `json:"forum_topic_closed,omitempty"` + // Optional. Service message: forum topic reopened + ForumTopicReopened *ForumTopicReopened `json:"forum_topic_reopened,omitempty"` + // Optional. Service message: the 'General' forum topic hidden + GeneralForumTopicHidden *GeneralForumTopicHidden `json:"general_forum_topic_hidden,omitempty"` + // Optional. Service message: the 'General' forum topic unhidden + GeneralForumTopicUnhidden *GeneralForumTopicUnhidden `json:"general_forum_topic_unhidden,omitempty"` + // Optional. Service message: a scheduled giveaway was created + GiveawayCreated *GiveawayCreated `json:"giveaway_created,omitempty"` + // Optional. The message is a scheduled giveaway message + Giveaway *Giveaway `json:"giveaway,omitempty"` + // Optional. A giveaway with public winners was completed + GiveawayWinners *GiveawayWinners `json:"giveaway_winners,omitempty"` + // Optional. Service message: a giveaway without public winners was completed + GiveawayCompleted *GiveawayCompleted `json:"giveaway_completed,omitempty"` + // Optional. Service message: user created a bot that will be managed by the current bot + ManagedBotCreated *ManagedBotCreated `json:"managed_bot_created,omitempty"` + // Optional. Service message: the price for paid messages has changed in the chat + PaidMessagePriceChanged *PaidMessagePriceChanged `json:"paid_message_price_changed,omitempty"` + // Optional. Service message: answer option was added to a poll + PollOptionAdded *PollOptionAdded `json:"poll_option_added,omitempty"` + // Optional. Service message: answer option was deleted from a poll + PollOptionDeleted *PollOptionDeleted `json:"poll_option_deleted,omitempty"` + // Optional. Service message: a suggested post was approved + SuggestedPostApproved *SuggestedPostApproved `json:"suggested_post_approved,omitempty"` + // Optional. Service message: approval of a suggested post has failed + SuggestedPostApprovalFailed *SuggestedPostApprovalFailed `json:"suggested_post_approval_failed,omitempty"` + // Optional. Service message: a suggested post was declined + SuggestedPostDeclined *SuggestedPostDeclined `json:"suggested_post_declined,omitempty"` + // Optional. Service message: payment for a suggested post was received + SuggestedPostPaid *SuggestedPostPaid `json:"suggested_post_paid,omitempty"` + // Optional. Service message: payment for a suggested post was refunded + SuggestedPostRefunded *SuggestedPostRefunded `json:"suggested_post_refunded,omitempty"` + // Optional. Service message: video chat scheduled + VideoChatScheduled *VideoChatScheduled `json:"video_chat_scheduled,omitempty"` + // Optional. Service message: video chat started + VideoChatStarted *VideoChatStarted `json:"video_chat_started,omitempty"` + // Optional. Service message: video chat ended + VideoChatEnded *VideoChatEnded `json:"video_chat_ended,omitempty"` + // Optional. Service message: new participants invited to a video chat + VideoChatParticipantsInvited *VideoChatParticipantsInvited `json:"video_chat_participants_invited,omitempty"` + // Optional. Service message: data sent by a Web App + WebAppData *WebAppData `json:"web_app_data,omitempty"` + // Optional. Inline keyboard attached to the message. login_url buttons are represented as ordinary url buttons. + ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"` +} + +// UnmarshalJSON decodes Message by dispatching union-typed fields +// (ForwardOrigin, PinnedMessage) through their concrete UnmarshalXxx helpers. +func (m *Message) UnmarshalJSON(data []byte) error { + type Alias Message + aux := &struct { + ForwardOrigin json.RawMessage `json:"forward_origin,omitempty"` + PinnedMessage json.RawMessage `json:"pinned_message,omitempty"` + *Alias + }{Alias: (*Alias)(m)} + if err := json.Unmarshal(data, aux); err != nil { + return err + } + + if len(aux.ForwardOrigin) > 0 && string(aux.ForwardOrigin) != "null" { + v, err := UnmarshalMessageOrigin(aux.ForwardOrigin) + if err != nil { + return fmt.Errorf("decoding forward_origin: %w", err) + } + m.ForwardOrigin = v + + } + + if len(aux.PinnedMessage) > 0 && string(aux.PinnedMessage) != "null" { + v, err := UnmarshalMaybeInaccessibleMessage(aux.PinnedMessage) + if err != nil { + return fmt.Errorf("decoding pinned_message: %w", err) + } + m.PinnedMessage = v + + } + + return nil +} + +// This object represents a unique message identifier. +type MessageId struct { + // Unique message identifier. In specific instances (e.g., message containing a video sent to a big chat), the server might automatically schedule a message instead of sending it immediately. In such cases, this field will be 0 and the relevant message will be unusable until it is actually sent + MessageID int64 `json:"message_id"` +} + +// This object describes a message that was deleted or is otherwise inaccessible to the bot. +type InaccessibleMessage struct { + // Chat the message belonged to + Chat Chat `json:"chat"` + // Unique message identifier inside the chat + MessageID int64 `json:"message_id"` + // Always 0. The field can be used to differentiate regular and inaccessible messages. + Date int64 `json:"date"` +} + +// MaybeInaccessibleMessage is a union type. The following concrete variants implement +// it: +// - Message +// - InaccessibleMessage +// +// This object describes a message that can be inaccessible to the bot. It can be one of +type MaybeInaccessibleMessage interface{ isMaybeInaccessibleMessage() } + +// isMaybeInaccessibleMessage is the marker method that makes Message implement MaybeInaccessibleMessage. +func (*Message) isMaybeInaccessibleMessage() {} + +// isMaybeInaccessibleMessage is the marker method that makes InaccessibleMessage implement MaybeInaccessibleMessage. +func (*InaccessibleMessage) isMaybeInaccessibleMessage() {} + +// UnmarshalMaybeInaccessibleMessage decodes a JSON object into the correct +// MaybeInaccessibleMessage variant. Telegram uses the date field as a +// discriminator: date == 0 indicates InaccessibleMessage; any other value +// indicates a real Message. +func UnmarshalMaybeInaccessibleMessage(data []byte) (MaybeInaccessibleMessage, error) { + var probe struct { + Date int64 `json:"date"` + } + if err := json.Unmarshal(data, &probe); err != nil { + return nil, fmt.Errorf("MaybeInaccessibleMessage: %w", err) + } + if probe.Date == 0 { + v := &InaccessibleMessage{} + if err := json.Unmarshal(data, v); err != nil { + return nil, fmt.Errorf("InaccessibleMessage: %w", err) + } + return v, nil + } + v := &Message{} + if err := json.Unmarshal(data, v); err != nil { + return nil, fmt.Errorf("Message: %w", err) + } + return v, nil +} + +// This object represents one special entity in a text message. For example, hashtags, usernames, URLs, etc. +type MessageEntity struct { + // Type of the entity. Currently, can be “mention” (@username), “hashtag” (#hashtag or #hashtag@chatusername), “cashtag” ($USD or $USD@chatusername), “bot_command” (/start@jobs_bot), “url” (https://telegram.org), “email” (do-not-reply@telegram.org), “phone_number” (+1-212-555-0123), “bold” (bold text), “italic” (italic text), “underline” (underlined text), “strikethrough” (strikethrough text), “spoiler” (spoiler message), “blockquote” (block quotation), “expandable_blockquote” (collapsed-by-default block quotation), “code” (monowidth string), “pre” (monowidth block), “text_link” (for clickable text URLs), “text_mention” (for users without usernames), “custom_emoji” (for inline custom emoji stickers), or “date_time” (for formatted date and time) + Type string `json:"type"` + // Offset in UTF-16 code units to the start of the entity + Offset int64 `json:"offset"` + // Length of the entity in UTF-16 code units + Length int64 `json:"length"` + // Optional. For “text_link” only, URL that will be opened after user taps on the text + URL string `json:"url,omitempty"` + // Optional. For “text_mention” only, the mentioned user + User *User `json:"user,omitempty"` + // Optional. For “pre” only, the programming language of the entity text + Language string `json:"language,omitempty"` + // Optional. For “custom_emoji” only, unique identifier of the custom emoji. Use getCustomEmojiStickers to get full information about the sticker + CustomEmojiID string `json:"custom_emoji_id,omitempty"` + // Optional. For “date_time” only, the Unix time associated with the entity + UnixTime *int64 `json:"unix_time,omitempty"` + // Optional. For “date_time” only, the string that defines the formatting of the date and time. See date-time entity formatting for more details. + DateTimeFormat string `json:"date_time_format,omitempty"` +} + +// This object contains information about the quoted part of a message that is replied to by the given message. +type TextQuote struct { + // Text of the quoted part of a message that is replied to by the given message + Text string `json:"text"` + // Optional. Special entities that appear in the quote. Currently, only bold, italic, underline, strikethrough, spoiler, custom_emoji, and date_time entities are kept in quotes. + Entities []MessageEntity `json:"entities,omitempty"` + // Approximate quote position in the original message in UTF-16 code units as specified by the sender + Position int64 `json:"position"` + // Optional. True, if the quote was chosen manually by the message sender. Otherwise, the quote was added automatically by the server. + IsManual *bool `json:"is_manual,omitempty"` +} + +// This object contains information about a message that is being replied to, which may come from another chat or forum topic. +type ExternalReplyInfo struct { + // Origin of the message replied to by the given message + Origin MessageOrigin `json:"origin"` + // Optional. Chat the original message belongs to. Available only if the chat is a supergroup or a channel. + Chat *Chat `json:"chat,omitempty"` + // Optional. Unique message identifier inside the original chat. Available only if the original chat is a supergroup or a channel. + MessageID *int64 `json:"message_id,omitempty"` + // Optional. Options used for link preview generation for the original message, if it is a text message + LinkPreviewOptions *LinkPreviewOptions `json:"link_preview_options,omitempty"` + // Optional. Message is an animation, information about the animation + Animation *Animation `json:"animation,omitempty"` + // Optional. Message is an audio file, information about the file + Audio *Audio `json:"audio,omitempty"` + // Optional. Message is a general file, information about the file + Document *Document `json:"document,omitempty"` + // Optional. Message is a live photo, information about the live photo + LivePhoto *LivePhoto `json:"live_photo,omitempty"` + // Optional. Message contains paid media; information about the paid media + PaidMedia *PaidMediaInfo `json:"paid_media,omitempty"` + // Optional. Message is a photo, available sizes of the photo + Photo []PhotoSize `json:"photo,omitempty"` + // Optional. Message is a sticker, information about the sticker + Sticker *Sticker `json:"sticker,omitempty"` + // Optional. Message is a forwarded story + Story *Story `json:"story,omitempty"` + // Optional. Message is a video, information about the video + Video *Video `json:"video,omitempty"` + // Optional. Message is a video note, information about the video message + VideoNote *VideoNote `json:"video_note,omitempty"` + // Optional. Message is a voice message, information about the file + Voice *Voice `json:"voice,omitempty"` + // Optional. True, if the message media is covered by a spoiler animation + HasMediaSpoiler *bool `json:"has_media_spoiler,omitempty"` + // Optional. Message is a checklist + Checklist *Checklist `json:"checklist,omitempty"` + // Optional. Message is a shared contact, information about the contact + Contact *Contact `json:"contact,omitempty"` + // Optional. Message is a dice with random value + Dice *Dice `json:"dice,omitempty"` + // Optional. Message is a game, information about the game. More about games » + Game *Game `json:"game,omitempty"` + // Optional. Message is a scheduled giveaway, information about the giveaway + Giveaway *Giveaway `json:"giveaway,omitempty"` + // Optional. A giveaway with public winners was completed + GiveawayWinners *GiveawayWinners `json:"giveaway_winners,omitempty"` + // Optional. Message is an invoice for a payment, information about the invoice. More about payments » + Invoice *Invoice `json:"invoice,omitempty"` + // Optional. Message is a shared location, information about the location + Location *Location `json:"location,omitempty"` + // Optional. Message is a native poll, information about the poll + Poll *Poll `json:"poll,omitempty"` + // Optional. Message is a venue, information about the venue + Venue *Venue `json:"venue,omitempty"` +} + +// UnmarshalJSON decodes ExternalReplyInfo by dispatching union-typed fields +// (Origin) through their concrete UnmarshalXxx helpers. +func (m *ExternalReplyInfo) UnmarshalJSON(data []byte) error { + type Alias ExternalReplyInfo + aux := &struct { + Origin json.RawMessage `json:"origin,omitempty"` + *Alias + }{Alias: (*Alias)(m)} + if err := json.Unmarshal(data, aux); err != nil { + return err + } + + if len(aux.Origin) > 0 && string(aux.Origin) != "null" { + v, err := UnmarshalMessageOrigin(aux.Origin) + if err != nil { + return fmt.Errorf("decoding origin: %w", err) + } + m.Origin = v + + } + + return nil +} + +// Describes reply parameters for the message that is being sent. +type ReplyParameters struct { + // Identifier of the message that will be replied to in the current chat, or in the chat chat_id if it is specified + MessageID int64 `json:"message_id"` + // Optional. If the message to be replied to is from a different chat, unique identifier for the chat or username of the bot, supergroup or channel in the format @username. Not supported for messages sent on behalf of a business account and messages from channel direct messages chats. + ChatID *ChatID `json:"chat_id,omitempty"` + // Optional. Pass True if the message should be sent even if the specified message to be replied to is not found. Always False for replies in another chat or forum topic. Always True for messages sent on behalf of a business account. + AllowSendingWithoutReply *bool `json:"allow_sending_without_reply,omitempty"` + // Optional. Quoted part of the message to be replied to; 0-1024 characters after entities parsing. The quote must be an exact substring of the message to be replied to, including bold, italic, underline, strikethrough, spoiler, custom_emoji, and date_time entities. The message will fail to send if the quote isn't found in the original message. + Quote string `json:"quote,omitempty"` + // Optional. Mode for parsing entities in the quote. See formatting options for more details. + QuoteParseMode string `json:"quote_parse_mode,omitempty"` + // Optional. A JSON-serialized list of special entities that appear in the quote. It can be specified instead of quote_parse_mode. + QuoteEntities []MessageEntity `json:"quote_entities,omitempty"` + // Optional. Position of the quote in the original message in UTF-16 code units + QuotePosition *int64 `json:"quote_position,omitempty"` + // Optional. Identifier of the specific checklist task to be replied to + ChecklistTaskID *int64 `json:"checklist_task_id,omitempty"` + // Optional. Persistent identifier of the specific poll option to be replied to + PollOptionID string `json:"poll_option_id,omitempty"` +} + +// MessageOrigin is a union type. The following concrete variants implement +// it: +// - MessageOriginUser +// - MessageOriginHiddenUser +// - MessageOriginChat +// - MessageOriginChannel +// +// This object describes the origin of a message. It can be one of +type MessageOrigin interface{ isMessageOrigin() } + +// isMessageOrigin is the marker method that makes MessageOriginUser implement MessageOrigin. +func (*MessageOriginUser) isMessageOrigin() {} + +// isMessageOrigin is the marker method that makes MessageOriginHiddenUser implement MessageOrigin. +func (*MessageOriginHiddenUser) isMessageOrigin() {} + +// isMessageOrigin is the marker method that makes MessageOriginChat implement MessageOrigin. +func (*MessageOriginChat) isMessageOrigin() {} + +// isMessageOrigin is the marker method that makes MessageOriginChannel implement MessageOrigin. +func (*MessageOriginChannel) isMessageOrigin() {} + +// UnmarshalMessageOrigin decodes a MessageOrigin from JSON by inspecting the +// "type" field and dispatching to the correct concrete type. +func UnmarshalMessageOrigin(data []byte) (MessageOrigin, error) { + var probe struct { + V string `json:"type"` + } + if err := json.Unmarshal(data, &probe); err != nil { + return nil, err + } + var v MessageOrigin + switch probe.V { + case "channel": + v = &MessageOriginChannel{} + case "chat": + v = &MessageOriginChat{} + case "hidden_user": + v = &MessageOriginHiddenUser{} + case "user": + v = &MessageOriginUser{} + default: + return nil, fmt.Errorf("MessageOrigin: unknown type %q", probe.V) + } + if err := json.Unmarshal(data, v); err != nil { + return nil, err + } + return v, nil +} + +// The message was originally sent by a known user. +type MessageOriginUser struct { + // Type of the message origin, always “user” + Type string `json:"type"` + // Date the message was sent originally in Unix time + Date int64 `json:"date"` + // User that sent the message originally + SenderUser User `json:"sender_user"` +} + +// The message was originally sent by an unknown user. +type MessageOriginHiddenUser struct { + // Type of the message origin, always “hidden_user” + Type string `json:"type"` + // Date the message was sent originally in Unix time + Date int64 `json:"date"` + // Name of the user that sent the message originally + SenderUserName string `json:"sender_user_name"` +} + +// The message was originally sent on behalf of a chat to a group chat. +type MessageOriginChat struct { + // Type of the message origin, always “chat” + Type string `json:"type"` + // Date the message was sent originally in Unix time + Date int64 `json:"date"` + // Chat that sent the message originally + SenderChat Chat `json:"sender_chat"` + // Optional. For messages originally sent by an anonymous chat administrator, original message author signature + AuthorSignature string `json:"author_signature,omitempty"` +} + +// The message was originally sent to a channel chat. +type MessageOriginChannel struct { + // Type of the message origin, always “channel” + Type string `json:"type"` + // Date the message was sent originally in Unix time + Date int64 `json:"date"` + // Channel chat to which the message was originally sent + Chat Chat `json:"chat"` + // Unique message identifier inside the chat + MessageID int64 `json:"message_id"` + // Optional. Signature of the original post author + AuthorSignature string `json:"author_signature,omitempty"` +} + +// This object represents one size of a photo or a file / sticker thumbnail. +type PhotoSize struct { + // Identifier for this file, which can be used to download or reuse the file + FileID string `json:"file_id"` + // Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file. + FileUniqueID string `json:"file_unique_id"` + // Photo width + Width int64 `json:"width"` + // Photo height + Height int64 `json:"height"` + // Optional. File size in bytes + FileSize *int64 `json:"file_size,omitempty"` +} + +// This object represents an animation file (GIF or H.264/MPEG-4 AVC video without sound). +type Animation struct { + // Identifier for this file, which can be used to download or reuse the file + FileID string `json:"file_id"` + // Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file. + FileUniqueID string `json:"file_unique_id"` + // Video width as defined by the sender + Width int64 `json:"width"` + // Video height as defined by the sender + Height int64 `json:"height"` + // Duration of the video in seconds as defined by the sender + Duration int64 `json:"duration"` + // Optional. Animation thumbnail as defined by the sender + Thumbnail *PhotoSize `json:"thumbnail,omitempty"` + // Optional. Original animation filename as defined by the sender + FileName string `json:"file_name,omitempty"` + // Optional. MIME type of the file as defined by the sender + MimeType string `json:"mime_type,omitempty"` + // Optional. File size in bytes. It can be bigger than 2^31 and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this value. + FileSize *int64 `json:"file_size,omitempty"` +} + +// This object represents an audio file to be treated as music by the Telegram clients. +type Audio struct { + // Identifier for this file, which can be used to download or reuse the file + FileID string `json:"file_id"` + // Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file. + FileUniqueID string `json:"file_unique_id"` + // Duration of the audio in seconds as defined by the sender + Duration int64 `json:"duration"` + // Optional. Performer of the audio as defined by the sender or by audio tags + Performer string `json:"performer,omitempty"` + // Optional. Title of the audio as defined by the sender or by audio tags + Title string `json:"title,omitempty"` + // Optional. Original filename as defined by the sender + FileName string `json:"file_name,omitempty"` + // Optional. MIME type of the file as defined by the sender + MimeType string `json:"mime_type,omitempty"` + // Optional. File size in bytes. It can be bigger than 2^31 and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this value. + FileSize *int64 `json:"file_size,omitempty"` + // Optional. Thumbnail of the album cover to which the music file belongs + Thumbnail *PhotoSize `json:"thumbnail,omitempty"` +} + +// This object represents a general file (as opposed to photos, voice messages and audio files). +type Document struct { + // Identifier for this file, which can be used to download or reuse the file + FileID string `json:"file_id"` + // Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file. + FileUniqueID string `json:"file_unique_id"` + // Optional. Document thumbnail as defined by the sender + Thumbnail *PhotoSize `json:"thumbnail,omitempty"` + // Optional. Original filename as defined by the sender + FileName string `json:"file_name,omitempty"` + // Optional. MIME type of the file as defined by the sender + MimeType string `json:"mime_type,omitempty"` + // Optional. File size in bytes. It can be bigger than 2^31 and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this value. + FileSize *int64 `json:"file_size,omitempty"` +} + +// This object represents a live photo. +type LivePhoto struct { + // Optional. Available sizes of the corresponding static photo + Photo []PhotoSize `json:"photo,omitempty"` + // Identifier for the video file which can be used to download or reuse the file + FileID string `json:"file_id"` + // Unique identifier for the video file which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file. + FileUniqueID string `json:"file_unique_id"` + // Video width as defined by the sender + Width int64 `json:"width"` + // Video height as defined by the sender + Height int64 `json:"height"` + // Duration of the video in seconds as defined by the sender + Duration int64 `json:"duration"` + // Optional. MIME type of the file as defined by the sender + MimeType string `json:"mime_type,omitempty"` + // Optional. File size in bytes. It can be bigger than 2^31 and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this value. + FileSize *int64 `json:"file_size,omitempty"` +} + +// This object represents a story. +type Story struct { + // Chat that posted the story + Chat Chat `json:"chat"` + // Unique identifier for the story in the chat + ID int64 `json:"id"` +} + +// This object represents a video file of a specific quality. +type VideoQuality struct { + // Identifier for this file, which can be used to download or reuse the file + FileID string `json:"file_id"` + // Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file. + FileUniqueID string `json:"file_unique_id"` + // Video width + Width int64 `json:"width"` + // Video height + Height int64 `json:"height"` + // Codec that was used to encode the video, for example, “h264”, “h265”, or “av01” + Codec string `json:"codec"` + // Optional. File size in bytes. It can be bigger than 2^31 and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this value. + FileSize *int64 `json:"file_size,omitempty"` +} + +// This object represents a video file. +type Video struct { + // Identifier for this file, which can be used to download or reuse the file + FileID string `json:"file_id"` + // Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file. + FileUniqueID string `json:"file_unique_id"` + // Video width as defined by the sender + Width int64 `json:"width"` + // Video height as defined by the sender + Height int64 `json:"height"` + // Duration of the video in seconds as defined by the sender + Duration int64 `json:"duration"` + // Optional. Video thumbnail + Thumbnail *PhotoSize `json:"thumbnail,omitempty"` + // Optional. Available sizes of the cover of the video in the message + Cover []PhotoSize `json:"cover,omitempty"` + // Optional. Timestamp in seconds from which the video will play in the message + StartTimestamp *int64 `json:"start_timestamp,omitempty"` + // Optional. List of available qualities of the video + Qualities []VideoQuality `json:"qualities,omitempty"` + // Optional. Original filename as defined by the sender + FileName string `json:"file_name,omitempty"` + // Optional. MIME type of the file as defined by the sender + MimeType string `json:"mime_type,omitempty"` + // Optional. File size in bytes. It can be bigger than 2^31 and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this value. + FileSize *int64 `json:"file_size,omitempty"` +} + +// This object represents a video message (available in Telegram apps as of v.4.0). +type VideoNote struct { + // Identifier for this file, which can be used to download or reuse the file + FileID string `json:"file_id"` + // Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file. + FileUniqueID string `json:"file_unique_id"` + // Video width and height (diameter of the video message) as defined by the sender + Length int64 `json:"length"` + // Duration of the video in seconds as defined by the sender + Duration int64 `json:"duration"` + // Optional. Video thumbnail + Thumbnail *PhotoSize `json:"thumbnail,omitempty"` + // Optional. File size in bytes + FileSize *int64 `json:"file_size,omitempty"` +} + +// This object represents a voice note. +type Voice struct { + // Identifier for this file, which can be used to download or reuse the file + FileID string `json:"file_id"` + // Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file. + FileUniqueID string `json:"file_unique_id"` + // Duration of the audio in seconds as defined by the sender + Duration int64 `json:"duration"` + // Optional. MIME type of the file as defined by the sender + MimeType string `json:"mime_type,omitempty"` + // Optional. File size in bytes. It can be bigger than 2^31 and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this value. + FileSize *int64 `json:"file_size,omitempty"` +} + +// Describes the paid media added to a message. +type PaidMediaInfo struct { + // The number of Telegram Stars that must be paid to buy access to the media + StarCount int64 `json:"star_count"` + // Information about the paid media + PaidMedia []PaidMedia `json:"paid_media"` +} + +// UnmarshalJSON decodes PaidMediaInfo by dispatching union-typed fields +// (PaidMedia) through their concrete UnmarshalXxx helpers. +func (m *PaidMediaInfo) UnmarshalJSON(data []byte) error { + type Alias PaidMediaInfo + aux := &struct { + PaidMedia json.RawMessage `json:"paid_media,omitempty"` + *Alias + }{Alias: (*Alias)(m)} + if err := json.Unmarshal(data, aux); err != nil { + return err + } + + if len(aux.PaidMedia) > 0 && string(aux.PaidMedia) != "null" { + var raws []json.RawMessage + if err := json.Unmarshal(aux.PaidMedia, &raws); err != nil { + return fmt.Errorf("decoding paid_media: %w", err) + } + decoded := make([]PaidMedia, 0, len(raws)) + for i, r := range raws { + v, err := UnmarshalPaidMedia(r) + if err != nil { + return fmt.Errorf("decoding paid_media[%d]: %w", i, err) + } + decoded = append(decoded, v) + } + m.PaidMedia = decoded + + } + + return nil +} + +// PaidMedia is a union type. The following concrete variants implement +// it: +// - PaidMediaLivePhoto +// - PaidMediaPhoto +// - PaidMediaPreview +// - PaidMediaVideo +// +// This object describes paid media. Currently, it can be one of +type PaidMedia interface{ isPaidMedia() } + +// isPaidMedia is the marker method that makes PaidMediaLivePhoto implement PaidMedia. +func (*PaidMediaLivePhoto) isPaidMedia() {} + +// isPaidMedia is the marker method that makes PaidMediaPhoto implement PaidMedia. +func (*PaidMediaPhoto) isPaidMedia() {} + +// isPaidMedia is the marker method that makes PaidMediaPreview implement PaidMedia. +func (*PaidMediaPreview) isPaidMedia() {} + +// isPaidMedia is the marker method that makes PaidMediaVideo implement PaidMedia. +func (*PaidMediaVideo) isPaidMedia() {} + +// UnmarshalPaidMedia decodes a PaidMedia from JSON by inspecting the +// "type" field and dispatching to the correct concrete type. +func UnmarshalPaidMedia(data []byte) (PaidMedia, error) { + var probe struct { + V string `json:"type"` + } + if err := json.Unmarshal(data, &probe); err != nil { + return nil, err + } + var v PaidMedia + switch probe.V { + case "photo": + v = &PaidMediaPhoto{} + case "preview": + v = &PaidMediaPreview{} + case "video": + v = &PaidMediaVideo{} + default: + return nil, fmt.Errorf("PaidMedia: unknown type %q", probe.V) + } + if err := json.Unmarshal(data, v); err != nil { + return nil, err + } + return v, nil +} + +// The paid media is a live photo. +type PaidMediaLivePhoto struct { + // Type of the paid media, always “live_photo” + Type string `json:"type"` + // The photo + LivePhoto LivePhoto `json:"live_photo"` +} + +// The paid media is a photo. +type PaidMediaPhoto struct { + // Type of the paid media, always “photo” + Type string `json:"type"` + // The photo + Photo []PhotoSize `json:"photo"` +} + +// The paid media isn't available before the payment. +type PaidMediaPreview struct { + // Type of the paid media, always “preview” + Type string `json:"type"` + // Optional. Media width as defined by the sender + Width *int64 `json:"width,omitempty"` + // Optional. Media height as defined by the sender + Height *int64 `json:"height,omitempty"` + // Optional. Duration of the media in seconds as defined by the sender + Duration *int64 `json:"duration,omitempty"` +} + +// The paid media is a video. +type PaidMediaVideo struct { + // Type of the paid media, always “video” + Type string `json:"type"` + // The video + Video Video `json:"video"` +} + +// This object represents a phone contact. +type Contact struct { + // Contact's phone number + PhoneNumber string `json:"phone_number"` + // Contact's first name + FirstName string `json:"first_name"` + // Optional. Contact's last name + LastName string `json:"last_name,omitempty"` + // Optional. Contact's user identifier in Telegram. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a 64-bit integer or double-precision float type are safe for storing this identifier. + UserID *int64 `json:"user_id,omitempty"` + // Optional. Additional data about the contact in the form of a vCard + Vcard string `json:"vcard,omitempty"` +} + +// This object represents an animated emoji that displays a random value. +type Dice struct { + // Emoji on which the dice throw animation is based + Emoji string `json:"emoji"` + // Value of the dice, 1-6 for “”, “” and “” base emoji, 1-5 for “” and “” base emoji, 1-64 for “” base emoji + Value int64 `json:"value"` +} + +// At most one of the optional fields can be present in any given object. +type PollMedia struct { + // Optional. Media is an animation, information about the animation + Animation *Animation `json:"animation,omitempty"` + // Optional. Media is an audio file, information about the file; currently, can't be received in a poll option + Audio *Audio `json:"audio,omitempty"` + // Optional. Media is a general file, information about the file; currently, can't be received in a poll option + Document *Document `json:"document,omitempty"` + // Optional. Media is a live photo, information about the live photo + LivePhoto *LivePhoto `json:"live_photo,omitempty"` + // Optional. Media is a shared location, information about the location + Location *Location `json:"location,omitempty"` + // Optional. Media is a photo, available sizes of the photo + Photo []PhotoSize `json:"photo,omitempty"` + // Optional. Media is a sticker, information about the sticker; currently, for poll options only + Sticker *Sticker `json:"sticker,omitempty"` + // Optional. Media is a venue, information about the venue + Venue *Venue `json:"venue,omitempty"` + // Optional. Media is a video, information about the video + Video *Video `json:"video,omitempty"` +} + +// InputPollMedia is a union type. The following concrete variants implement +// it: +// - InputMediaAnimation +// - InputMediaAudio +// - InputMediaDocument +// - InputMediaLivePhoto +// - InputMediaLocation +// - InputMediaPhoto +// - InputMediaVenue +// - InputMediaVideo +// +// This object represents the content of a poll description or a quiz explanation to be sent. It should be one of +type InputPollMedia interface{ isInputPollMedia() } + +// isInputPollMedia is the marker method that makes InputMediaAnimation implement InputPollMedia. +func (*InputMediaAnimation) isInputPollMedia() {} + +// isInputPollMedia is the marker method that makes InputMediaAudio implement InputPollMedia. +func (*InputMediaAudio) isInputPollMedia() {} + +// isInputPollMedia is the marker method that makes InputMediaDocument implement InputPollMedia. +func (*InputMediaDocument) isInputPollMedia() {} + +// isInputPollMedia is the marker method that makes InputMediaLivePhoto implement InputPollMedia. +func (*InputMediaLivePhoto) isInputPollMedia() {} + +// isInputPollMedia is the marker method that makes InputMediaLocation implement InputPollMedia. +func (*InputMediaLocation) isInputPollMedia() {} + +// isInputPollMedia is the marker method that makes InputMediaPhoto implement InputPollMedia. +func (*InputMediaPhoto) isInputPollMedia() {} + +// isInputPollMedia is the marker method that makes InputMediaVenue implement InputPollMedia. +func (*InputMediaVenue) isInputPollMedia() {} + +// isInputPollMedia is the marker method that makes InputMediaVideo implement InputPollMedia. +func (*InputMediaVideo) isInputPollMedia() {} + +// InputPollOptionMedia is a union type. The following concrete variants implement +// it: +// - InputMediaAnimation +// - InputMediaLivePhoto +// - InputMediaLocation +// - InputMediaPhoto +// - InputMediaSticker +// - InputMediaVenue +// - InputMediaVideo +// +// This object represents the content of a poll option to be sent. It should be one of +type InputPollOptionMedia interface{ isInputPollOptionMedia() } + +// isInputPollOptionMedia is the marker method that makes InputMediaAnimation implement InputPollOptionMedia. +func (*InputMediaAnimation) isInputPollOptionMedia() {} + +// isInputPollOptionMedia is the marker method that makes InputMediaLivePhoto implement InputPollOptionMedia. +func (*InputMediaLivePhoto) isInputPollOptionMedia() {} + +// isInputPollOptionMedia is the marker method that makes InputMediaLocation implement InputPollOptionMedia. +func (*InputMediaLocation) isInputPollOptionMedia() {} + +// isInputPollOptionMedia is the marker method that makes InputMediaPhoto implement InputPollOptionMedia. +func (*InputMediaPhoto) isInputPollOptionMedia() {} + +// isInputPollOptionMedia is the marker method that makes InputMediaSticker implement InputPollOptionMedia. +func (*InputMediaSticker) isInputPollOptionMedia() {} + +// isInputPollOptionMedia is the marker method that makes InputMediaVenue implement InputPollOptionMedia. +func (*InputMediaVenue) isInputPollOptionMedia() {} + +// isInputPollOptionMedia is the marker method that makes InputMediaVideo implement InputPollOptionMedia. +func (*InputMediaVideo) isInputPollOptionMedia() {} + +// This object contains information about one answer option in a poll. +type PollOption struct { + // Unique identifier of the option, persistent on option addition and deletion + PersistentID string `json:"persistent_id"` + // Option text, 1-100 characters + Text string `json:"text"` + // Optional. Special entities that appear in the option text. Currently, only custom emoji entities are allowed in poll option texts + TextEntities []MessageEntity `json:"text_entities,omitempty"` + // Optional. Media added to the poll option + Media *PollMedia `json:"media,omitempty"` + // Number of users who voted for this option; may be 0 if unknown + VoterCount int64 `json:"voter_count"` + // Optional. User who added the option; omitted if the option wasn't added by a user after poll creation + AddedByUser *User `json:"added_by_user,omitempty"` + // Optional. Chat that added the option; omitted if the option wasn't added by a chat after poll creation + AddedByChat *Chat `json:"added_by_chat,omitempty"` + // Optional. Point in time (Unix timestamp) when the option was added; omitted if the option existed in the original poll + AdditionDate *int64 `json:"addition_date,omitempty"` +} + +// This object contains information about one answer option in a poll to be sent. +type InputPollOption struct { + // Option text, 1-100 characters + Text string `json:"text"` + // Optional. Mode for parsing entities in the text. See formatting options for more details. Currently, only custom emoji entities are allowed + TextParseMode string `json:"text_parse_mode,omitempty"` + // Optional. A JSON-serialized list of special entities that appear in the poll option text. It can be specified instead of text_parse_mode + TextEntities []MessageEntity `json:"text_entities,omitempty"` + // Optional. Media added to the poll option + Media *InputPollOptionMedia `json:"media,omitempty"` +} + +// This object represents an answer of a user in a non-anonymous poll. +type PollAnswer struct { + // Unique poll identifier + PollID string `json:"poll_id"` + // Optional. The chat that changed the answer to the poll, if the voter is anonymous + VoterChat *Chat `json:"voter_chat,omitempty"` + // Optional. The user that changed the answer to the poll, if the voter isn't anonymous + User *User `json:"user,omitempty"` + // 0-based identifiers of chosen answer options. May be empty if the vote was retracted. + OptionIds []int64 `json:"option_ids"` + // Persistent identifiers of the chosen answer options. May be empty if the vote was retracted. + OptionPersistentIds []string `json:"option_persistent_ids"` +} + +// This object contains information about a poll. +type Poll struct { + // Unique poll identifier + ID string `json:"id"` + // Poll question, 1-300 characters + Question string `json:"question"` + // Optional. Special entities that appear in the question. Currently, only custom emoji entities are allowed in poll questions + QuestionEntities []MessageEntity `json:"question_entities,omitempty"` + // List of poll options + Options []PollOption `json:"options"` + // Total number of users that voted in the poll + TotalVoterCount int64 `json:"total_voter_count"` + // True, if the poll is closed + IsClosed bool `json:"is_closed"` + // True, if the poll is anonymous + IsAnonymous bool `json:"is_anonymous"` + // Poll type, currently can be “regular” or “quiz” + Type string `json:"type"` + // True, if the poll allows multiple answers + AllowsMultipleAnswers bool `json:"allows_multiple_answers"` + // True, if the poll allows to change the chosen answer options + AllowsRevoting bool `json:"allows_revoting"` + // True if voting is limited to users who have been members of the chat where the poll was originally sent for more than 24 hours + MembersOnly bool `json:"members_only"` + // Optional. A list of two-letter ISO 3166-1 alpha-2 country codes indicating the countries from which users can vote in the poll. If omitted, then users from any country can participate in the poll. + CountryCodes []string `json:"country_codes,omitempty"` + // Optional. Array of 0-based identifiers of the correct answer options. Available only for polls in quiz mode which are closed or were sent (not forwarded) by the bot or to the private chat with the bot. + CorrectOptionIds []int64 `json:"correct_option_ids,omitempty"` + // Optional. Text that is shown when a user chooses an incorrect answer or taps on the lamp icon in a quiz-style poll, 0-200 characters + Explanation string `json:"explanation,omitempty"` + // Optional. Special entities like usernames, URLs, bot commands, etc. that appear in the explanation + ExplanationEntities []MessageEntity `json:"explanation_entities,omitempty"` + // Optional. Media added to the quiz explanation + ExplanationMedia *PollMedia `json:"explanation_media,omitempty"` + // Optional. Amount of time in seconds the poll will be active after creation + OpenPeriod *int64 `json:"open_period,omitempty"` + // Optional. Point in time (Unix timestamp) when the poll will be automatically closed + CloseDate *int64 `json:"close_date,omitempty"` + // Optional. Description of the poll; for polls inside the Message object only + Description string `json:"description,omitempty"` + // Optional. Special entities like usernames, URLs, bot commands, etc. that appear in the description + DescriptionEntities []MessageEntity `json:"description_entities,omitempty"` + // Optional. Media added to the poll description; for polls inside the Message object only + Media *PollMedia `json:"media,omitempty"` +} + +// Describes a task in a checklist. +type ChecklistTask struct { + // Unique identifier of the task + ID int64 `json:"id"` + // Text of the task + Text string `json:"text"` + // Optional. Special entities that appear in the task text + TextEntities []MessageEntity `json:"text_entities,omitempty"` + // Optional. User that completed the task; omitted if the task wasn't completed by a user + CompletedByUser *User `json:"completed_by_user,omitempty"` + // Optional. Chat that completed the task; omitted if the task wasn't completed by a chat + CompletedByChat *Chat `json:"completed_by_chat,omitempty"` + // Optional. Point in time (Unix timestamp) when the task was completed; 0 if the task wasn't completed + CompletionDate *int64 `json:"completion_date,omitempty"` +} + +// Describes a checklist. +type Checklist struct { + // Title of the checklist + Title string `json:"title"` + // Optional. Special entities that appear in the checklist title + TitleEntities []MessageEntity `json:"title_entities,omitempty"` + // List of tasks in the checklist + Tasks []ChecklistTask `json:"tasks"` + // Optional. True, if users other than the creator of the list can add tasks to the list + OthersCanAddTasks *bool `json:"others_can_add_tasks,omitempty"` + // Optional. True, if users other than the creator of the list can mark tasks as done or not done + OthersCanMarkTasksAsDone *bool `json:"others_can_mark_tasks_as_done,omitempty"` +} + +// Describes a task to add to a checklist. +type InputChecklistTask struct { + // Unique identifier of the task; must be positive and unique among all task identifiers currently present in the checklist + ID int64 `json:"id"` + // Text of the task; 1-100 characters after entities parsing + Text string `json:"text"` + // Optional. Mode for parsing entities in the text. See formatting options for more details. + ParseMode string `json:"parse_mode,omitempty"` + // Optional. List of special entities that appear in the text, which can be specified instead of parse_mode. Currently, only bold, italic, underline, strikethrough, spoiler, custom_emoji, and date_time entities are allowed. + TextEntities []MessageEntity `json:"text_entities,omitempty"` +} + +// Describes a checklist to create. +type InputChecklist struct { + // Title of the checklist; 1-255 characters after entities parsing + Title string `json:"title"` + // Optional. Mode for parsing entities in the title. See formatting options for more details. + ParseMode string `json:"parse_mode,omitempty"` + // Optional. List of special entities that appear in the title, which can be specified instead of parse_mode. Currently, only bold, italic, underline, strikethrough, spoiler, custom_emoji, and date_time entities are allowed. + TitleEntities []MessageEntity `json:"title_entities,omitempty"` + // List of 1-30 tasks in the checklist + Tasks []InputChecklistTask `json:"tasks"` + // Optional. Pass True if other users can add tasks to the checklist + OthersCanAddTasks *bool `json:"others_can_add_tasks,omitempty"` + // Optional. Pass True if other users can mark tasks as done or not done in the checklist + OthersCanMarkTasksAsDone *bool `json:"others_can_mark_tasks_as_done,omitempty"` +} + +// Describes a service message about checklist tasks marked as done or not done. +type ChecklistTasksDone struct { + // Optional. Message containing the checklist whose tasks were marked as done or not done. Note that the Message object in this field will not contain the reply_to_message field even if it itself is a reply. + ChecklistMessage *Message `json:"checklist_message,omitempty"` + // Optional. Identifiers of the tasks that were marked as done + MarkedAsDoneTaskIds []int64 `json:"marked_as_done_task_ids,omitempty"` + // Optional. Identifiers of the tasks that were marked as not done + MarkedAsNotDoneTaskIds []int64 `json:"marked_as_not_done_task_ids,omitempty"` +} + +// Describes a service message about tasks added to a checklist. +type ChecklistTasksAdded struct { + // Optional. Message containing the checklist to which the tasks were added. Note that the Message object in this field will not contain the reply_to_message field even if it itself is a reply. + ChecklistMessage *Message `json:"checklist_message,omitempty"` + // List of tasks added to the checklist + Tasks []ChecklistTask `json:"tasks"` +} + +// This object represents a point on the map. +type Location struct { + // Latitude as defined by the sender + Latitude float64 `json:"latitude"` + // Longitude as defined by the sender + Longitude float64 `json:"longitude"` + // Optional. The radius of uncertainty for the location, measured in meters; 0-1500 + HorizontalAccuracy *float64 `json:"horizontal_accuracy,omitempty"` + // Optional. Time relative to the message sending date, during which the location can be updated; in seconds. For active live locations only. + LivePeriod *int64 `json:"live_period,omitempty"` + // Optional. The direction in which user is moving, in degrees; 1-360. For active live locations only. + Heading *int64 `json:"heading,omitempty"` + // Optional. The maximum distance for proximity alerts about approaching another chat member, in meters. For sent live locations only. + ProximityAlertRadius *int64 `json:"proximity_alert_radius,omitempty"` +} + +// This object represents a venue. +type Venue struct { + // Venue location. Can't be a live location + Location Location `json:"location"` + // Name of the venue + Title string `json:"title"` + // Address of the venue + Address string `json:"address"` + // Optional. Foursquare identifier of the venue + FoursquareID string `json:"foursquare_id,omitempty"` + // Optional. Foursquare type of the venue. (For example, “arts_entertainment/default”, “arts_entertainment/aquarium” or “food/icecream”.) + FoursquareType string `json:"foursquare_type,omitempty"` + // Optional. Google Places identifier of the venue + GooglePlaceID string `json:"google_place_id,omitempty"` + // Optional. Google Places type of the venue. (See supported types.) + GooglePlaceType string `json:"google_place_type,omitempty"` +} + +// Describes data sent from a Web App to the bot. +type WebAppData struct { + // The data. Be aware that a bad client can send arbitrary data in this field. + Data string `json:"data"` + // Text of the web_app keyboard button from which the Web App was opened. Be aware that a bad client can send arbitrary data in this field. + ButtonText string `json:"button_text"` +} + +// This object represents the content of a service message, sent whenever a user in the chat triggers a proximity alert set by another user. +type ProximityAlertTriggered struct { + // User that triggered the alert + Traveler User `json:"traveler"` + // User that set the alert + Watcher User `json:"watcher"` + // The distance between the users + Distance int64 `json:"distance"` +} + +// This object represents a service message about a change in auto-delete timer settings. +type MessageAutoDeleteTimerChanged struct { + // New auto-delete time for messages in the chat; in seconds + MessageAutoDeleteTime int64 `json:"message_auto_delete_time"` +} + +// This object contains information about the bot that was created to be managed by the current bot. +type ManagedBotCreated struct { + // Information about the bot. The bot's token can be fetched using the method getManagedBotToken. + Bot User `json:"bot"` +} + +// This object contains information about the creation, token update, or owner update of a bot that is managed by the current bot. +type ManagedBotUpdated struct { + // User that created the bot + User User `json:"user"` + // Information about the bot. Token of the bot can be fetched using the method getManagedBotToken. + Bot User `json:"bot"` +} + +// Describes a service message about an option added to a poll. +type PollOptionAdded struct { + // Optional. Message containing the poll to which the option was added, if known. Note that the Message object in this field will not contain the reply_to_message field even if it itself is a reply. + PollMessage MaybeInaccessibleMessage `json:"poll_message,omitempty"` + // Unique identifier of the added option + OptionPersistentID string `json:"option_persistent_id"` + // Option text + OptionText string `json:"option_text"` + // Optional. Special entities that appear in the option_text + OptionTextEntities []MessageEntity `json:"option_text_entities,omitempty"` +} + +// UnmarshalJSON decodes PollOptionAdded by dispatching union-typed fields +// (PollMessage) through their concrete UnmarshalXxx helpers. +func (m *PollOptionAdded) UnmarshalJSON(data []byte) error { + type Alias PollOptionAdded + aux := &struct { + PollMessage json.RawMessage `json:"poll_message,omitempty"` + *Alias + }{Alias: (*Alias)(m)} + if err := json.Unmarshal(data, aux); err != nil { + return err + } + + if len(aux.PollMessage) > 0 && string(aux.PollMessage) != "null" { + v, err := UnmarshalMaybeInaccessibleMessage(aux.PollMessage) + if err != nil { + return fmt.Errorf("decoding poll_message: %w", err) + } + m.PollMessage = v + + } + + return nil +} + +// Describes a service message about an option deleted from a poll. +type PollOptionDeleted struct { + // Optional. Message containing the poll from which the option was deleted, if known. Note that the Message object in this field will not contain the reply_to_message field even if it itself is a reply. + PollMessage MaybeInaccessibleMessage `json:"poll_message,omitempty"` + // Unique identifier of the deleted option + OptionPersistentID string `json:"option_persistent_id"` + // Option text + OptionText string `json:"option_text"` + // Optional. Special entities that appear in the option_text + OptionTextEntities []MessageEntity `json:"option_text_entities,omitempty"` +} + +// UnmarshalJSON decodes PollOptionDeleted by dispatching union-typed fields +// (PollMessage) through their concrete UnmarshalXxx helpers. +func (m *PollOptionDeleted) UnmarshalJSON(data []byte) error { + type Alias PollOptionDeleted + aux := &struct { + PollMessage json.RawMessage `json:"poll_message,omitempty"` + *Alias + }{Alias: (*Alias)(m)} + if err := json.Unmarshal(data, aux); err != nil { + return err + } + + if len(aux.PollMessage) > 0 && string(aux.PollMessage) != "null" { + v, err := UnmarshalMaybeInaccessibleMessage(aux.PollMessage) + if err != nil { + return fmt.Errorf("decoding poll_message: %w", err) + } + m.PollMessage = v + + } + + return nil +} + +// This object represents a service message about a user boosting a chat. +type ChatBoostAdded struct { + // Number of boosts added by the user + BoostCount int64 `json:"boost_count"` +} + +// BackgroundFill is a union type. The following concrete variants implement +// it: +// - BackgroundFillSolid +// - BackgroundFillGradient +// - BackgroundFillFreeformGradient +// +// This object describes the way a background is filled based on the selected colors. Currently, it can be one of +type BackgroundFill interface{ isBackgroundFill() } + +// isBackgroundFill is the marker method that makes BackgroundFillSolid implement BackgroundFill. +func (*BackgroundFillSolid) isBackgroundFill() {} + +// isBackgroundFill is the marker method that makes BackgroundFillGradient implement BackgroundFill. +func (*BackgroundFillGradient) isBackgroundFill() {} + +// isBackgroundFill is the marker method that makes BackgroundFillFreeformGradient implement BackgroundFill. +func (*BackgroundFillFreeformGradient) isBackgroundFill() {} + +// UnmarshalBackgroundFill decodes a BackgroundFill from JSON by inspecting the +// "type" field and dispatching to the correct concrete type. +func UnmarshalBackgroundFill(data []byte) (BackgroundFill, error) { + var probe struct { + V string `json:"type"` + } + if err := json.Unmarshal(data, &probe); err != nil { + return nil, err + } + var v BackgroundFill + switch probe.V { + case "freeform_gradient": + v = &BackgroundFillFreeformGradient{} + case "gradient": + v = &BackgroundFillGradient{} + case "solid": + v = &BackgroundFillSolid{} + default: + return nil, fmt.Errorf("BackgroundFill: unknown type %q", probe.V) + } + if err := json.Unmarshal(data, v); err != nil { + return nil, err + } + return v, nil +} + +// The background is filled using the selected color. +type BackgroundFillSolid struct { + // Type of the background fill, always “solid” + Type string `json:"type"` + // The color of the background fill in the RGB24 format + Color int64 `json:"color"` +} + +// The background is a gradient fill. +type BackgroundFillGradient struct { + // Type of the background fill, always “gradient” + Type string `json:"type"` + // Top color of the gradient in the RGB24 format + TopColor int64 `json:"top_color"` + // Bottom color of the gradient in the RGB24 format + BottomColor int64 `json:"bottom_color"` + // Clockwise rotation angle of the background fill in degrees; 0-359 + RotationAngle int64 `json:"rotation_angle"` +} + +// The background is a freeform gradient that rotates after every message in the chat. +type BackgroundFillFreeformGradient struct { + // Type of the background fill, always “freeform_gradient” + Type string `json:"type"` + // A list of the 3 or 4 base colors that are used to generate the freeform gradient in the RGB24 format + Colors []int64 `json:"colors"` +} + +// BackgroundType is a union type. The following concrete variants implement +// it: +// - BackgroundTypeFill +// - BackgroundTypeWallpaper +// - BackgroundTypePattern +// - BackgroundTypeChatTheme +// +// This object describes the type of a background. Currently, it can be one of +type BackgroundType interface{ isBackgroundType() } + +// isBackgroundType is the marker method that makes BackgroundTypeFill implement BackgroundType. +func (*BackgroundTypeFill) isBackgroundType() {} + +// isBackgroundType is the marker method that makes BackgroundTypeWallpaper implement BackgroundType. +func (*BackgroundTypeWallpaper) isBackgroundType() {} + +// isBackgroundType is the marker method that makes BackgroundTypePattern implement BackgroundType. +func (*BackgroundTypePattern) isBackgroundType() {} + +// isBackgroundType is the marker method that makes BackgroundTypeChatTheme implement BackgroundType. +func (*BackgroundTypeChatTheme) isBackgroundType() {} + +// UnmarshalBackgroundType decodes a BackgroundType from JSON by inspecting the +// "type" field and dispatching to the correct concrete type. +func UnmarshalBackgroundType(data []byte) (BackgroundType, error) { + var probe struct { + V string `json:"type"` + } + if err := json.Unmarshal(data, &probe); err != nil { + return nil, err + } + var v BackgroundType + switch probe.V { + case "chat_theme": + v = &BackgroundTypeChatTheme{} + case "fill": + v = &BackgroundTypeFill{} + case "pattern": + v = &BackgroundTypePattern{} + case "wallpaper": + v = &BackgroundTypeWallpaper{} + default: + return nil, fmt.Errorf("BackgroundType: unknown type %q", probe.V) + } + if err := json.Unmarshal(data, v); err != nil { + return nil, err + } + return v, nil +} + +// The background is automatically filled based on the selected colors. +type BackgroundTypeFill struct { + // Type of the background, always “fill” + Type string `json:"type"` + // The background fill + Fill BackgroundFill `json:"fill"` + // Dimming of the background in dark themes, as a percentage; 0-100 + DarkThemeDimming int64 `json:"dark_theme_dimming"` +} + +// UnmarshalJSON decodes BackgroundTypeFill by dispatching union-typed fields +// (Fill) through their concrete UnmarshalXxx helpers. +func (m *BackgroundTypeFill) UnmarshalJSON(data []byte) error { + type Alias BackgroundTypeFill + aux := &struct { + Fill json.RawMessage `json:"fill,omitempty"` + *Alias + }{Alias: (*Alias)(m)} + if err := json.Unmarshal(data, aux); err != nil { + return err + } + + if len(aux.Fill) > 0 && string(aux.Fill) != "null" { + v, err := UnmarshalBackgroundFill(aux.Fill) + if err != nil { + return fmt.Errorf("decoding fill: %w", err) + } + m.Fill = v + + } + + return nil +} + +// The background is a wallpaper in the JPEG format. +type BackgroundTypeWallpaper struct { + // Type of the background, always “wallpaper” + Type string `json:"type"` + // Document with the wallpaper + Document Document `json:"document"` + // Dimming of the background in dark themes, as a percentage; 0-100 + DarkThemeDimming int64 `json:"dark_theme_dimming"` + // Optional. True, if the wallpaper is downscaled to fit in a 450x450 square and then box-blurred with radius 12 + IsBlurred *bool `json:"is_blurred,omitempty"` + // Optional. True, if the background moves slightly when the device is tilted + IsMoving *bool `json:"is_moving,omitempty"` +} + +// The background is a .PNG or .TGV (gzipped subset of SVG with MIME type “application/x-tgwallpattern”) pattern to be combined with the background fill chosen by the user. +type BackgroundTypePattern struct { + // Type of the background, always “pattern” + Type string `json:"type"` + // Document with the pattern + Document Document `json:"document"` + // The background fill that is combined with the pattern + Fill BackgroundFill `json:"fill"` + // Intensity of the pattern when it is shown above the filled background; 0-100 + Intensity int64 `json:"intensity"` + // Optional. True, if the background fill must be applied only to the pattern itself. All other pixels are black in this case. For dark themes only + IsInverted *bool `json:"is_inverted,omitempty"` + // Optional. True, if the background moves slightly when the device is tilted + IsMoving *bool `json:"is_moving,omitempty"` +} + +// UnmarshalJSON decodes BackgroundTypePattern by dispatching union-typed fields +// (Fill) through their concrete UnmarshalXxx helpers. +func (m *BackgroundTypePattern) UnmarshalJSON(data []byte) error { + type Alias BackgroundTypePattern + aux := &struct { + Fill json.RawMessage `json:"fill,omitempty"` + *Alias + }{Alias: (*Alias)(m)} + if err := json.Unmarshal(data, aux); err != nil { + return err + } + + if len(aux.Fill) > 0 && string(aux.Fill) != "null" { + v, err := UnmarshalBackgroundFill(aux.Fill) + if err != nil { + return fmt.Errorf("decoding fill: %w", err) + } + m.Fill = v + + } + + return nil +} + +// The background is taken directly from a built-in chat theme. +type BackgroundTypeChatTheme struct { + // Type of the background, always “chat_theme” + Type string `json:"type"` + // Name of the chat theme, which is usually an emoji + ThemeName string `json:"theme_name"` +} + +// This object represents a chat background. +type ChatBackground struct { + // Type of the background + Type BackgroundType `json:"type"` +} + +// UnmarshalJSON decodes ChatBackground by dispatching union-typed fields +// (Type) through their concrete UnmarshalXxx helpers. +func (m *ChatBackground) UnmarshalJSON(data []byte) error { + type Alias ChatBackground + aux := &struct { + Type json.RawMessage `json:"type,omitempty"` + *Alias + }{Alias: (*Alias)(m)} + if err := json.Unmarshal(data, aux); err != nil { + return err + } + + if len(aux.Type) > 0 && string(aux.Type) != "null" { + v, err := UnmarshalBackgroundType(aux.Type) + if err != nil { + return fmt.Errorf("decoding type: %w", err) + } + m.Type = v + + } + + return nil +} + +// This object represents a service message about a new forum topic created in the chat. +type ForumTopicCreated struct { + // Name of the topic + Name string `json:"name"` + // Color of the topic icon in RGB format + IconColor int64 `json:"icon_color"` + // Optional. Unique identifier of the custom emoji shown as the topic icon + IconCustomEmojiID string `json:"icon_custom_emoji_id,omitempty"` + // Optional. True, if the name of the topic wasn't specified explicitly by its creator and likely needs to be changed by the bot + IsNameImplicit *bool `json:"is_name_implicit,omitempty"` +} + +// This object represents a service message about a forum topic closed in the chat. Currently holds no information. +type ForumTopicClosed struct { +} + +// This object represents a service message about an edited forum topic. +type ForumTopicEdited struct { + // Optional. New name of the topic, if it was edited + Name string `json:"name,omitempty"` + // Optional. New identifier of the custom emoji shown as the topic icon, if it was edited; an empty string if the icon was removed + IconCustomEmojiID string `json:"icon_custom_emoji_id,omitempty"` +} + +// This object represents a service message about a forum topic reopened in the chat. Currently holds no information. +type ForumTopicReopened struct { +} + +// This object represents a service message about General forum topic hidden in the chat. Currently holds no information. +type GeneralForumTopicHidden struct { +} + +// This object represents a service message about General forum topic unhidden in the chat. Currently holds no information. +type GeneralForumTopicUnhidden struct { +} + +// This object contains information about a user that was shared with the bot using a KeyboardButtonRequestUsers button. +type SharedUser struct { + // Identifier of the shared user. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so 64-bit integers or double-precision float types are safe for storing these identifiers. The bot may not have access to the user and could be unable to use this identifier, unless the user is already known to the bot by some other means. + UserID int64 `json:"user_id"` + // Optional. First name of the user, if the name was requested by the bot + FirstName string `json:"first_name,omitempty"` + // Optional. Last name of the user, if the name was requested by the bot + LastName string `json:"last_name,omitempty"` + // Optional. Username of the user, if the username was requested by the bot + Username string `json:"username,omitempty"` + // Optional. Available sizes of the chat photo, if the photo was requested by the bot + Photo []PhotoSize `json:"photo,omitempty"` +} + +// This object contains information about the users whose identifiers were shared with the bot using a KeyboardButtonRequestUsers button. +type UsersShared struct { + // Identifier of the request + RequestID int64 `json:"request_id"` + // Information about users shared with the bot. + Users []SharedUser `json:"users"` +} + +// This object contains information about a chat that was shared with the bot using a KeyboardButtonRequestChat button. +type ChatShared struct { + // Identifier of the request + RequestID int64 `json:"request_id"` + // Identifier of the shared chat. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a 64-bit integer or double-precision float type are safe for storing this identifier. The bot may not have access to the chat and could be unable to use this identifier, unless the chat is already known to the bot by some other means. + ChatID int64 `json:"chat_id"` + // Optional. Title of the chat, if the title was requested by the bot. + Title string `json:"title,omitempty"` + // Optional. Username of the chat, if the username was requested by the bot and available. + Username string `json:"username,omitempty"` + // Optional. Available sizes of the chat photo, if the photo was requested by the bot + Photo []PhotoSize `json:"photo,omitempty"` +} + +// This object represents a service message about a user allowing a bot to write messages after adding it to the attachment menu, launching a Web App from a link, or accepting an explicit request from a Web App sent by the method requestWriteAccess. +type WriteAccessAllowed struct { + // Optional. True, if the access was granted after the user accepted an explicit request from a Web App sent by the method requestWriteAccess + FromRequest *bool `json:"from_request,omitempty"` + // Optional. Name of the Web App, if the access was granted when the Web App was launched from a link + WebAppName string `json:"web_app_name,omitempty"` + // Optional. True, if the access was granted when the bot was added to the attachment or side menu + FromAttachmentMenu *bool `json:"from_attachment_menu,omitempty"` +} + +// This object represents a service message about a video chat scheduled in the chat. +type VideoChatScheduled struct { + // Point in time (Unix timestamp) when the video chat is supposed to be started by a chat administrator + StartDate int64 `json:"start_date"` +} + +// This object represents a service message about a video chat started in the chat. Currently holds no information. +type VideoChatStarted struct { +} + +// This object represents a service message about a video chat ended in the chat. +type VideoChatEnded struct { + // Video chat duration in seconds + Duration int64 `json:"duration"` +} + +// This object represents a service message about new members invited to a video chat. +type VideoChatParticipantsInvited struct { + // New members that were invited to the video chat + Users []User `json:"users"` +} + +// Describes a service message about a change in the price of paid messages within a chat. +type PaidMessagePriceChanged struct { + // The new number of Telegram Stars that must be paid by non-administrator users of the supergroup chat for each sent message + PaidMessageStarCount int64 `json:"paid_message_star_count"` +} + +// Describes a service message about a change in the price of direct messages sent to a channel chat. +type DirectMessagePriceChanged struct { + // True, if direct messages are enabled for the channel chat; false otherwise + AreDirectMessagesEnabled bool `json:"are_direct_messages_enabled"` + // Optional. The new number of Telegram Stars that must be paid by users for each direct message sent to the channel. Does not apply to users who have been exempted by administrators. Defaults to 0. + DirectMessageStarCount *int64 `json:"direct_message_star_count,omitempty"` +} + +// Describes a service message about the approval of a suggested post. +type SuggestedPostApproved struct { + // Optional. Message containing the suggested post. Note that the Message object in this field will not contain the reply_to_message field even if it itself is a reply. + SuggestedPostMessage *Message `json:"suggested_post_message,omitempty"` + // Optional. Amount paid for the post + Price *SuggestedPostPrice `json:"price,omitempty"` + // Date when the post will be published + SendDate int64 `json:"send_date"` +} + +// Describes a service message about the failed approval of a suggested post. Currently, only caused by insufficient user funds at the time of approval. +type SuggestedPostApprovalFailed struct { + // Optional. Message containing the suggested post whose approval has failed. Note that the Message object in this field will not contain the reply_to_message field even if it itself is a reply. + SuggestedPostMessage *Message `json:"suggested_post_message,omitempty"` + // Expected price of the post + Price SuggestedPostPrice `json:"price"` +} + +// Describes a service message about the rejection of a suggested post. +type SuggestedPostDeclined struct { + // Optional. Message containing the suggested post. Note that the Message object in this field will not contain the reply_to_message field even if it itself is a reply. + SuggestedPostMessage *Message `json:"suggested_post_message,omitempty"` + // Optional. Comment with which the post was declined + Comment string `json:"comment,omitempty"` +} + +// Describes a service message about a successful payment for a suggested post. +type SuggestedPostPaid struct { + // Optional. Message containing the suggested post. Note that the Message object in this field will not contain the reply_to_message field even if it itself is a reply. + SuggestedPostMessage *Message `json:"suggested_post_message,omitempty"` + // Currency in which the payment was made. Currently, one of “XTR” for Telegram Stars or “TON” for toncoins + Currency string `json:"currency"` + // Optional. The amount of the currency that was received by the channel in nanotoncoins; for payments in toncoins only + Amount *int64 `json:"amount,omitempty"` + // Optional. The amount of Telegram Stars that was received by the channel; for payments in Telegram Stars only + StarAmount *StarAmount `json:"star_amount,omitempty"` +} + +// Describes a service message about a payment refund for a suggested post. +type SuggestedPostRefunded struct { + // Optional. Message containing the suggested post. Note that the Message object in this field will not contain the reply_to_message field even if it itself is a reply. + SuggestedPostMessage *Message `json:"suggested_post_message,omitempty"` + // Reason for the refund. Currently, one of “post_deleted” if the post was deleted within 24 hours of being posted or removed from scheduled messages without being posted, or “payment_refunded” if the payer refunded their payment. + Reason string `json:"reason"` +} + +// This object represents a service message about the creation of a scheduled giveaway. +type GiveawayCreated struct { + // Optional. The number of Telegram Stars to be split between giveaway winners; for Telegram Star giveaways only + PrizeStarCount *int64 `json:"prize_star_count,omitempty"` +} + +// This object represents a message about a scheduled giveaway. +type Giveaway struct { + // The list of chats which the user must join to participate in the giveaway + Chats []Chat `json:"chats"` + // Point in time (Unix timestamp) when winners of the giveaway will be selected + WinnersSelectionDate int64 `json:"winners_selection_date"` + // The number of users which are supposed to be selected as winners of the giveaway + WinnerCount int64 `json:"winner_count"` + // Optional. True, if only users who join the chats after the giveaway started should be eligible to win + OnlyNewMembers *bool `json:"only_new_members,omitempty"` + // Optional. True, if the list of giveaway winners will be visible to everyone + HasPublicWinners *bool `json:"has_public_winners,omitempty"` + // Optional. Description of additional giveaway prize + PrizeDescription string `json:"prize_description,omitempty"` + // Optional. A list of two-letter ISO 3166-1 alpha-2 country codes indicating the countries from which eligible users for the giveaway must come. If empty, then all users can participate in the giveaway. Users with a phone number that was bought on Fragment can always participate in giveaways. + CountryCodes []string `json:"country_codes,omitempty"` + // Optional. The number of Telegram Stars to be split between giveaway winners; for Telegram Star giveaways only + PrizeStarCount *int64 `json:"prize_star_count,omitempty"` + // Optional. The number of months the Telegram Premium subscription won from the giveaway will be active for; for Telegram Premium giveaways only + PremiumSubscriptionMonthCount *int64 `json:"premium_subscription_month_count,omitempty"` +} + +// This object represents a message about the completion of a giveaway with public winners. +type GiveawayWinners struct { + // The chat that created the giveaway + Chat Chat `json:"chat"` + // Identifier of the message with the giveaway in the chat + GiveawayMessageID int64 `json:"giveaway_message_id"` + // Point in time (Unix timestamp) when winners of the giveaway were selected + WinnersSelectionDate int64 `json:"winners_selection_date"` + // Total number of winners in the giveaway + WinnerCount int64 `json:"winner_count"` + // List of up to 100 winners of the giveaway + Winners []User `json:"winners"` + // Optional. The number of other chats the user had to join in order to be eligible for the giveaway + AdditionalChatCount *int64 `json:"additional_chat_count,omitempty"` + // Optional. The number of Telegram Stars that were split between giveaway winners; for Telegram Star giveaways only + PrizeStarCount *int64 `json:"prize_star_count,omitempty"` + // Optional. The number of months the Telegram Premium subscription won from the giveaway will be active for; for Telegram Premium giveaways only + PremiumSubscriptionMonthCount *int64 `json:"premium_subscription_month_count,omitempty"` + // Optional. Number of undistributed prizes + UnclaimedPrizeCount *int64 `json:"unclaimed_prize_count,omitempty"` + // Optional. True, if only users who had joined the chats after the giveaway started were eligible to win + OnlyNewMembers *bool `json:"only_new_members,omitempty"` + // Optional. True, if the giveaway was canceled because the payment for it was refunded + WasRefunded *bool `json:"was_refunded,omitempty"` + // Optional. Description of additional giveaway prize + PrizeDescription string `json:"prize_description,omitempty"` +} + +// This object represents a service message about the completion of a giveaway without public winners. +type GiveawayCompleted struct { + // Number of winners in the giveaway + WinnerCount int64 `json:"winner_count"` + // Optional. Number of undistributed prizes + UnclaimedPrizeCount *int64 `json:"unclaimed_prize_count,omitempty"` + // Optional. Message with the giveaway that was completed, if it wasn't deleted + GiveawayMessage *Message `json:"giveaway_message,omitempty"` + // Optional. True, if the giveaway is a Telegram Star giveaway. Otherwise, currently, the giveaway is a Telegram Premium giveaway. + IsStarGiveaway *bool `json:"is_star_giveaway,omitempty"` +} + +// Describes the options used for link preview generation. +type LinkPreviewOptions struct { + // Optional. True, if the link preview is disabled + IsDisabled *bool `json:"is_disabled,omitempty"` + // Optional. URL to use for the link preview. If empty, then the first URL found in the message text will be used + URL string `json:"url,omitempty"` + // Optional. True, if the media in the link preview is supposed to be shrunk; ignored if the URL isn't explicitly specified or media size change isn't supported for the preview + PreferSmallMedia *bool `json:"prefer_small_media,omitempty"` + // Optional. True, if the media in the link preview is supposed to be enlarged; ignored if the URL isn't explicitly specified or media size change isn't supported for the preview + PreferLargeMedia *bool `json:"prefer_large_media,omitempty"` + // Optional. True, if the link preview must be shown above the message text; otherwise, the link preview will be shown below the message text + ShowAboveText *bool `json:"show_above_text,omitempty"` +} + +// Describes the price of a suggested post. +type SuggestedPostPrice struct { + // Currency in which the post will be paid. Currently, must be one of “XTR” for Telegram Stars or “TON” for toncoins + Currency string `json:"currency"` + // The amount of the currency that will be paid for the post in the smallest units of the currency, i.e. Telegram Stars or nanotoncoins. Currently, price in Telegram Stars must be between 5 and 100000, and price in nanotoncoins must be between 10000000 and 10000000000000. + Amount int64 `json:"amount"` +} + +// Contains information about a suggested post. +type SuggestedPostInfo struct { + // State of the suggested post. Currently, it can be one of “pending”, “approved”, “declined”. + State string `json:"state"` + // Optional. Proposed price of the post. If the field is omitted, then the post is unpaid. + Price *SuggestedPostPrice `json:"price,omitempty"` + // Optional. Proposed send date of the post. If the field is omitted, then the post can be published at any time within 30 days at the sole discretion of the user or administrator who approves it. + SendDate *int64 `json:"send_date,omitempty"` +} + +// Contains parameters of a post that is being suggested by the bot. +type SuggestedPostParameters struct { + // Optional. Proposed price for the post. If the field is omitted, then the post is unpaid. + Price *SuggestedPostPrice `json:"price,omitempty"` + // Optional. Proposed send date of the post. If specified, then the date must be between 300 second and 2678400 seconds (30 days) in the future. If the field is omitted, then the post can be published at any time within 30 days at the sole discretion of the user who approves it. + SendDate *int64 `json:"send_date,omitempty"` +} + +// Describes a topic of a direct messages chat. +type DirectMessagesTopic struct { + // Unique identifier of the topic. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a 64-bit integer or double-precision float type are safe for storing this identifier. + TopicID int64 `json:"topic_id"` + // Optional. Information about the user that created the topic. Currently, it is always present + User *User `json:"user,omitempty"` +} + +// This object represent a user's profile pictures. +type UserProfilePhotos struct { + // Total number of profile pictures the target user has + TotalCount int64 `json:"total_count"` + // Requested profile pictures (in up to 4 sizes each) + Photos [][]PhotoSize `json:"photos"` +} + +// This object represents the audios displayed on a user's profile. +type UserProfileAudios struct { + // Total number of profile audios for the target user + TotalCount int64 `json:"total_count"` + // Requested profile audios + Audios []Audio `json:"audios"` +} + +// This object represents a file ready to be downloaded. The file can be downloaded via the link https://api.telegram.org/file/bot/. It is guaranteed that the link will be valid for at least 1 hour. When the link expires, a new one can be requested by calling getFile. +// The maximum file size to download is 20 MB +type File struct { + // Identifier for this file, which can be used to download or reuse the file + FileID string `json:"file_id"` + // Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file. + FileUniqueID string `json:"file_unique_id"` + // Optional. File size in bytes. It can be bigger than 2^31 and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this value. + FileSize *int64 `json:"file_size,omitempty"` + // Optional. File path. Use https://api.telegram.org/file/bot/ to get the file. + FilePath string `json:"file_path,omitempty"` +} + +// Describes a Web App. +type WebAppInfo struct { + // An HTTPS URL of a Web App to be opened with additional data as specified in Initializing Web Apps + URL string `json:"url"` +} + +// This object represents a custom keyboard with reply options (see Introduction to bots for details and examples). Not supported in channels and for messages sent on behalf of a business account. +type ReplyKeyboardMarkup struct { + // Array of button rows, each represented by an Array of KeyboardButton objects + Keyboard [][]KeyboardButton `json:"keyboard"` + // Optional. Requests clients to always show the keyboard when the regular keyboard is hidden. Defaults to false, in which case the custom keyboard can be hidden and opened with a keyboard icon. + IsPersistent *bool `json:"is_persistent,omitempty"` + // Optional. Requests clients to resize the keyboard vertically for optimal fit (e.g., make the keyboard smaller if there are just two rows of buttons). Defaults to false, in which case the custom keyboard is always of the same height as the app's standard keyboard. + ResizeKeyboard *bool `json:"resize_keyboard,omitempty"` + // Optional. Requests clients to hide the keyboard as soon as it's been used. The keyboard will still be available, but clients will automatically display the usual letter-keyboard in the chat - the user can press a special button in the input field to see the custom keyboard again. Defaults to false. + OneTimeKeyboard *bool `json:"one_time_keyboard,omitempty"` + // Optional. The placeholder to be shown in the input field when the keyboard is active; 1-64 characters + InputFieldPlaceholder string `json:"input_field_placeholder,omitempty"` + // Optional. Use this parameter if you want to show the keyboard to specific users only. Targets: 1) users that are @mentioned in the text of the Message object; 2) if the bot's message is a reply to a message in the same chat and forum topic, sender of the original message.Example: A user requests to change the bot's language, bot replies to the request with a keyboard to select the new language. Other users in the group don't see the keyboard. + Selective *bool `json:"selective,omitempty"` +} + +// This object represents one button of the reply keyboard. At most one of the fields other than text, icon_custom_emoji_id, and style must be used to specify the type of the button. For simple text buttons, String can be used instead of this object to specify the button text. +type KeyboardButton struct { + // Text of the button. If none of the fields other than text, icon_custom_emoji_id, and style are used, it will be sent as a message when the button is pressed + Text string `json:"text"` + // Optional. Unique identifier of the custom emoji shown before the text of the button. Can only be used by bots that purchased additional usernames on Fragment or in the messages directly sent by the bot to private, group and supergroup chats if the owner of the bot has a Telegram Premium subscription. + IconCustomEmojiID string `json:"icon_custom_emoji_id,omitempty"` + // Optional. Style of the button. Must be one of “danger” (red), “success” (green) or “primary” (blue). If omitted, then an app-specific style is used. + Style string `json:"style,omitempty"` + // Optional. If specified, pressing the button will open a list of suitable users. Identifiers of selected users will be sent to the bot in a “users_shared” service message. Available in private chats only. + RequestUsers *KeyboardButtonRequestUsers `json:"request_users,omitempty"` + // Optional. If specified, pressing the button will open a list of suitable chats. Tapping on a chat will send its identifier to the bot in a “chat_shared” service message. Available in private chats only. + RequestChat *KeyboardButtonRequestChat `json:"request_chat,omitempty"` + // Optional. If specified, pressing the button will ask the user to create and share a bot that will be managed by the current bot. Available for bots that enabled management of other bots in the @BotFather Mini App. Available in private chats only. + RequestManagedBot *KeyboardButtonRequestManagedBot `json:"request_managed_bot,omitempty"` + // Optional. If True, the user's phone number will be sent as a contact when the button is pressed. Available in private chats only. + RequestContact *bool `json:"request_contact,omitempty"` + // Optional. If True, the user's current location will be sent when the button is pressed. Available in private chats only. + RequestLocation *bool `json:"request_location,omitempty"` + // Optional. If specified, the user will be asked to create a poll and send it to the bot when the button is pressed. Available in private chats only. + RequestPoll *KeyboardButtonPollType `json:"request_poll,omitempty"` + // Optional. If specified, the described Web App will be launched when the button is pressed. The Web App will be able to send a “web_app_data” service message. Available in private chats only. + WebApp *WebAppInfo `json:"web_app,omitempty"` +} + +// This object defines the criteria used to request suitable users. Information about the selected users will be shared with the bot when the corresponding button is pressed. More about requesting users » +type KeyboardButtonRequestUsers struct { + // Signed 32-bit identifier of the request that will be received back in the UsersShared object. Must be unique within the message + RequestID int64 `json:"request_id"` + // Optional. Pass True to request bots, pass False to request regular users. If not specified, no additional restrictions are applied. + UserIsBot *bool `json:"user_is_bot,omitempty"` + // Optional. Pass True to request premium users, pass False to request non-premium users. If not specified, no additional restrictions are applied. + UserIsPremium *bool `json:"user_is_premium,omitempty"` + // Optional. The maximum number of users to be selected; 1-10. Defaults to 1. + MaxQuantity *int64 `json:"max_quantity,omitempty"` + // Optional. Pass True to request the users' first and last names + RequestName *bool `json:"request_name,omitempty"` + // Optional. Pass True to request the users' usernames + RequestUsername *bool `json:"request_username,omitempty"` + // Optional. Pass True to request the users' photos + RequestPhoto *bool `json:"request_photo,omitempty"` +} + +// This object defines the criteria used to request a suitable chat. Information about the selected chat will be shared with the bot when the corresponding button is pressed. The bot will be granted requested rights in the chat if appropriate. More about requesting chats ». +type KeyboardButtonRequestChat struct { + // Signed 32-bit identifier of the request, which will be received back in the ChatShared object. Must be unique within the message + RequestID int64 `json:"request_id"` + // Pass True to request a channel chat, pass False to request a group or a supergroup chat. + ChatIsChannel bool `json:"chat_is_channel"` + // Optional. Pass True to request a forum supergroup, pass False to request a non-forum chat. If not specified, no additional restrictions are applied. + ChatIsForum *bool `json:"chat_is_forum,omitempty"` + // Optional. Pass True to request a supergroup or a channel with a username, pass False to request a chat without a username. If not specified, no additional restrictions are applied. + ChatHasUsername *bool `json:"chat_has_username,omitempty"` + // Optional. Pass True to request a chat owned by the user. Otherwise, no additional restrictions are applied. + ChatIsCreated *bool `json:"chat_is_created,omitempty"` + // Optional. A JSON-serialized object listing the required administrator rights of the user in the chat. The rights must be a superset of bot_administrator_rights. If not specified, no additional restrictions are applied. + UserAdministratorRights *ChatAdministratorRights `json:"user_administrator_rights,omitempty"` + // Optional. A JSON-serialized object listing the required administrator rights of the bot in the chat. The rights must be a subset of user_administrator_rights. If not specified, no additional restrictions are applied. + BotAdministratorRights *ChatAdministratorRights `json:"bot_administrator_rights,omitempty"` + // Optional. Pass True to request a chat with the bot as a member. Otherwise, no additional restrictions are applied. + BotIsMember *bool `json:"bot_is_member,omitempty"` + // Optional. Pass True to request the chat's title + RequestTitle *bool `json:"request_title,omitempty"` + // Optional. Pass True to request the chat's username + RequestUsername *bool `json:"request_username,omitempty"` + // Optional. Pass True to request the chat's photo + RequestPhoto *bool `json:"request_photo,omitempty"` +} + +// This object defines the parameters for the creation of a managed bot. Information about the created bot will be shared with the bot using the update managed_bot and a Message with the field managed_bot_created. +type KeyboardButtonRequestManagedBot struct { + // Signed 32-bit identifier of the request. Must be unique within the message + RequestID int64 `json:"request_id"` + // Optional. Suggested name for the bot + SuggestedName string `json:"suggested_name,omitempty"` + // Optional. Suggested username for the bot + SuggestedUsername string `json:"suggested_username,omitempty"` +} + +// This object represents type of a poll, which is allowed to be created and sent when the corresponding button is pressed. +type KeyboardButtonPollType struct { + // Optional. If quiz is passed, the user will be allowed to create only polls in the quiz mode. If regular is passed, only regular polls will be allowed. Otherwise, the user will be allowed to create a poll of any type. + Type string `json:"type,omitempty"` +} + +// Upon receiving a message with this object, Telegram clients will remove the current custom keyboard and display the default letter-keyboard. By default, custom keyboards are displayed until a new keyboard is sent by a bot. An exception is made for one-time keyboards that are hidden immediately after the user presses a button (see ReplyKeyboardMarkup). Not supported in channels and for messages sent on behalf of a business account. +type ReplyKeyboardRemove struct { + // Requests clients to remove the custom keyboard (user will not be able to summon this keyboard; if you want to hide the keyboard from sight but keep it accessible, use one_time_keyboard in ReplyKeyboardMarkup) + RemoveKeyboard bool `json:"remove_keyboard"` + // Optional. Use this parameter if you want to remove the keyboard for specific users only. Targets: 1) users that are @mentioned in the text of the Message object; 2) if the bot's message is a reply to a message in the same chat and forum topic, sender of the original message.Example: A user votes in a poll, bot returns confirmation message in reply to the vote and removes the keyboard for that user, while still showing the keyboard with poll options to users who haven't voted yet. + Selective *bool `json:"selective,omitempty"` +} + +// This object represents an inline keyboard that appears right next to the message it belongs to. +type InlineKeyboardMarkup struct { + // Array of button rows, each represented by an Array of InlineKeyboardButton objects + InlineKeyboard [][]InlineKeyboardButton `json:"inline_keyboard"` +} + +// This object represents one button of an inline keyboard. Exactly one of the fields other than text, icon_custom_emoji_id, and style must be used to specify the type of the button. +type InlineKeyboardButton struct { + // Label text on the button + Text string `json:"text"` + // Optional. Unique identifier of the custom emoji shown before the text of the button. Can only be used by bots that purchased additional usernames on Fragment or in the messages directly sent by the bot to private, group and supergroup chats if the owner of the bot has a Telegram Premium subscription. + IconCustomEmojiID string `json:"icon_custom_emoji_id,omitempty"` + // Optional. Style of the button. Must be one of “danger” (red), “success” (green) or “primary” (blue). If omitted, then an app-specific style is used. + Style string `json:"style,omitempty"` + // Optional. HTTP or tg:// URL to be opened when the button is pressed. Links tg://user?id= can be used to mention a user by their identifier without using a username, if this is allowed by their privacy settings. + URL string `json:"url,omitempty"` + // Optional. Data to be sent in a callback query to the bot when the button is pressed, 1-64 bytes + CallbackData string `json:"callback_data,omitempty"` + // Optional. Description of the Web App that will be launched when the user presses the button. The Web App will be able to send an arbitrary message on behalf of the user using the method answerWebAppQuery. Available only in private chats between a user and the bot. Not supported for messages sent on behalf of a business account. + WebApp *WebAppInfo `json:"web_app,omitempty"` + // Optional. An HTTPS URL used to automatically authorize the user. Can be used as a replacement for the Telegram Login Widget. + LoginURL *LoginUrl `json:"login_url,omitempty"` + // Optional. If set, pressing the button will prompt the user to select one of their chats, open that chat and insert the bot's username and the specified inline query in the input field. May be empty, in which case just the bot's username will be inserted. Not supported for messages sent in channel direct messages chats and on behalf of a business account. + SwitchInlineQuery string `json:"switch_inline_query,omitempty"` + // Optional. If set, pressing the button will insert the bot's username and the specified inline query in the current chat's input field. May be empty, in which case only the bot's username will be inserted.This offers a quick way for the user to open your bot in inline mode in the same chat - good for selecting something from multiple options. Not supported in channels and for messages sent in channel direct messages chats and on behalf of a business account. + SwitchInlineQueryCurrentChat string `json:"switch_inline_query_current_chat,omitempty"` + // Optional. If set, pressing the button will prompt the user to select one of their chats of the specified type, open that chat and insert the bot's username and the specified inline query in the input field. Not supported for messages sent in channel direct messages chats and on behalf of a business account. + SwitchInlineQueryChosenChat *SwitchInlineQueryChosenChat `json:"switch_inline_query_chosen_chat,omitempty"` + // Optional. Description of the button that copies the specified text to the clipboard. + CopyText *CopyTextButton `json:"copy_text,omitempty"` + // Optional. Description of the game that will be launched when the user presses the button.NOTE: This type of button must always be the first button in the first row. + CallbackGame *CallbackGame `json:"callback_game,omitempty"` + // Optional. Specify True, to send a Pay button. Substrings “” and “XTR” in the buttons's text will be replaced with a Telegram Star icon.NOTE: This type of button must always be the first button in the first row and can only be used in invoice messages. + Pay *bool `json:"pay,omitempty"` +} + +// This object represents a parameter of the inline keyboard button used to automatically authorize a user. Serves as a great replacement for the Telegram Login Widget when the user is coming from Telegram. All the user needs to do is tap/click a button and confirm that they want to log in: +// Telegram apps support these buttons as of version 5.7. +// Sample bot: @discussbot +type LoginUrl struct { + // An HTTPS URL to be opened with user authorization data added to the query string when the button is pressed. If the user refuses to provide authorization data, the original URL without information about the user will be opened. The data added is the same as described in Receiving authorization data.NOTE: You must always check the hash of the received data to verify the authentication and the integrity of the data as described in Checking authorization. + URL string `json:"url"` + // Optional. New text of the button in forwarded messages. + ForwardText string `json:"forward_text,omitempty"` + // Optional. Username of a bot, which will be used for user authorization. See Setting up a bot for more details. If not specified, the current bot's username will be assumed. The url's domain must be the same as the domain linked with the bot. See Linking your domain to the bot for more details. + BotUsername string `json:"bot_username,omitempty"` + // Optional. Pass True to request the permission for your bot to send messages to the user. + RequestWriteAccess *bool `json:"request_write_access,omitempty"` +} + +// This object represents an inline button that switches the current user to inline mode in a chosen chat, with an optional default inline query. +type SwitchInlineQueryChosenChat struct { + // Optional. The default inline query to be inserted in the input field. If left empty, only the bot's username will be inserted + Query string `json:"query,omitempty"` + // Optional. True, if private chats with users can be chosen + AllowUserChats *bool `json:"allow_user_chats,omitempty"` + // Optional. True, if private chats with bots can be chosen + AllowBotChats *bool `json:"allow_bot_chats,omitempty"` + // Optional. True, if group and supergroup chats can be chosen + AllowGroupChats *bool `json:"allow_group_chats,omitempty"` + // Optional. True, if channel chats can be chosen + AllowChannelChats *bool `json:"allow_channel_chats,omitempty"` +} + +// This object represents an inline keyboard button that copies specified text to the clipboard. +type CopyTextButton struct { + // The text to be copied to the clipboard; 1-256 characters + Text string `json:"text"` +} + +// This object represents an incoming callback query from a callback button in an inline keyboard. If the button that originated the query was attached to a message sent by the bot, the field message will be present. If the button was attached to a message sent via the bot (in inline mode), the field inline_message_id will be present. Exactly one of the fields data or game_short_name will be present. +// NOTE: After the user presses a callback button, Telegram clients will display a progress bar until you call answerCallbackQuery. It is, therefore, necessary to react by calling answerCallbackQuery even if no notification to the user is needed (e.g., without specifying any of the optional parameters). +type CallbackQuery struct { + // Unique identifier for this query + ID string `json:"id"` + // Sender + From User `json:"from"` + // Optional. Message sent by the bot with the callback button that originated the query + Message MaybeInaccessibleMessage `json:"message,omitempty"` + // Optional. Identifier of the message sent via the bot in inline mode, that originated the query. + InlineMessageID string `json:"inline_message_id,omitempty"` + // Global identifier, uniquely corresponding to the chat to which the message with the callback button was sent. Useful for high scores in games. + ChatInstance string `json:"chat_instance"` + // Optional. Data associated with the callback button. Be aware that the message originated the query can contain no callback buttons with this data. + Data string `json:"data,omitempty"` + // Optional. Short name of a Game to be returned, serves as the unique identifier for the game + GameShortName string `json:"game_short_name,omitempty"` +} + +// UnmarshalJSON decodes CallbackQuery by dispatching union-typed fields +// (Message) through their concrete UnmarshalXxx helpers. +func (m *CallbackQuery) UnmarshalJSON(data []byte) error { + type Alias CallbackQuery + aux := &struct { + Message json.RawMessage `json:"message,omitempty"` + *Alias + }{Alias: (*Alias)(m)} + if err := json.Unmarshal(data, aux); err != nil { + return err + } + + if len(aux.Message) > 0 && string(aux.Message) != "null" { + v, err := UnmarshalMaybeInaccessibleMessage(aux.Message) + if err != nil { + return fmt.Errorf("decoding message: %w", err) + } + m.Message = v + + } + + return nil +} + +// Upon receiving a message with this object, Telegram clients will display a reply interface to the user (act as if the user has selected the bot's message and tapped 'Reply'). This can be extremely useful if you want to create user-friendly step-by-step interfaces without having to sacrifice privacy mode. Not supported in channels and for messages sent on behalf of a user account. +// Example: A poll bot for groups runs in privacy mode (only receives commands, replies to its messages and mentions). There could be two ways to create a new poll: +// The last option is definitely more attractive. And if you use ForceReply in your bot's questions, it will receive the user's answers even if it only receives replies, commands and mentions - without any extra work for the user. +type ForceReply struct { + // Shows reply interface to the user, as if they manually selected the bot's message and tapped 'Reply' + ForceReply bool `json:"force_reply"` + // Optional. The placeholder to be shown in the input field when the reply is active; 1-64 characters + InputFieldPlaceholder string `json:"input_field_placeholder,omitempty"` + // Optional. Use this parameter if you want to force reply from specific users only. Targets: 1) users that are @mentioned in the text of the Message object; 2) if the bot's message is a reply to a message in the same chat and forum topic, sender of the original message. + Selective *bool `json:"selective,omitempty"` +} + +// This object represents a chat photo. +type ChatPhoto struct { + // File identifier of small (160x160) chat photo. This file_id can be used only for photo download and only for as long as the photo is not changed. + SmallFileID string `json:"small_file_id"` + // Unique file identifier of small (160x160) chat photo, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file. + SmallFileUniqueID string `json:"small_file_unique_id"` + // File identifier of big (640x640) chat photo. This file_id can be used only for photo download and only for as long as the photo is not changed. + BigFileID string `json:"big_file_id"` + // Unique file identifier of big (640x640) chat photo, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file. + BigFileUniqueID string `json:"big_file_unique_id"` +} + +// Represents an invite link for a chat. +type ChatInviteLink struct { + // The invite link. If the link was created by another chat administrator, then the second part of the link will be replaced with “…”. + InviteLink string `json:"invite_link"` + // Creator of the link + Creator User `json:"creator"` + // True, if users joining the chat via the link need to be approved by chat administrators + CreatesJoinRequest bool `json:"creates_join_request"` + // True, if the link is primary + IsPrimary bool `json:"is_primary"` + // True, if the link is revoked + IsRevoked bool `json:"is_revoked"` + // Optional. Invite link name + Name string `json:"name,omitempty"` + // Optional. Point in time (Unix timestamp) when the link will expire or has been expired + ExpireDate *int64 `json:"expire_date,omitempty"` + // Optional. The maximum number of users that can be members of the chat simultaneously after joining the chat via this invite link; 1-99999 + MemberLimit *int64 `json:"member_limit,omitempty"` + // Optional. Number of pending join requests created using this link + PendingJoinRequestCount *int64 `json:"pending_join_request_count,omitempty"` + // Optional. The number of seconds the subscription will be active for before the next payment + SubscriptionPeriod *int64 `json:"subscription_period,omitempty"` + // Optional. The amount of Telegram Stars a user must pay initially and after each subsequent subscription period to be a member of the chat using the link + SubscriptionPrice *int64 `json:"subscription_price,omitempty"` +} + +// Represents the rights of an administrator in a chat. +type ChatAdministratorRights struct { + // True, if the user's presence in the chat is hidden + IsAnonymous bool `json:"is_anonymous"` + // True, if the administrator can access the chat event log, get boost list, see hidden supergroup and channel members, report spam messages, ignore slow mode, and send messages to the chat without paying Telegram Stars. Implied by any other administrator privilege. + CanManageChat bool `json:"can_manage_chat"` + // True, if the administrator can delete messages of other users + CanDeleteMessages bool `json:"can_delete_messages"` + // True, if the administrator can manage video chats + CanManageVideoChats bool `json:"can_manage_video_chats"` + // True, if the administrator can restrict, ban or unban chat members, or access supergroup statistics + CanRestrictMembers bool `json:"can_restrict_members"` + // True, if the administrator can add new administrators with a subset of their own privileges or demote administrators that they have promoted, directly or indirectly (promoted by administrators that were appointed by the user) + CanPromoteMembers bool `json:"can_promote_members"` + // True, if the user is allowed to change the chat title, photo and other settings + CanChangeInfo bool `json:"can_change_info"` + // True, if the user is allowed to invite new users to the chat + CanInviteUsers bool `json:"can_invite_users"` + // True, if the administrator can post stories to the chat + CanPostStories bool `json:"can_post_stories"` + // True, if the administrator can edit stories posted by other users, post stories to the chat page, pin chat stories, and access the chat's story archive + CanEditStories bool `json:"can_edit_stories"` + // True, if the administrator can delete stories posted by other users + CanDeleteStories bool `json:"can_delete_stories"` + // Optional. True, if the administrator can post messages in the channel, approve suggested posts, or access channel statistics; for channels only + CanPostMessages *bool `json:"can_post_messages,omitempty"` + // Optional. True, if the administrator can edit messages of other users and can pin messages; for channels only + CanEditMessages *bool `json:"can_edit_messages,omitempty"` + // Optional. True, if the user is allowed to pin messages; for groups and supergroups only + CanPinMessages *bool `json:"can_pin_messages,omitempty"` + // Optional. True, if the user is allowed to create, rename, close, and reopen forum topics; for supergroups only + CanManageTopics *bool `json:"can_manage_topics,omitempty"` + // Optional. True, if the administrator can manage direct messages of the channel and decline suggested posts; for channels only + CanManageDirectMessages *bool `json:"can_manage_direct_messages,omitempty"` + // Optional. True, if the administrator can edit the tags of regular members; for groups and supergroups only. If omitted defaults to the value of can_pin_messages. + CanManageTags *bool `json:"can_manage_tags,omitempty"` +} + +// This object represents changes in the status of a chat member. +type ChatMemberUpdated struct { + // Chat the user belongs to + Chat Chat `json:"chat"` + // Performer of the action, which resulted in the change + From User `json:"from"` + // Date the change was done in Unix time + Date int64 `json:"date"` + // Previous information about the chat member + OldChatMember ChatMember `json:"old_chat_member"` + // New information about the chat member + NewChatMember ChatMember `json:"new_chat_member"` + // Optional. Chat invite link, which was used by the user to join the chat; for joining by invite link events only. + InviteLink *ChatInviteLink `json:"invite_link,omitempty"` + // Optional. True, if the user joined the chat after sending a direct join request without using an invite link and being approved by an administrator + ViaJoinRequest *bool `json:"via_join_request,omitempty"` + // Optional. True, if the user joined the chat via a chat folder invite link + ViaChatFolderInviteLink *bool `json:"via_chat_folder_invite_link,omitempty"` +} + +// UnmarshalJSON decodes ChatMemberUpdated by dispatching union-typed fields +// (OldChatMember, NewChatMember) through their concrete UnmarshalXxx helpers. +func (m *ChatMemberUpdated) UnmarshalJSON(data []byte) error { + type Alias ChatMemberUpdated + aux := &struct { + OldChatMember json.RawMessage `json:"old_chat_member,omitempty"` + NewChatMember json.RawMessage `json:"new_chat_member,omitempty"` + *Alias + }{Alias: (*Alias)(m)} + if err := json.Unmarshal(data, aux); err != nil { + return err + } + + if len(aux.OldChatMember) > 0 && string(aux.OldChatMember) != "null" { + v, err := UnmarshalChatMember(aux.OldChatMember) + if err != nil { + return fmt.Errorf("decoding old_chat_member: %w", err) + } + m.OldChatMember = v + + } + + if len(aux.NewChatMember) > 0 && string(aux.NewChatMember) != "null" { + v, err := UnmarshalChatMember(aux.NewChatMember) + if err != nil { + return fmt.Errorf("decoding new_chat_member: %w", err) + } + m.NewChatMember = v + + } + + return nil +} + +// ChatMember is a union type. The following concrete variants implement +// it: +// - ChatMemberOwner +// - ChatMemberAdministrator +// - ChatMemberMember +// - ChatMemberRestricted +// - ChatMemberLeft +// - ChatMemberBanned +// +// This object contains information about one member of a chat. Currently, the following 6 types of chat members are supported: +type ChatMember interface{ isChatMember() } + +// isChatMember is the marker method that makes ChatMemberOwner implement ChatMember. +func (*ChatMemberOwner) isChatMember() {} + +// isChatMember is the marker method that makes ChatMemberAdministrator implement ChatMember. +func (*ChatMemberAdministrator) isChatMember() {} + +// isChatMember is the marker method that makes ChatMemberMember implement ChatMember. +func (*ChatMemberMember) isChatMember() {} + +// isChatMember is the marker method that makes ChatMemberRestricted implement ChatMember. +func (*ChatMemberRestricted) isChatMember() {} + +// isChatMember is the marker method that makes ChatMemberLeft implement ChatMember. +func (*ChatMemberLeft) isChatMember() {} + +// isChatMember is the marker method that makes ChatMemberBanned implement ChatMember. +func (*ChatMemberBanned) isChatMember() {} + +// UnmarshalChatMember decodes a ChatMember from JSON by inspecting the +// "status" field and dispatching to the correct concrete type. +func UnmarshalChatMember(data []byte) (ChatMember, error) { + var probe struct { + V string `json:"status"` + } + if err := json.Unmarshal(data, &probe); err != nil { + return nil, err + } + var v ChatMember + switch probe.V { + case "administrator": + v = &ChatMemberAdministrator{} + case "creator": + v = &ChatMemberOwner{} + case "kicked": + v = &ChatMemberBanned{} + case "left": + v = &ChatMemberLeft{} + case "member": + v = &ChatMemberMember{} + case "restricted": + v = &ChatMemberRestricted{} + default: + return nil, fmt.Errorf("ChatMember: unknown status %q", probe.V) + } + if err := json.Unmarshal(data, v); err != nil { + return nil, err + } + return v, nil +} + +// Represents a chat member that owns the chat and has all administrator privileges. +type ChatMemberOwner struct { + // The member's status in the chat, always “creator” + Status string `json:"status"` + // Information about the user + User User `json:"user"` + // True, if the user's presence in the chat is hidden + IsAnonymous bool `json:"is_anonymous"` + // Optional. Custom title for this user + CustomTitle string `json:"custom_title,omitempty"` +} + +// Represents a chat member that has some additional privileges. +type ChatMemberAdministrator struct { + // The member's status in the chat, always “administrator” + Status string `json:"status"` + // Information about the user + User User `json:"user"` + // True, if the bot is allowed to edit administrator privileges of that user + CanBeEdited bool `json:"can_be_edited"` + // True, if the user's presence in the chat is hidden + IsAnonymous bool `json:"is_anonymous"` + // True, if the administrator can access the chat event log, get boost list, see hidden supergroup and channel members, report spam messages, ignore slow mode, and send messages to the chat without paying Telegram Stars. Implied by any other administrator privilege. + CanManageChat bool `json:"can_manage_chat"` + // True, if the administrator can delete messages of other users + CanDeleteMessages bool `json:"can_delete_messages"` + // True, if the administrator can manage video chats + CanManageVideoChats bool `json:"can_manage_video_chats"` + // True, if the administrator can restrict, ban or unban chat members, or access supergroup statistics + CanRestrictMembers bool `json:"can_restrict_members"` + // True, if the administrator can add new administrators with a subset of their own privileges or demote administrators that they have promoted, directly or indirectly (promoted by administrators that were appointed by the user) + CanPromoteMembers bool `json:"can_promote_members"` + // True, if the user is allowed to change the chat title, photo and other settings + CanChangeInfo bool `json:"can_change_info"` + // True, if the user is allowed to invite new users to the chat + CanInviteUsers bool `json:"can_invite_users"` + // True, if the administrator can post stories to the chat + CanPostStories bool `json:"can_post_stories"` + // True, if the administrator can edit stories posted by other users, post stories to the chat page, pin chat stories, and access the chat's story archive + CanEditStories bool `json:"can_edit_stories"` + // True, if the administrator can delete stories posted by other users + CanDeleteStories bool `json:"can_delete_stories"` + // Optional. True, if the administrator can post messages in the channel, approve suggested posts, or access channel statistics; for channels only + CanPostMessages *bool `json:"can_post_messages,omitempty"` + // Optional. True, if the administrator can edit messages of other users and can pin messages; for channels only + CanEditMessages *bool `json:"can_edit_messages,omitempty"` + // Optional. True, if the user is allowed to pin messages; for groups and supergroups only + CanPinMessages *bool `json:"can_pin_messages,omitempty"` + // Optional. True, if the user is allowed to create, rename, close, and reopen forum topics; for supergroups only + CanManageTopics *bool `json:"can_manage_topics,omitempty"` + // Optional. True, if the administrator can manage direct messages of the channel and decline suggested posts; for channels only + CanManageDirectMessages *bool `json:"can_manage_direct_messages,omitempty"` + // Optional. True, if the administrator can edit the tags of regular members; for groups and supergroups only. If omitted defaults to the value of can_pin_messages. + CanManageTags *bool `json:"can_manage_tags,omitempty"` + // Optional. Custom title for this user + CustomTitle string `json:"custom_title,omitempty"` +} + +// Represents a chat member that has no additional privileges or restrictions. +type ChatMemberMember struct { + // The member's status in the chat, always “member” + Status string `json:"status"` + // Optional. Tag of the member + Tag string `json:"tag,omitempty"` + // Information about the user + User User `json:"user"` + // Optional. Date when the user's subscription will expire; Unix time + UntilDate *int64 `json:"until_date,omitempty"` +} + +// Represents a chat member that is under certain restrictions in the chat. Supergroups only. +type ChatMemberRestricted struct { + // The member's status in the chat, always “restricted” + Status string `json:"status"` + // Optional. Tag of the member + Tag string `json:"tag,omitempty"` + // Information about the user + User User `json:"user"` + // True, if the user is a member of the chat at the moment of the request + IsMember bool `json:"is_member"` + // True, if the user is allowed to send text messages, contacts, giveaways, giveaway winners, invoices, locations and venues + CanSendMessages bool `json:"can_send_messages"` + // True, if the user is allowed to send audios + CanSendAudios bool `json:"can_send_audios"` + // True, if the user is allowed to send documents + CanSendDocuments bool `json:"can_send_documents"` + // True, if the user is allowed to send photos + CanSendPhotos bool `json:"can_send_photos"` + // True, if the user is allowed to send videos + CanSendVideos bool `json:"can_send_videos"` + // True, if the user is allowed to send video notes + CanSendVideoNotes bool `json:"can_send_video_notes"` + // True, if the user is allowed to send voice notes + CanSendVoiceNotes bool `json:"can_send_voice_notes"` + // True, if the user is allowed to send polls and checklists + CanSendPolls bool `json:"can_send_polls"` + // True, if the user is allowed to send animations, games, stickers and use inline bots + CanSendOtherMessages bool `json:"can_send_other_messages"` + // True, if the user is allowed to add web page previews to their messages + CanAddWebPagePreviews bool `json:"can_add_web_page_previews"` + // True, if the user is allowed to react to messages + CanReactToMessages bool `json:"can_react_to_messages"` + // True, if the user is allowed to edit their own tag + CanEditTag bool `json:"can_edit_tag"` + // True, if the user is allowed to change the chat title, photo and other settings + CanChangeInfo bool `json:"can_change_info"` + // True, if the user is allowed to invite new users to the chat + CanInviteUsers bool `json:"can_invite_users"` + // True, if the user is allowed to pin messages + CanPinMessages bool `json:"can_pin_messages"` + // True, if the user is allowed to create forum topics + CanManageTopics bool `json:"can_manage_topics"` + // Date when restrictions will be lifted for this user; Unix time. If 0, then the user is restricted forever + UntilDate int64 `json:"until_date"` +} + +// Represents a chat member that isn't currently a member of the chat, but may join it themselves. +type ChatMemberLeft struct { + // The member's status in the chat, always “left” + Status string `json:"status"` + // Information about the user + User User `json:"user"` +} + +// Represents a chat member that was banned in the chat and can't return to the chat or view chat messages. +type ChatMemberBanned struct { + // The member's status in the chat, always “kicked” + Status string `json:"status"` + // Information about the user + User User `json:"user"` + // Date when restrictions will be lifted for this user; Unix time. If 0, then the user is banned forever + UntilDate int64 `json:"until_date"` +} + +// Represents a join request sent to a chat. +type ChatJoinRequest struct { + // Chat to which the request was sent + Chat Chat `json:"chat"` + // User that sent the join request + From User `json:"from"` + // Identifier of a private chat with the user who sent the join request. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a 64-bit integer or double-precision float type are safe for storing this identifier. The bot can use this identifier for 5 minutes to send messages until the join request is processed, assuming no other administrator contacted the user. + UserChatID int64 `json:"user_chat_id"` + // Date the request was sent in Unix time + Date int64 `json:"date"` + // Optional. Bio of the user. + Bio string `json:"bio,omitempty"` + // Optional. Chat invite link that was used by the user to send the join request + InviteLink *ChatInviteLink `json:"invite_link,omitempty"` +} + +// Describes actions that a non-administrator user is allowed to take in a chat. +type ChatPermissions struct { + // Optional. True, if the user is allowed to send text messages, contacts, giveaways, giveaway winners, invoices, locations and venues + CanSendMessages *bool `json:"can_send_messages,omitempty"` + // Optional. True, if the user is allowed to send audios + CanSendAudios *bool `json:"can_send_audios,omitempty"` + // Optional. True, if the user is allowed to send documents + CanSendDocuments *bool `json:"can_send_documents,omitempty"` + // Optional. True, if the user is allowed to send photos + CanSendPhotos *bool `json:"can_send_photos,omitempty"` + // Optional. True, if the user is allowed to send videos + CanSendVideos *bool `json:"can_send_videos,omitempty"` + // Optional. True, if the user is allowed to send video notes + CanSendVideoNotes *bool `json:"can_send_video_notes,omitempty"` + // Optional. True, if the user is allowed to send voice notes + CanSendVoiceNotes *bool `json:"can_send_voice_notes,omitempty"` + // Optional. True, if the user is allowed to send polls and checklists + CanSendPolls *bool `json:"can_send_polls,omitempty"` + // Optional. True, if the user is allowed to send animations, games, stickers and use inline bots + CanSendOtherMessages *bool `json:"can_send_other_messages,omitempty"` + // Optional. True, if the user is allowed to add web page previews to their messages + CanAddWebPagePreviews *bool `json:"can_add_web_page_previews,omitempty"` + // Optional. True, if the user is allowed to react to messages. If omitted, defaults to the value of can_send_messages. + CanReactToMessages *bool `json:"can_react_to_messages,omitempty"` + // Optional. True, if the user is allowed to edit their own tag. If omitted, defaults to the value of can_pin_messages. + CanEditTag *bool `json:"can_edit_tag,omitempty"` + // Optional. True, if the user is allowed to change the chat title, photo and other settings. Ignored in public supergroups + CanChangeInfo *bool `json:"can_change_info,omitempty"` + // Optional. True, if the user is allowed to invite new users to the chat + CanInviteUsers *bool `json:"can_invite_users,omitempty"` + // Optional. True, if the user is allowed to pin messages. Ignored in public supergroups + CanPinMessages *bool `json:"can_pin_messages,omitempty"` + // Optional. True, if the user is allowed to create forum topics. If omitted defaults to the value of can_pin_messages + CanManageTopics *bool `json:"can_manage_topics,omitempty"` +} + +// Describes the birthdate of a user. +type Birthdate struct { + // Day of the user's birth; 1-31 + Day int64 `json:"day"` + // Month of the user's birth; 1-12 + Month int64 `json:"month"` + // Optional. Year of the user's birth + Year *int64 `json:"year,omitempty"` +} + +// Contains information about the start page settings of a Telegram Business account. +type BusinessIntro struct { + // Optional. Title text of the business intro + Title string `json:"title,omitempty"` + // Optional. Message text of the business intro + Message string `json:"message,omitempty"` + // Optional. Sticker of the business intro + Sticker *Sticker `json:"sticker,omitempty"` +} + +// Contains information about the location of a Telegram Business account. +type BusinessLocation struct { + // Address of the business + Address string `json:"address"` + // Optional. Location of the business + Location *Location `json:"location,omitempty"` +} + +// Describes an interval of time during which a business is open. +type BusinessOpeningHoursInterval struct { + // The minute's sequence number in a week, starting on Monday, marking the start of the time interval during which the business is open; 0 - 7 * 24 * 60 + OpeningMinute int64 `json:"opening_minute"` + // The minute's sequence number in a week, starting on Monday, marking the end of the time interval during which the business is open; 0 - 8 * 24 * 60 + ClosingMinute int64 `json:"closing_minute"` +} + +// Describes the opening hours of a business. +type BusinessOpeningHours struct { + // Unique name of the time zone for which the opening hours are defined + TimeZoneName string `json:"time_zone_name"` + // List of time intervals describing business opening hours + OpeningHours []BusinessOpeningHoursInterval `json:"opening_hours"` +} + +// This object describes the rating of a user based on their Telegram Star spendings. +type UserRating struct { + // Current level of the user, indicating their reliability when purchasing digital goods and services. A higher level suggests a more trustworthy customer; a negative level is likely reason for concern. + Level int64 `json:"level"` + // Numerical value of the user's rating; the higher the rating, the better + Rating int64 `json:"rating"` + // The rating value required to get the current level + CurrentLevelRating int64 `json:"current_level_rating"` + // Optional. The rating value required to get to the next level; omitted if the maximum level was reached + NextLevelRating *int64 `json:"next_level_rating,omitempty"` +} + +// Describes the position of a clickable area within a story. +type StoryAreaPosition struct { + // The abscissa of the area's center, as a percentage of the media width + XPercentage float64 `json:"x_percentage"` + // The ordinate of the area's center, as a percentage of the media height + YPercentage float64 `json:"y_percentage"` + // The width of the area's rectangle, as a percentage of the media width + WidthPercentage float64 `json:"width_percentage"` + // The height of the area's rectangle, as a percentage of the media height + HeightPercentage float64 `json:"height_percentage"` + // The clockwise rotation angle of the rectangle, in degrees; 0-360 + RotationAngle float64 `json:"rotation_angle"` + // The radius of the rectangle corner rounding, as a percentage of the media width + CornerRadiusPercentage float64 `json:"corner_radius_percentage"` +} + +// Describes the physical address of a location. +type LocationAddress struct { + // The two-letter ISO 3166-1 alpha-2 country code of the country where the location is located + CountryCode string `json:"country_code"` + // Optional. State of the location + State string `json:"state,omitempty"` + // Optional. City of the location + City string `json:"city,omitempty"` + // Optional. Street address of the location + Street string `json:"street,omitempty"` +} + +// StoryAreaType is a union type. The following concrete variants implement +// it: +// - StoryAreaTypeLocation +// - StoryAreaTypeSuggestedReaction +// - StoryAreaTypeLink +// - StoryAreaTypeWeather +// - StoryAreaTypeUniqueGift +// +// Describes the type of a clickable area on a story. Currently, it can be one of +type StoryAreaType interface{ isStoryAreaType() } + +// isStoryAreaType is the marker method that makes StoryAreaTypeLocation implement StoryAreaType. +func (*StoryAreaTypeLocation) isStoryAreaType() {} + +// isStoryAreaType is the marker method that makes StoryAreaTypeSuggestedReaction implement StoryAreaType. +func (*StoryAreaTypeSuggestedReaction) isStoryAreaType() {} + +// isStoryAreaType is the marker method that makes StoryAreaTypeLink implement StoryAreaType. +func (*StoryAreaTypeLink) isStoryAreaType() {} + +// isStoryAreaType is the marker method that makes StoryAreaTypeWeather implement StoryAreaType. +func (*StoryAreaTypeWeather) isStoryAreaType() {} + +// isStoryAreaType is the marker method that makes StoryAreaTypeUniqueGift implement StoryAreaType. +func (*StoryAreaTypeUniqueGift) isStoryAreaType() {} + +// UnmarshalStoryAreaType decodes a StoryAreaType from JSON by inspecting the +// "type" field and dispatching to the correct concrete type. +func UnmarshalStoryAreaType(data []byte) (StoryAreaType, error) { + var probe struct { + V string `json:"type"` + } + if err := json.Unmarshal(data, &probe); err != nil { + return nil, err + } + var v StoryAreaType + switch probe.V { + case "link": + v = &StoryAreaTypeLink{} + case "location": + v = &StoryAreaTypeLocation{} + case "suggested_reaction": + v = &StoryAreaTypeSuggestedReaction{} + case "unique_gift": + v = &StoryAreaTypeUniqueGift{} + case "weather": + v = &StoryAreaTypeWeather{} + default: + return nil, fmt.Errorf("StoryAreaType: unknown type %q", probe.V) + } + if err := json.Unmarshal(data, v); err != nil { + return nil, err + } + return v, nil +} + +// Describes a story area pointing to a location. Currently, a story can have up to 10 location areas. +type StoryAreaTypeLocation struct { + // Type of the area, always “location” + Type string `json:"type"` + // Location latitude in degrees + Latitude float64 `json:"latitude"` + // Location longitude in degrees + Longitude float64 `json:"longitude"` + // Optional. Address of the location + Address *LocationAddress `json:"address,omitempty"` +} + +// Describes a story area pointing to a suggested reaction. Currently, a story can have up to 5 suggested reaction areas. +type StoryAreaTypeSuggestedReaction struct { + // Type of the area, always “suggested_reaction” + Type string `json:"type"` + // Type of the reaction + ReactionType ReactionType `json:"reaction_type"` + // Optional. Pass True if the reaction area has a dark background + IsDark *bool `json:"is_dark,omitempty"` + // Optional. Pass True if reaction area corner is flipped + IsFlipped *bool `json:"is_flipped,omitempty"` +} + +// UnmarshalJSON decodes StoryAreaTypeSuggestedReaction by dispatching union-typed fields +// (ReactionType) through their concrete UnmarshalXxx helpers. +func (m *StoryAreaTypeSuggestedReaction) UnmarshalJSON(data []byte) error { + type Alias StoryAreaTypeSuggestedReaction + aux := &struct { + ReactionType json.RawMessage `json:"reaction_type,omitempty"` + *Alias + }{Alias: (*Alias)(m)} + if err := json.Unmarshal(data, aux); err != nil { + return err + } + + if len(aux.ReactionType) > 0 && string(aux.ReactionType) != "null" { + v, err := UnmarshalReactionType(aux.ReactionType) + if err != nil { + return fmt.Errorf("decoding reaction_type: %w", err) + } + m.ReactionType = v + + } + + return nil +} + +// Describes a story area pointing to an HTTP or tg:// link. Currently, a story can have up to 3 link areas. +type StoryAreaTypeLink struct { + // Type of the area, always “link” + Type string `json:"type"` + // HTTP or tg:// URL to be opened when the area is clicked + URL string `json:"url"` +} + +// Describes a story area containing weather information. Currently, a story can have up to 3 weather areas. +type StoryAreaTypeWeather struct { + // Type of the area, always “weather” + Type string `json:"type"` + // Temperature, in degree Celsius + Temperature float64 `json:"temperature"` + // Emoji representing the weather + Emoji string `json:"emoji"` + // A color of the area background in the ARGB format + BackgroundColor int64 `json:"background_color"` +} + +// Describes a story area pointing to a unique gift. Currently, a story can have at most 1 unique gift area. +type StoryAreaTypeUniqueGift struct { + // Type of the area, always “unique_gift” + Type string `json:"type"` + // Unique name of the gift + Name string `json:"name"` +} + +// Describes a clickable area on a story media. +type StoryArea struct { + // Position of the area + Position StoryAreaPosition `json:"position"` + // Type of the area + Type StoryAreaType `json:"type"` +} + +// UnmarshalJSON decodes StoryArea by dispatching union-typed fields +// (Type) through their concrete UnmarshalXxx helpers. +func (m *StoryArea) UnmarshalJSON(data []byte) error { + type Alias StoryArea + aux := &struct { + Type json.RawMessage `json:"type,omitempty"` + *Alias + }{Alias: (*Alias)(m)} + if err := json.Unmarshal(data, aux); err != nil { + return err + } + + if len(aux.Type) > 0 && string(aux.Type) != "null" { + v, err := UnmarshalStoryAreaType(aux.Type) + if err != nil { + return fmt.Errorf("decoding type: %w", err) + } + m.Type = v + + } + + return nil +} + +// Represents a location to which a chat is connected. +type ChatLocation struct { + // The location to which the supergroup is connected. Can't be a live location. + Location Location `json:"location"` + // Location address; 1-64 characters, as defined by the chat owner + Address string `json:"address"` +} + +// ReactionType is a union type. The following concrete variants implement +// it: +// - ReactionTypeEmoji +// - ReactionTypeCustomEmoji +// - ReactionTypePaid +// +// This object describes the type of a reaction. Currently, it can be one of +type ReactionType interface{ isReactionType() } + +// isReactionType is the marker method that makes ReactionTypeEmoji implement ReactionType. +func (*ReactionTypeEmoji) isReactionType() {} + +// isReactionType is the marker method that makes ReactionTypeCustomEmoji implement ReactionType. +func (*ReactionTypeCustomEmoji) isReactionType() {} + +// isReactionType is the marker method that makes ReactionTypePaid implement ReactionType. +func (*ReactionTypePaid) isReactionType() {} + +// UnmarshalReactionType decodes a ReactionType from JSON by inspecting the +// "type" field and dispatching to the correct concrete type. +func UnmarshalReactionType(data []byte) (ReactionType, error) { + var probe struct { + V string `json:"type"` + } + if err := json.Unmarshal(data, &probe); err != nil { + return nil, err + } + var v ReactionType + switch probe.V { + case "custom_emoji": + v = &ReactionTypeCustomEmoji{} + case "emoji": + v = &ReactionTypeEmoji{} + case "paid": + v = &ReactionTypePaid{} + default: + return nil, fmt.Errorf("ReactionType: unknown type %q", probe.V) + } + if err := json.Unmarshal(data, v); err != nil { + return nil, err + } + return v, nil +} + +// The reaction is based on an emoji. +type ReactionTypeEmoji struct { + // Type of the reaction, always “emoji” + Type string `json:"type"` + // Reaction emoji. Currently, it can be one of "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "" + Emoji string `json:"emoji"` +} + +// The reaction is based on a custom emoji. +type ReactionTypeCustomEmoji struct { + // Type of the reaction, always “custom_emoji” + Type string `json:"type"` + // Custom emoji identifier + CustomEmojiID string `json:"custom_emoji_id"` +} + +// The reaction is paid. +type ReactionTypePaid struct { + // Type of the reaction, always “paid” + Type string `json:"type"` +} + +// Represents a reaction added to a message along with the number of times it was added. +type ReactionCount struct { + // Type of the reaction + Type ReactionType `json:"type"` + // Number of times the reaction was added + TotalCount int64 `json:"total_count"` +} + +// UnmarshalJSON decodes ReactionCount by dispatching union-typed fields +// (Type) through their concrete UnmarshalXxx helpers. +func (m *ReactionCount) UnmarshalJSON(data []byte) error { + type Alias ReactionCount + aux := &struct { + Type json.RawMessage `json:"type,omitempty"` + *Alias + }{Alias: (*Alias)(m)} + if err := json.Unmarshal(data, aux); err != nil { + return err + } + + if len(aux.Type) > 0 && string(aux.Type) != "null" { + v, err := UnmarshalReactionType(aux.Type) + if err != nil { + return fmt.Errorf("decoding type: %w", err) + } + m.Type = v + + } + + return nil +} + +// This object represents a change of a reaction on a message performed by a user. +type MessageReactionUpdated struct { + // The chat containing the message the user reacted to + Chat Chat `json:"chat"` + // Unique identifier of the message inside the chat + MessageID int64 `json:"message_id"` + // Optional. The user that changed the reaction, if the user isn't anonymous + User *User `json:"user,omitempty"` + // Optional. The chat on behalf of which the reaction was changed, if the user is anonymous + ActorChat *Chat `json:"actor_chat,omitempty"` + // Date of the change in Unix time + Date int64 `json:"date"` + // Previous list of reaction types that were set by the user + OldReaction []ReactionType `json:"old_reaction"` + // New list of reaction types that have been set by the user + NewReaction []ReactionType `json:"new_reaction"` +} + +// UnmarshalJSON decodes MessageReactionUpdated by dispatching union-typed fields +// (OldReaction, NewReaction) through their concrete UnmarshalXxx helpers. +func (m *MessageReactionUpdated) UnmarshalJSON(data []byte) error { + type Alias MessageReactionUpdated + aux := &struct { + OldReaction json.RawMessage `json:"old_reaction,omitempty"` + NewReaction json.RawMessage `json:"new_reaction,omitempty"` + *Alias + }{Alias: (*Alias)(m)} + if err := json.Unmarshal(data, aux); err != nil { + return err + } + + if len(aux.OldReaction) > 0 && string(aux.OldReaction) != "null" { + var raws []json.RawMessage + if err := json.Unmarshal(aux.OldReaction, &raws); err != nil { + return fmt.Errorf("decoding old_reaction: %w", err) + } + decoded := make([]ReactionType, 0, len(raws)) + for i, r := range raws { + v, err := UnmarshalReactionType(r) + if err != nil { + return fmt.Errorf("decoding old_reaction[%d]: %w", i, err) + } + decoded = append(decoded, v) + } + m.OldReaction = decoded + + } + + if len(aux.NewReaction) > 0 && string(aux.NewReaction) != "null" { + var raws []json.RawMessage + if err := json.Unmarshal(aux.NewReaction, &raws); err != nil { + return fmt.Errorf("decoding new_reaction: %w", err) + } + decoded := make([]ReactionType, 0, len(raws)) + for i, r := range raws { + v, err := UnmarshalReactionType(r) + if err != nil { + return fmt.Errorf("decoding new_reaction[%d]: %w", i, err) + } + decoded = append(decoded, v) + } + m.NewReaction = decoded + + } + + return nil +} + +// This object represents reaction changes on a message with anonymous reactions. +type MessageReactionCountUpdated struct { + // The chat containing the message + Chat Chat `json:"chat"` + // Unique message identifier inside the chat + MessageID int64 `json:"message_id"` + // Date of the change in Unix time + Date int64 `json:"date"` + // List of reactions that are present on the message + Reactions []ReactionCount `json:"reactions"` +} + +// This object represents a forum topic. +type ForumTopic struct { + // Unique identifier of the forum topic + MessageThreadID int64 `json:"message_thread_id"` + // Name of the topic + Name string `json:"name"` + // Color of the topic icon in RGB format + IconColor int64 `json:"icon_color"` + // Optional. Unique identifier of the custom emoji shown as the topic icon + IconCustomEmojiID string `json:"icon_custom_emoji_id,omitempty"` + // Optional. True, if the name of the topic wasn't specified explicitly by its creator and likely needs to be changed by the bot + IsNameImplicit *bool `json:"is_name_implicit,omitempty"` +} + +// This object describes the background of a gift. +type GiftBackground struct { + // Center color of the background in RGB format + CenterColor int64 `json:"center_color"` + // Edge color of the background in RGB format + EdgeColor int64 `json:"edge_color"` + // Text color of the background in RGB format + TextColor int64 `json:"text_color"` +} + +// This object represents a gift that can be sent by the bot. +type Gift struct { + // Unique identifier of the gift + ID string `json:"id"` + // The sticker that represents the gift + Sticker Sticker `json:"sticker"` + // The number of Telegram Stars that must be paid to send the sticker + StarCount int64 `json:"star_count"` + // Optional. The number of Telegram Stars that must be paid to upgrade the gift to a unique one + UpgradeStarCount *int64 `json:"upgrade_star_count,omitempty"` + // Optional. True, if the gift can only be purchased by Telegram Premium subscribers + IsPremium *bool `json:"is_premium,omitempty"` + // Optional. True, if the gift can be used (after being upgraded) to customize a user's appearance + HasColors *bool `json:"has_colors,omitempty"` + // Optional. The total number of gifts of this type that can be sent by all users; for limited gifts only + TotalCount *int64 `json:"total_count,omitempty"` + // Optional. The number of remaining gifts of this type that can be sent by all users; for limited gifts only + RemainingCount *int64 `json:"remaining_count,omitempty"` + // Optional. The total number of gifts of this type that can be sent by the bot; for limited gifts only + PersonalTotalCount *int64 `json:"personal_total_count,omitempty"` + // Optional. The number of remaining gifts of this type that can be sent by the bot; for limited gifts only + PersonalRemainingCount *int64 `json:"personal_remaining_count,omitempty"` + // Optional. Background of the gift + Background *GiftBackground `json:"background,omitempty"` + // Optional. The total number of different unique gifts that can be obtained by upgrading the gift + UniqueGiftVariantCount *int64 `json:"unique_gift_variant_count,omitempty"` + // Optional. Information about the chat that published the gift + PublisherChat *Chat `json:"publisher_chat,omitempty"` +} + +// This object represent a list of gifts. +type Gifts struct { + // The list of gifts + Gifts []Gift `json:"gifts"` +} + +// This object describes the model of a unique gift. +type UniqueGiftModel struct { + // Name of the model + Name string `json:"name"` + // The sticker that represents the unique gift + Sticker Sticker `json:"sticker"` + // The number of unique gifts that receive this model for every 1000 gift upgrades. Always 0 for crafted gifts. + RarityPerMille int64 `json:"rarity_per_mille"` + // Optional. Rarity of the model if it is a crafted model. Currently, can be “uncommon”, “rare”, “epic”, or “legendary”. + Rarity string `json:"rarity,omitempty"` +} + +// This object describes the symbol shown on the pattern of a unique gift. +type UniqueGiftSymbol struct { + // Name of the symbol + Name string `json:"name"` + // The sticker that represents the unique gift + Sticker Sticker `json:"sticker"` + // The number of unique gifts that receive this model for every 1000 gifts upgraded + RarityPerMille int64 `json:"rarity_per_mille"` +} + +// This object describes the colors of the backdrop of a unique gift. +type UniqueGiftBackdropColors struct { + // The color in the center of the backdrop in RGB format + CenterColor int64 `json:"center_color"` + // The color on the edges of the backdrop in RGB format + EdgeColor int64 `json:"edge_color"` + // The color to be applied to the symbol in RGB format + SymbolColor int64 `json:"symbol_color"` + // The color for the text on the backdrop in RGB format + TextColor int64 `json:"text_color"` +} + +// This object describes the backdrop of a unique gift. +type UniqueGiftBackdrop struct { + // Name of the backdrop + Name string `json:"name"` + // Colors of the backdrop + Colors UniqueGiftBackdropColors `json:"colors"` + // The number of unique gifts that receive this backdrop for every 1000 gifts upgraded + RarityPerMille int64 `json:"rarity_per_mille"` +} + +// This object contains information about the color scheme for a user's name, message replies and link previews based on a unique gift. +type UniqueGiftColors struct { + // Custom emoji identifier of the unique gift's model + ModelCustomEmojiID string `json:"model_custom_emoji_id"` + // Custom emoji identifier of the unique gift's symbol + SymbolCustomEmojiID string `json:"symbol_custom_emoji_id"` + // Main color used in light themes; RGB format + LightThemeMainColor int64 `json:"light_theme_main_color"` + // List of 1-3 additional colors used in light themes; RGB format + LightThemeOtherColors []int64 `json:"light_theme_other_colors"` + // Main color used in dark themes; RGB format + DarkThemeMainColor int64 `json:"dark_theme_main_color"` + // List of 1-3 additional colors used in dark themes; RGB format + DarkThemeOtherColors []int64 `json:"dark_theme_other_colors"` +} + +// This object describes a unique gift that was upgraded from a regular gift. +type UniqueGift struct { + // Identifier of the regular gift from which the gift was upgraded + GiftID string `json:"gift_id"` + // Human-readable name of the regular gift from which this unique gift was upgraded + BaseName string `json:"base_name"` + // Unique name of the gift. This name can be used in https://t.me/nft/... links and story areas + Name string `json:"name"` + // Unique number of the upgraded gift among gifts upgraded from the same regular gift + Number int64 `json:"number"` + // Model of the gift + Model UniqueGiftModel `json:"model"` + // Symbol of the gift + Symbol UniqueGiftSymbol `json:"symbol"` + // Backdrop of the gift + Backdrop UniqueGiftBackdrop `json:"backdrop"` + // Optional. True, if the original regular gift was exclusively purchaseable by Telegram Premium subscribers + IsPremium *bool `json:"is_premium,omitempty"` + // Optional. True, if the gift was used to craft another gift and isn't available anymore + IsBurned *bool `json:"is_burned,omitempty"` + // Optional. True, if the gift is assigned from the TON blockchain and can't be resold or transferred in Telegram + IsFromBlockchain *bool `json:"is_from_blockchain,omitempty"` + // Optional. The color scheme that can be used by the gift's owner for the chat's name, replies to messages and link previews; for business account gifts and gifts that are currently on sale only + Colors *UniqueGiftColors `json:"colors,omitempty"` + // Optional. Information about the chat that published the gift + PublisherChat *Chat `json:"publisher_chat,omitempty"` +} + +// Describes a service message about a regular gift that was sent or received. +type GiftInfo struct { + // Information about the gift + Gift Gift `json:"gift"` + // Optional. Unique identifier of the received gift for the bot; only present for gifts received on behalf of business accounts + OwnedGiftID string `json:"owned_gift_id,omitempty"` + // Optional. Number of Telegram Stars that can be claimed by the receiver by converting the gift; omitted if conversion to Telegram Stars is impossible + ConvertStarCount *int64 `json:"convert_star_count,omitempty"` + // Optional. Number of Telegram Stars that were prepaid for the ability to upgrade the gift + PrepaidUpgradeStarCount *int64 `json:"prepaid_upgrade_star_count,omitempty"` + // Optional. True, if the gift's upgrade was purchased after the gift was sent + IsUpgradeSeparate *bool `json:"is_upgrade_separate,omitempty"` + // Optional. True, if the gift can be upgraded to a unique gift + CanBeUpgraded *bool `json:"can_be_upgraded,omitempty"` + // Optional. Text of the message that was added to the gift + Text string `json:"text,omitempty"` + // Optional. Special entities that appear in the text + Entities []MessageEntity `json:"entities,omitempty"` + // Optional. True, if the sender and gift text are shown only to the gift receiver; otherwise, everyone will be able to see them + IsPrivate *bool `json:"is_private,omitempty"` + // Optional. Unique number reserved for this gift when upgraded. See the number field in UniqueGift + UniqueGiftNumber *int64 `json:"unique_gift_number,omitempty"` +} + +// Describes a service message about a unique gift that was sent or received. +type UniqueGiftInfo struct { + // Information about the gift + Gift UniqueGift `json:"gift"` + // Origin of the gift. Currently, either “upgrade” for gifts upgraded from regular gifts, “transfer” for gifts transferred from other users or channels, “resale” for gifts bought from other users, “gifted_upgrade” for upgrades purchased after the gift was sent, or “offer” for gifts bought or sold through gift purchase offers + Origin string `json:"origin"` + // Optional. For gifts bought from other users, the currency in which the payment for the gift was done. Currently, one of “XTR” for Telegram Stars or “TON” for toncoins. + LastResaleCurrency string `json:"last_resale_currency,omitempty"` + // Optional. For gifts bought from other users, the price paid for the gift in either Telegram Stars or nanotoncoins + LastResaleAmount *int64 `json:"last_resale_amount,omitempty"` + // Optional. Unique identifier of the received gift for the bot; only present for gifts received on behalf of business accounts + OwnedGiftID string `json:"owned_gift_id,omitempty"` + // Optional. Number of Telegram Stars that must be paid to transfer the gift; omitted if the bot cannot transfer the gift + TransferStarCount *int64 `json:"transfer_star_count,omitempty"` + // Optional. Point in time (Unix timestamp) when the gift can be transferred. If it is in the past, then the gift can be transferred now + NextTransferDate *int64 `json:"next_transfer_date,omitempty"` +} + +// OwnedGift is a union type. The following concrete variants implement +// it: +// - OwnedGiftRegular +// - OwnedGiftUnique +// +// This object describes a gift received and owned by a user or a chat. Currently, it can be one of +type OwnedGift interface{ isOwnedGift() } + +// isOwnedGift is the marker method that makes OwnedGiftRegular implement OwnedGift. +func (*OwnedGiftRegular) isOwnedGift() {} + +// isOwnedGift is the marker method that makes OwnedGiftUnique implement OwnedGift. +func (*OwnedGiftUnique) isOwnedGift() {} + +// UnmarshalOwnedGift decodes a OwnedGift from JSON by inspecting the +// "type" field and dispatching to the correct concrete type. +func UnmarshalOwnedGift(data []byte) (OwnedGift, error) { + var probe struct { + V string `json:"type"` + } + if err := json.Unmarshal(data, &probe); err != nil { + return nil, err + } + var v OwnedGift + switch probe.V { + case "regular": + v = &OwnedGiftRegular{} + case "unique": + v = &OwnedGiftUnique{} + default: + return nil, fmt.Errorf("OwnedGift: unknown type %q", probe.V) + } + if err := json.Unmarshal(data, v); err != nil { + return nil, err + } + return v, nil +} + +// Describes a regular gift owned by a user or a chat. +type OwnedGiftRegular struct { + // Type of the gift, always “regular” + Type string `json:"type"` + // Information about the regular gift + Gift Gift `json:"gift"` + // Optional. Unique identifier of the gift for the bot; for gifts received on behalf of business accounts only + OwnedGiftID string `json:"owned_gift_id,omitempty"` + // Optional. Sender of the gift if it is a known user + SenderUser *User `json:"sender_user,omitempty"` + // Date the gift was sent in Unix time + SendDate int64 `json:"send_date"` + // Optional. Text of the message that was added to the gift + Text string `json:"text,omitempty"` + // Optional. Special entities that appear in the text + Entities []MessageEntity `json:"entities,omitempty"` + // Optional. True, if the sender and gift text are shown only to the gift receiver; otherwise, everyone will be able to see them + IsPrivate *bool `json:"is_private,omitempty"` + // Optional. True, if the gift is displayed on the account's profile page; for gifts received on behalf of business accounts only + IsSaved *bool `json:"is_saved,omitempty"` + // Optional. True, if the gift can be upgraded to a unique gift; for gifts received on behalf of business accounts only + CanBeUpgraded *bool `json:"can_be_upgraded,omitempty"` + // Optional. True, if the gift was refunded and isn't available anymore + WasRefunded *bool `json:"was_refunded,omitempty"` + // Optional. Number of Telegram Stars that can be claimed by the receiver instead of the gift; omitted if the gift cannot be converted to Telegram Stars; for gifts received on behalf of business accounts only + ConvertStarCount *int64 `json:"convert_star_count,omitempty"` + // Optional. Number of Telegram Stars that were paid for the ability to upgrade the gift + PrepaidUpgradeStarCount *int64 `json:"prepaid_upgrade_star_count,omitempty"` + // Optional. True, if the gift's upgrade was purchased after the gift was sent; for gifts received on behalf of business accounts only + IsUpgradeSeparate *bool `json:"is_upgrade_separate,omitempty"` + // Optional. Unique number reserved for this gift when upgraded. See the number field in UniqueGift + UniqueGiftNumber *int64 `json:"unique_gift_number,omitempty"` +} + +// Describes a unique gift received and owned by a user or a chat. +type OwnedGiftUnique struct { + // Type of the gift, always “unique” + Type string `json:"type"` + // Information about the unique gift + Gift UniqueGift `json:"gift"` + // Optional. Unique identifier of the received gift for the bot; for gifts received on behalf of business accounts only + OwnedGiftID string `json:"owned_gift_id,omitempty"` + // Optional. Sender of the gift if it is a known user + SenderUser *User `json:"sender_user,omitempty"` + // Date the gift was sent in Unix time + SendDate int64 `json:"send_date"` + // Optional. True, if the gift is displayed on the account's profile page; for gifts received on behalf of business accounts only + IsSaved *bool `json:"is_saved,omitempty"` + // Optional. True, if the gift can be transferred to another owner; for gifts received on behalf of business accounts only + CanBeTransferred *bool `json:"can_be_transferred,omitempty"` + // Optional. Number of Telegram Stars that must be paid to transfer the gift; omitted if the bot cannot transfer the gift + TransferStarCount *int64 `json:"transfer_star_count,omitempty"` + // Optional. Point in time (Unix timestamp) when the gift can be transferred. If it is in the past, then the gift can be transferred now + NextTransferDate *int64 `json:"next_transfer_date,omitempty"` +} + +// Contains the list of gifts received and owned by a user or a chat. +type OwnedGifts struct { + // The total number of gifts owned by the user or the chat + TotalCount int64 `json:"total_count"` + // The list of gifts + Gifts []OwnedGift `json:"gifts"` + // Optional. Offset for the next request. If empty, then there are no more results + NextOffset string `json:"next_offset,omitempty"` +} + +// UnmarshalJSON decodes OwnedGifts by dispatching union-typed fields +// (Gifts) through their concrete UnmarshalXxx helpers. +func (m *OwnedGifts) UnmarshalJSON(data []byte) error { + type Alias OwnedGifts + aux := &struct { + Gifts json.RawMessage `json:"gifts,omitempty"` + *Alias + }{Alias: (*Alias)(m)} + if err := json.Unmarshal(data, aux); err != nil { + return err + } + + if len(aux.Gifts) > 0 && string(aux.Gifts) != "null" { + var raws []json.RawMessage + if err := json.Unmarshal(aux.Gifts, &raws); err != nil { + return fmt.Errorf("decoding gifts: %w", err) + } + decoded := make([]OwnedGift, 0, len(raws)) + for i, r := range raws { + v, err := UnmarshalOwnedGift(r) + if err != nil { + return fmt.Errorf("decoding gifts[%d]: %w", i, err) + } + decoded = append(decoded, v) + } + m.Gifts = decoded + + } + + return nil +} + +// This object describes the access settings of a bot. +type BotAccessSettings struct { + // True, if only selected users can access the bot. The bot's owner can always access it. + IsAccessRestricted bool `json:"is_access_restricted"` + // Optional. The list of other users who have access to the bot if the access is restricted + AddedUsers []User `json:"added_users,omitempty"` +} + +// This object describes the types of gifts that can be gifted to a user or a chat. +type AcceptedGiftTypes struct { + // True, if unlimited regular gifts are accepted + UnlimitedGifts bool `json:"unlimited_gifts"` + // True, if limited regular gifts are accepted + LimitedGifts bool `json:"limited_gifts"` + // True, if unique gifts or gifts that can be upgraded to unique for free are accepted + UniqueGifts bool `json:"unique_gifts"` + // True, if a Telegram Premium subscription is accepted + PremiumSubscription bool `json:"premium_subscription"` + // True, if transfers of unique gifts from channels are accepted + GiftsFromChannels bool `json:"gifts_from_channels"` +} + +// Describes an amount of Telegram Stars. +type StarAmount struct { + // Integer amount of Telegram Stars, rounded to 0; can be negative + Amount int64 `json:"amount"` + // Optional. The number of 1/1000000000 shares of Telegram Stars; from -999999999 to 999999999; can be negative if and only if amount is non-positive + NanostarAmount *int64 `json:"nanostar_amount,omitempty"` +} + +// This object represents a bot command. +type BotCommand struct { + // Text of the command; 1-32 characters. Can contain only lowercase English letters, digits and underscores. + Command string `json:"command"` + // Description of the command; 1-256 characters. + Description string `json:"description"` +} + +// BotCommandScope is a union type. The following concrete variants implement +// it: +// - BotCommandScopeDefault +// - BotCommandScopeAllPrivateChats +// - BotCommandScopeAllGroupChats +// - BotCommandScopeAllChatAdministrators +// - BotCommandScopeChat +// - BotCommandScopeChatAdministrators +// - BotCommandScopeChatMember +// +// This object represents the scope to which bot commands are applied. Currently, the following 7 scopes are supported: +type BotCommandScope interface{ isBotCommandScope() } + +// isBotCommandScope is the marker method that makes BotCommandScopeDefault implement BotCommandScope. +func (*BotCommandScopeDefault) isBotCommandScope() {} + +// isBotCommandScope is the marker method that makes BotCommandScopeAllPrivateChats implement BotCommandScope. +func (*BotCommandScopeAllPrivateChats) isBotCommandScope() {} + +// isBotCommandScope is the marker method that makes BotCommandScopeAllGroupChats implement BotCommandScope. +func (*BotCommandScopeAllGroupChats) isBotCommandScope() {} + +// isBotCommandScope is the marker method that makes BotCommandScopeAllChatAdministrators implement BotCommandScope. +func (*BotCommandScopeAllChatAdministrators) isBotCommandScope() {} + +// isBotCommandScope is the marker method that makes BotCommandScopeChat implement BotCommandScope. +func (*BotCommandScopeChat) isBotCommandScope() {} + +// isBotCommandScope is the marker method that makes BotCommandScopeChatAdministrators implement BotCommandScope. +func (*BotCommandScopeChatAdministrators) isBotCommandScope() {} + +// isBotCommandScope is the marker method that makes BotCommandScopeChatMember implement BotCommandScope. +func (*BotCommandScopeChatMember) isBotCommandScope() {} + +// Represents the default scope of bot commands. Default commands are used if no commands with a narrower scope are specified for the user. +type BotCommandScopeDefault struct { + // Scope type, must be default + Type string `json:"type"` +} + +// Represents the scope of bot commands, covering all private chats. +type BotCommandScopeAllPrivateChats struct { + // Scope type, must be all_private_chats + Type string `json:"type"` +} + +// Represents the scope of bot commands, covering all group and supergroup chats. +type BotCommandScopeAllGroupChats struct { + // Scope type, must be all_group_chats + Type string `json:"type"` +} + +// Represents the scope of bot commands, covering all group and supergroup chat administrators. +type BotCommandScopeAllChatAdministrators struct { + // Scope type, must be all_chat_administrators + Type string `json:"type"` +} + +// Represents the scope of bot commands, covering a specific chat. +type BotCommandScopeChat struct { + // Scope type, must be chat + Type string `json:"type"` + // Unique identifier for the target chat or username of the target supergroup in the format @username. Channel direct messages chats and channel chats aren't supported. + ChatID ChatID `json:"chat_id"` +} + +// Represents the scope of bot commands, covering all administrators of a specific group or supergroup chat. +type BotCommandScopeChatAdministrators struct { + // Scope type, must be chat_administrators + Type string `json:"type"` + // Unique identifier for the target chat or username of the target supergroup in the format @username. Channel direct messages chats and channel chats aren't supported. + ChatID ChatID `json:"chat_id"` +} + +// Represents the scope of bot commands, covering a specific member of a group or supergroup chat. +type BotCommandScopeChatMember struct { + // Scope type, must be chat_member + Type string `json:"type"` + // Unique identifier for the target chat or username of the target supergroup in the format @username. Channel direct messages chats and channel chats aren't supported. + ChatID ChatID `json:"chat_id"` + // Unique identifier of the target user + UserID int64 `json:"user_id"` +} + +// This object represents the bot's name. +type BotName struct { + // The bot's name + Name string `json:"name"` +} + +// This object represents the bot's description. +type BotDescription struct { + // The bot's description + Description string `json:"description"` +} + +// This object represents the bot's short description. +type BotShortDescription struct { + // The bot's short description + ShortDescription string `json:"short_description"` +} + +// MenuButton is a union type. The following concrete variants implement +// it: +// - MenuButtonCommands +// - MenuButtonWebApp +// - MenuButtonDefault +// +// This object describes the bot's menu button in a private chat. It should be one of +// If a menu button other than MenuButtonDefault is set for a private chat, then it is applied in the chat. Otherwise the default menu button is applied. By default, the menu button opens the list of bot commands. +type MenuButton interface{ isMenuButton() } + +// isMenuButton is the marker method that makes MenuButtonCommands implement MenuButton. +func (*MenuButtonCommands) isMenuButton() {} + +// isMenuButton is the marker method that makes MenuButtonWebApp implement MenuButton. +func (*MenuButtonWebApp) isMenuButton() {} + +// isMenuButton is the marker method that makes MenuButtonDefault implement MenuButton. +func (*MenuButtonDefault) isMenuButton() {} + +// UnmarshalMenuButton decodes a MenuButton from JSON by inspecting the +// "type" field and dispatching to the correct concrete type. +func UnmarshalMenuButton(data []byte) (MenuButton, error) { + var probe struct { + V string `json:"type"` + } + if err := json.Unmarshal(data, &probe); err != nil { + return nil, err + } + var v MenuButton + switch probe.V { + case "commands": + v = &MenuButtonCommands{} + case "default": + v = &MenuButtonDefault{} + case "web_app": + v = &MenuButtonWebApp{} + default: + return nil, fmt.Errorf("MenuButton: unknown type %q", probe.V) + } + if err := json.Unmarshal(data, v); err != nil { + return nil, err + } + return v, nil +} + +// Represents a menu button, which opens the bot's list of commands. +type MenuButtonCommands struct { + // Type of the button, must be commands + Type string `json:"type"` +} + +// Represents a menu button, which launches a Web App. +type MenuButtonWebApp struct { + // Type of the button, must be web_app + Type string `json:"type"` + // Text on the button + Text string `json:"text"` + // Description of the Web App that will be launched when the user presses the button. The Web App will be able to send an arbitrary message on behalf of the user using the method answerWebAppQuery. Alternatively, a t.me link to a Web App of the bot can be specified in the object instead of the Web App's URL, in which case the Web App will be opened as if the user pressed the link. + WebApp WebAppInfo `json:"web_app"` +} + +// Describes that no specific value for the menu button was set. +type MenuButtonDefault struct { + // Type of the button, must be default + Type string `json:"type"` +} + +// ChatBoostSource is a union type. The following concrete variants implement +// it: +// - ChatBoostSourcePremium +// - ChatBoostSourceGiftCode +// - ChatBoostSourceGiveaway +// +// This object describes the source of a chat boost. It can be one of +type ChatBoostSource interface{ isChatBoostSource() } + +// isChatBoostSource is the marker method that makes ChatBoostSourcePremium implement ChatBoostSource. +func (*ChatBoostSourcePremium) isChatBoostSource() {} + +// isChatBoostSource is the marker method that makes ChatBoostSourceGiftCode implement ChatBoostSource. +func (*ChatBoostSourceGiftCode) isChatBoostSource() {} + +// isChatBoostSource is the marker method that makes ChatBoostSourceGiveaway implement ChatBoostSource. +func (*ChatBoostSourceGiveaway) isChatBoostSource() {} + +// UnmarshalChatBoostSource decodes a ChatBoostSource from JSON by inspecting the +// "source" field and dispatching to the correct concrete type. +func UnmarshalChatBoostSource(data []byte) (ChatBoostSource, error) { + var probe struct { + V string `json:"source"` + } + if err := json.Unmarshal(data, &probe); err != nil { + return nil, err + } + var v ChatBoostSource + switch probe.V { + case "gift_code": + v = &ChatBoostSourceGiftCode{} + case "giveaway": + v = &ChatBoostSourceGiveaway{} + case "premium": + v = &ChatBoostSourcePremium{} + default: + return nil, fmt.Errorf("ChatBoostSource: unknown source %q", probe.V) + } + if err := json.Unmarshal(data, v); err != nil { + return nil, err + } + return v, nil +} + +// The boost was obtained by subscribing to Telegram Premium or by gifting a Telegram Premium subscription to another user. +type ChatBoostSourcePremium struct { + // Source of the boost, always “premium” + Source string `json:"source"` + // User that boosted the chat + User User `json:"user"` +} + +// The boost was obtained by the creation of Telegram Premium gift codes to boost a chat. Each such code boosts the chat 4 times for the duration of the corresponding Telegram Premium subscription. +type ChatBoostSourceGiftCode struct { + // Source of the boost, always “gift_code” + Source string `json:"source"` + // User for which the gift code was created + User User `json:"user"` +} + +// The boost was obtained by the creation of a Telegram Premium or a Telegram Star giveaway. This boosts the chat 4 times for the duration of the corresponding Telegram Premium subscription for Telegram Premium giveaways and prize_star_count / 500 times for one year for Telegram Star giveaways. +type ChatBoostSourceGiveaway struct { + // Source of the boost, always “giveaway” + Source string `json:"source"` + // Identifier of a message in the chat with the giveaway; the message could have been deleted already. May be 0 if the message isn't sent yet. + GiveawayMessageID int64 `json:"giveaway_message_id"` + // Optional. User that won the prize in the giveaway if any; for Telegram Premium giveaways only + User *User `json:"user,omitempty"` + // Optional. The number of Telegram Stars to be split between giveaway winners; for Telegram Star giveaways only + PrizeStarCount *int64 `json:"prize_star_count,omitempty"` + // Optional. True, if the giveaway was completed, but there was no user to win the prize + IsUnclaimed *bool `json:"is_unclaimed,omitempty"` +} + +// This object contains information about a chat boost. +type ChatBoost struct { + // Unique identifier of the boost + BoostID string `json:"boost_id"` + // Point in time (Unix timestamp) when the chat was boosted + AddDate int64 `json:"add_date"` + // Point in time (Unix timestamp) when the boost will automatically expire, unless the booster's Telegram Premium subscription is prolonged + ExpirationDate int64 `json:"expiration_date"` + // Source of the added boost + Source ChatBoostSource `json:"source"` +} + +// UnmarshalJSON decodes ChatBoost by dispatching union-typed fields +// (Source) through their concrete UnmarshalXxx helpers. +func (m *ChatBoost) UnmarshalJSON(data []byte) error { + type Alias ChatBoost + aux := &struct { + Source json.RawMessage `json:"source,omitempty"` + *Alias + }{Alias: (*Alias)(m)} + if err := json.Unmarshal(data, aux); err != nil { + return err + } + + if len(aux.Source) > 0 && string(aux.Source) != "null" { + v, err := UnmarshalChatBoostSource(aux.Source) + if err != nil { + return fmt.Errorf("decoding source: %w", err) + } + m.Source = v + + } + + return nil +} + +// This object represents a boost added to a chat or changed. +type ChatBoostUpdated struct { + // Chat which was boosted + Chat Chat `json:"chat"` + // Information about the chat boost + Boost ChatBoost `json:"boost"` +} + +// This object represents a boost removed from a chat. +type ChatBoostRemoved struct { + // Chat which was boosted + Chat Chat `json:"chat"` + // Unique identifier of the boost + BoostID string `json:"boost_id"` + // Point in time (Unix timestamp) when the boost was removed + RemoveDate int64 `json:"remove_date"` + // Source of the removed boost + Source ChatBoostSource `json:"source"` +} + +// UnmarshalJSON decodes ChatBoostRemoved by dispatching union-typed fields +// (Source) through their concrete UnmarshalXxx helpers. +func (m *ChatBoostRemoved) UnmarshalJSON(data []byte) error { + type Alias ChatBoostRemoved + aux := &struct { + Source json.RawMessage `json:"source,omitempty"` + *Alias + }{Alias: (*Alias)(m)} + if err := json.Unmarshal(data, aux); err != nil { + return err + } + + if len(aux.Source) > 0 && string(aux.Source) != "null" { + v, err := UnmarshalChatBoostSource(aux.Source) + if err != nil { + return fmt.Errorf("decoding source: %w", err) + } + m.Source = v + + } + + return nil +} + +// Describes a service message about the chat owner leaving the chat. +type ChatOwnerLeft struct { + // Optional. The user who will become the new owner of the chat if the previous owner does not return to the chat + NewOwner *User `json:"new_owner,omitempty"` +} + +// Describes a service message about an ownership change in the chat. +type ChatOwnerChanged struct { + // The new owner of the chat + NewOwner User `json:"new_owner"` +} + +// This object represents a list of boosts added to a chat by a user. +type UserChatBoosts struct { + // The list of boosts added to the chat by the user + Boosts []ChatBoost `json:"boosts"` +} + +// Represents the rights of a business bot. +type BusinessBotRights struct { + // Optional. True, if the bot can send and edit messages in the private chats that had incoming messages in the last 24 hours + CanReply *bool `json:"can_reply,omitempty"` + // Optional. True, if the bot can mark incoming private messages as read + CanReadMessages *bool `json:"can_read_messages,omitempty"` + // Optional. True, if the bot can delete messages sent by the bot + CanDeleteSentMessages *bool `json:"can_delete_sent_messages,omitempty"` + // Optional. True, if the bot can delete all private messages in managed chats + CanDeleteAllMessages *bool `json:"can_delete_all_messages,omitempty"` + // Optional. True, if the bot can edit the first and last name of the business account + CanEditName *bool `json:"can_edit_name,omitempty"` + // Optional. True, if the bot can edit the bio of the business account + CanEditBio *bool `json:"can_edit_bio,omitempty"` + // Optional. True, if the bot can edit the profile photo of the business account + CanEditProfilePhoto *bool `json:"can_edit_profile_photo,omitempty"` + // Optional. True, if the bot can edit the username of the business account + CanEditUsername *bool `json:"can_edit_username,omitempty"` + // Optional. True, if the bot can change the privacy settings pertaining to gifts for the business account + CanChangeGiftSettings *bool `json:"can_change_gift_settings,omitempty"` + // Optional. True, if the bot can view gifts and the amount of Telegram Stars owned by the business account + CanViewGiftsAndStars *bool `json:"can_view_gifts_and_stars,omitempty"` + // Optional. True, if the bot can convert regular gifts owned by the business account to Telegram Stars + CanConvertGiftsToStars *bool `json:"can_convert_gifts_to_stars,omitempty"` + // Optional. True, if the bot can transfer and upgrade gifts owned by the business account + CanTransferAndUpgradeGifts *bool `json:"can_transfer_and_upgrade_gifts,omitempty"` + // Optional. True, if the bot can transfer Telegram Stars received by the business account to its own account, or use them to upgrade and transfer gifts + CanTransferStars *bool `json:"can_transfer_stars,omitempty"` + // Optional. True, if the bot can post, edit and delete stories on behalf of the business account + CanManageStories *bool `json:"can_manage_stories,omitempty"` +} + +// Describes the connection of the bot with a business account. +type BusinessConnection struct { + // Unique identifier of the business connection + ID string `json:"id"` + // Business account user that created the business connection + User User `json:"user"` + // Identifier of a private chat with the user who created the business connection. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a 64-bit integer or double-precision float type are safe for storing this identifier. + UserChatID int64 `json:"user_chat_id"` + // Date the connection was established in Unix time + Date int64 `json:"date"` + // Optional. Rights of the business bot + Rights *BusinessBotRights `json:"rights,omitempty"` + // True, if the connection is active + IsEnabled bool `json:"is_enabled"` +} + +// This object is received when messages are deleted from a connected business account. +type BusinessMessagesDeleted struct { + // Unique identifier of the business connection + BusinessConnectionID string `json:"business_connection_id"` + // Information about a chat in the business account. The bot may not have access to the chat or the corresponding user. + Chat Chat `json:"chat"` + // The list of identifiers of deleted messages in the chat of the business account + MessageIds []int64 `json:"message_ids"` +} + +// Describes an inline message sent by a Web App on behalf of a user. +type SentWebAppMessage struct { + // Optional. Identifier of the sent inline message. Available only if there is an inline keyboard attached to the message. + InlineMessageID string `json:"inline_message_id,omitempty"` +} + +// Describes an inline message sent by a guest bot. +type SentGuestMessage struct { + // Identifier of the sent inline message + InlineMessageID string `json:"inline_message_id"` +} + +// Describes an inline message to be sent by a user of a Mini App. +type PreparedInlineMessage struct { + // Unique identifier of the prepared message + ID string `json:"id"` + // Expiration date of the prepared message, in Unix time. Expired prepared messages can no longer be used + ExpirationDate int64 `json:"expiration_date"` +} + +// Describes a keyboard button to be used by a user of a Mini App. +type PreparedKeyboardButton struct { + // Unique identifier of the keyboard button + ID string `json:"id"` +} + +// InputMedia is a union type. The following concrete variants implement +// it: +// - InputMediaAnimation +// - InputMediaAudio +// - InputMediaDocument +// - InputMediaLivePhoto +// - InputMediaPhoto +// - InputMediaVideo +// +// This object represents the content of a media message to be sent. It should be one of +type InputMedia interface{ isInputMedia() } + +// isInputMedia is the marker method that makes InputMediaAnimation implement InputMedia. +func (*InputMediaAnimation) isInputMedia() {} + +// isInputMedia is the marker method that makes InputMediaAudio implement InputMedia. +func (*InputMediaAudio) isInputMedia() {} + +// isInputMedia is the marker method that makes InputMediaDocument implement InputMedia. +func (*InputMediaDocument) isInputMedia() {} + +// isInputMedia is the marker method that makes InputMediaLivePhoto implement InputMedia. +func (*InputMediaLivePhoto) isInputMedia() {} + +// isInputMedia is the marker method that makes InputMediaPhoto implement InputMedia. +func (*InputMediaPhoto) isInputMedia() {} + +// isInputMedia is the marker method that makes InputMediaVideo implement InputMedia. +func (*InputMediaVideo) isInputMedia() {} + +// Represents an animation file (GIF or H.264/MPEG-4 AVC video without sound) to be sent. +type InputMediaAnimation struct { + // Type of the result, must be animation + Type string `json:"type"` + // File to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet, or pass “attach://” to upload a new one using multipart/form-data under name. More information on Sending Files » + Media string `json:"media"` + // Optional. Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://” if the thumbnail was uploaded using multipart/form-data under . More information on Sending Files » + Thumbnail string `json:"thumbnail,omitempty"` + // Optional. Caption of the animation to be sent, 0-1024 characters after entities parsing + Caption string `json:"caption,omitempty"` + // Optional. Mode for parsing entities in the animation caption. See formatting options for more details. + ParseMode string `json:"parse_mode,omitempty"` + // Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode + CaptionEntities []MessageEntity `json:"caption_entities,omitempty"` + // Optional. Pass True, if the caption must be shown above the message media + ShowCaptionAboveMedia *bool `json:"show_caption_above_media,omitempty"` + // Optional. Animation width + Width *int64 `json:"width,omitempty"` + // Optional. Animation height + Height *int64 `json:"height,omitempty"` + // Optional. Animation duration in seconds + Duration *int64 `json:"duration,omitempty"` + // Optional. Pass True if the animation needs to be covered with a spoiler animation + HasSpoiler *bool `json:"has_spoiler,omitempty"` +} + +// Represents an audio file to be treated as music to be sent. +type InputMediaAudio struct { + // Type of the result, must be audio + Type string `json:"type"` + // File to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet, or pass “attach://” to upload a new one using multipart/form-data under name. More information on Sending Files » + Media string `json:"media"` + // Optional. Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://” if the thumbnail was uploaded using multipart/form-data under . More information on Sending Files » + Thumbnail string `json:"thumbnail,omitempty"` + // Optional. Caption of the audio to be sent, 0-1024 characters after entities parsing + Caption string `json:"caption,omitempty"` + // Optional. Mode for parsing entities in the audio caption. See formatting options for more details. + ParseMode string `json:"parse_mode,omitempty"` + // Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode + CaptionEntities []MessageEntity `json:"caption_entities,omitempty"` + // Optional. Duration of the audio in seconds + Duration *int64 `json:"duration,omitempty"` + // Optional. Performer of the audio + Performer string `json:"performer,omitempty"` + // Optional. Title of the audio + Title string `json:"title,omitempty"` +} + +// Represents a general file to be sent. +type InputMediaDocument struct { + // Type of the result, must be document + Type string `json:"type"` + // File to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet, or pass “attach://” to upload a new one using multipart/form-data under name. More information on Sending Files » + Media string `json:"media"` + // Optional. Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://” if the thumbnail was uploaded using multipart/form-data under . More information on Sending Files » + Thumbnail string `json:"thumbnail,omitempty"` + // Optional. Caption of the document to be sent, 0-1024 characters after entities parsing + Caption string `json:"caption,omitempty"` + // Optional. Mode for parsing entities in the document caption. See formatting options for more details. + ParseMode string `json:"parse_mode,omitempty"` + // Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode + CaptionEntities []MessageEntity `json:"caption_entities,omitempty"` + // Optional. Disables automatic server-side content type detection for files uploaded using multipart/form-data. Always True, if the document is sent as part of an album. + DisableContentTypeDetection *bool `json:"disable_content_type_detection,omitempty"` +} + +// Represents a live photo to be sent. +type InputMediaLivePhoto struct { + // Type of the result, must be live_photo + Type string `json:"type"` + // Video of the live photo to send. Pass a file_id to send a file that exists on the Telegram servers (recommended) or pass “attach://” to upload a new one using multipart/form-data under name. More information on Sending Files ». Sending live photos by a URL is currently unsupported. + Media string `json:"media"` + // The static photo to send. Pass a file_id to send a file that exists on the Telegram servers (recommended) or pass “attach://” to upload a new one using multipart/form-data under name. More information on Sending Files ». Sending live photos by a URL is currently unsupported. + Photo string `json:"photo"` + // Optional. Caption of the live photo to be sent, 0-1024 characters after entities parsing + Caption string `json:"caption,omitempty"` + // Optional. Mode for parsing entities in the live photo caption. See formatting options for more details. + ParseMode string `json:"parse_mode,omitempty"` + // Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode + CaptionEntities []MessageEntity `json:"caption_entities,omitempty"` + // Optional. Pass True, if the caption must be shown above the message media + ShowCaptionAboveMedia *bool `json:"show_caption_above_media,omitempty"` + // Optional. Pass True if the live photo needs to be covered with a spoiler animation + HasSpoiler *bool `json:"has_spoiler,omitempty"` +} + +// Represents a location to be sent. +type InputMediaLocation struct { + // Type of the result, must be location + Type string `json:"type"` + // Latitude of the location + Latitude float64 `json:"latitude"` + // Longitude of the location + Longitude float64 `json:"longitude"` + // Optional. The radius of uncertainty for the location, measured in meters; 0-1500 + HorizontalAccuracy *float64 `json:"horizontal_accuracy,omitempty"` +} + +// Represents a photo to be sent. +type InputMediaPhoto struct { + // Type of the result, must be photo + Type string `json:"type"` + // File to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet, or pass “attach://” to upload a new one using multipart/form-data under name. More information on Sending Files » + Media string `json:"media"` + // Optional. Caption of the photo to be sent, 0-1024 characters after entities parsing + Caption string `json:"caption,omitempty"` + // Optional. Mode for parsing entities in the photo caption. See formatting options for more details. + ParseMode string `json:"parse_mode,omitempty"` + // Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode + CaptionEntities []MessageEntity `json:"caption_entities,omitempty"` + // Optional. Pass True, if the caption must be shown above the message media + ShowCaptionAboveMedia *bool `json:"show_caption_above_media,omitempty"` + // Optional. Pass True if the photo needs to be covered with a spoiler animation + HasSpoiler *bool `json:"has_spoiler,omitempty"` +} + +// Represents a sticker file to be sent. +type InputMediaSticker struct { + // Type of the result, must be sticker + Type string `json:"type"` + // File to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for Telegram to get a .WEBP sticker from the Internet, or pass “attach://” to upload a new .WEBP, .TGS, or .WEBM sticker using multipart/form-data under name. More information on Sending Files » + Media string `json:"media"` + // Optional. Emoji associated with the sticker; only for just uploaded stickers + Emoji string `json:"emoji,omitempty"` +} + +// Represents a venue to be sent. +type InputMediaVenue struct { + // Type of the result, must be venue + Type string `json:"type"` + // Latitude of the location + Latitude float64 `json:"latitude"` + // Longitude of the location + Longitude float64 `json:"longitude"` + // Name of the venue + Title string `json:"title"` + // Address of the venue + Address string `json:"address"` + // Optional. Foursquare identifier of the venue + FoursquareID string `json:"foursquare_id,omitempty"` + // Optional. Foursquare type of the venue, if known. (For example, “arts_entertainment/default”, “arts_entertainment/aquarium” or “food/icecream”.) + FoursquareType string `json:"foursquare_type,omitempty"` + // Optional. Google Places identifier of the venue + GooglePlaceID string `json:"google_place_id,omitempty"` + // Optional. Google Places type of the venue. (See supported types.) + GooglePlaceType string `json:"google_place_type,omitempty"` +} + +// Represents a video to be sent. +type InputMediaVideo struct { + // Type of the result, must be video + Type string `json:"type"` + // File to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet, or pass “attach://” to upload a new one using multipart/form-data under name. More information on Sending Files » + Media string `json:"media"` + // Optional. Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://” if the thumbnail was uploaded using multipart/form-data under . More information on Sending Files » + Thumbnail string `json:"thumbnail,omitempty"` + // Optional. Cover for the video in the message. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet, or pass “attach://” to upload a new one using multipart/form-data under name. More information on Sending Files » + Cover string `json:"cover,omitempty"` + // Optional. Start timestamp for the video in the message + StartTimestamp *int64 `json:"start_timestamp,omitempty"` + // Optional. Caption of the video to be sent, 0-1024 characters after entities parsing + Caption string `json:"caption,omitempty"` + // Optional. Mode for parsing entities in the video caption. See formatting options for more details. + ParseMode string `json:"parse_mode,omitempty"` + // Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode + CaptionEntities []MessageEntity `json:"caption_entities,omitempty"` + // Optional. Pass True, if the caption must be shown above the message media + ShowCaptionAboveMedia *bool `json:"show_caption_above_media,omitempty"` + // Optional. Video width + Width *int64 `json:"width,omitempty"` + // Optional. Video height + Height *int64 `json:"height,omitempty"` + // Optional. Video duration in seconds + Duration *int64 `json:"duration,omitempty"` + // Optional. Pass True if the uploaded video is suitable for streaming + SupportsStreaming *bool `json:"supports_streaming,omitempty"` + // Optional. Pass True if the video needs to be covered with a spoiler animation + HasSpoiler *bool `json:"has_spoiler,omitempty"` +} + +// InputPaidMedia is a union type. The following concrete variants implement +// it: +// - InputPaidMediaLivePhoto +// - InputPaidMediaPhoto +// - InputPaidMediaVideo +// +// This object describes the paid media to be sent. Currently, it can be one of +type InputPaidMedia interface{ isInputPaidMedia() } + +// isInputPaidMedia is the marker method that makes InputPaidMediaLivePhoto implement InputPaidMedia. +func (*InputPaidMediaLivePhoto) isInputPaidMedia() {} + +// isInputPaidMedia is the marker method that makes InputPaidMediaPhoto implement InputPaidMedia. +func (*InputPaidMediaPhoto) isInputPaidMedia() {} + +// isInputPaidMedia is the marker method that makes InputPaidMediaVideo implement InputPaidMedia. +func (*InputPaidMediaVideo) isInputPaidMedia() {} + +// The paid media to send is a live photo. +type InputPaidMediaLivePhoto struct { + // Type of the media, must be live_photo + Type string `json:"type"` + // Video of the live photo to send. Pass a file_id to send a file that exists on the Telegram servers (recommended) or pass “attach://” to upload a new one using multipart/form-data under name. More information on Sending Files ». Sending live photos by a URL is currently unsupported. + Media string `json:"media"` + // The static photo to send. Pass a file_id to send a file that exists on the Telegram servers (recommended) or pass “attach://” to upload a new one using multipart/form-data under name. More information on Sending Files ». Sending live photos by a URL is currently unsupported. + Photo string `json:"photo"` +} + +// The paid media to send is a photo. +type InputPaidMediaPhoto struct { + // Type of the media, must be photo + Type string `json:"type"` + // File to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet, or pass “attach://” to upload a new one using multipart/form-data under name. More information on Sending Files » + Media string `json:"media"` +} + +// The paid media to send is a video. +type InputPaidMediaVideo struct { + // Type of the media, must be video + Type string `json:"type"` + // File to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet, or pass “attach://” to upload a new one using multipart/form-data under name. More information on Sending Files » + Media string `json:"media"` + // Optional. Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://” if the thumbnail was uploaded using multipart/form-data under . More information on Sending Files » + Thumbnail string `json:"thumbnail,omitempty"` + // Optional. Cover for the video in the message. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet, or pass “attach://” to upload a new one using multipart/form-data under name. More information on Sending Files » + Cover string `json:"cover,omitempty"` + // Optional. Start timestamp for the video in the message + StartTimestamp *int64 `json:"start_timestamp,omitempty"` + // Optional. Video width + Width *int64 `json:"width,omitempty"` + // Optional. Video height + Height *int64 `json:"height,omitempty"` + // Optional. Video duration in seconds + Duration *int64 `json:"duration,omitempty"` + // Optional. Pass True if the uploaded video is suitable for streaming + SupportsStreaming *bool `json:"supports_streaming,omitempty"` +} + +// InputProfilePhoto is a union type. The following concrete variants implement +// it: +// - InputProfilePhotoStatic +// - InputProfilePhotoAnimated +// +// This object describes a profile photo to set. Currently, it can be one of +type InputProfilePhoto interface{ isInputProfilePhoto() } + +// isInputProfilePhoto is the marker method that makes InputProfilePhotoStatic implement InputProfilePhoto. +func (*InputProfilePhotoStatic) isInputProfilePhoto() {} + +// isInputProfilePhoto is the marker method that makes InputProfilePhotoAnimated implement InputProfilePhoto. +func (*InputProfilePhotoAnimated) isInputProfilePhoto() {} + +// A static profile photo in the .JPG format. +type InputProfilePhotoStatic struct { + // Type of the profile photo, must be static + Type string `json:"type"` + // The static profile photo. Profile photos can't be reused and can only be uploaded as a new file, so you can pass “attach://” if the photo was uploaded using multipart/form-data under . More information on Sending Files » + Photo string `json:"photo"` +} + +// An animated profile photo in the MPEG4 format. +type InputProfilePhotoAnimated struct { + // Type of the profile photo, must be animated + Type string `json:"type"` + // The animated profile photo. Profile photos can't be reused and can only be uploaded as a new file, so you can pass “attach://” if the photo was uploaded using multipart/form-data under . More information on Sending Files » + Animation string `json:"animation"` + // Optional. Timestamp in seconds of the frame that will be used as the static profile photo. Defaults to 0.0. + MainFrameTimestamp *float64 `json:"main_frame_timestamp,omitempty"` +} + +// InputStoryContent is a union type. The following concrete variants implement +// it: +// - InputStoryContentPhoto +// - InputStoryContentVideo +// +// This object describes the content of a story to post. Currently, it can be one of +type InputStoryContent interface{ isInputStoryContent() } + +// isInputStoryContent is the marker method that makes InputStoryContentPhoto implement InputStoryContent. +func (*InputStoryContentPhoto) isInputStoryContent() {} + +// isInputStoryContent is the marker method that makes InputStoryContentVideo implement InputStoryContent. +func (*InputStoryContentVideo) isInputStoryContent() {} + +// Describes a photo to post as a story. +type InputStoryContentPhoto struct { + // Type of the content, must be photo + Type string `json:"type"` + // The photo to post as a story. The photo must be of the size 1080x1920 and must not exceed 10 MB. The photo can't be reused and can only be uploaded as a new file, so you can pass “attach://” if the photo was uploaded using multipart/form-data under . More information on Sending Files » + Photo string `json:"photo"` +} + +// Describes a video to post as a story. +type InputStoryContentVideo struct { + // Type of the content, must be video + Type string `json:"type"` + // The video to post as a story. The video must be of the size 720x1280, streamable, encoded with H.265 codec, with key frames added each second in the MPEG4 format, and must not exceed 30 MB. The video can't be reused and can only be uploaded as a new file, so you can pass “attach://” if the video was uploaded using multipart/form-data under . More information on Sending Files » + Video string `json:"video"` + // Optional. Precise duration of the video in seconds; 0-60 + Duration *float64 `json:"duration,omitempty"` + // Optional. Timestamp in seconds of the frame that will be used as the static cover for the story. Defaults to 0.0. + CoverFrameTimestamp *float64 `json:"cover_frame_timestamp,omitempty"` + // Optional. Pass True if the video has no sound + IsAnimation *bool `json:"is_animation,omitempty"` +} + +// This object represents a sticker. +type Sticker struct { + // Identifier for this file, which can be used to download or reuse the file + FileID string `json:"file_id"` + // Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file. + FileUniqueID string `json:"file_unique_id"` + // Type of the sticker, currently one of “regular”, “mask”, “custom_emoji”. The type of the sticker is independent from its format, which is determined by the fields is_animated and is_video. + Type string `json:"type"` + // Sticker width + Width int64 `json:"width"` + // Sticker height + Height int64 `json:"height"` + // True, if the sticker is animated + IsAnimated bool `json:"is_animated"` + // True, if the sticker is a video sticker + IsVideo bool `json:"is_video"` + // Optional. Sticker thumbnail in the .WEBP or .JPG format + Thumbnail *PhotoSize `json:"thumbnail,omitempty"` + // Optional. Emoji associated with the sticker + Emoji string `json:"emoji,omitempty"` + // Optional. Name of the sticker set to which the sticker belongs + SetName string `json:"set_name,omitempty"` + // Optional. For premium regular stickers, premium animation for the sticker + PremiumAnimation *File `json:"premium_animation,omitempty"` + // Optional. For mask stickers, the position where the mask should be placed + MaskPosition *MaskPosition `json:"mask_position,omitempty"` + // Optional. For custom emoji stickers, unique identifier of the custom emoji + CustomEmojiID string `json:"custom_emoji_id,omitempty"` + // Optional. True, if the sticker must be repainted to a text color in messages, the color of the Telegram Premium badge in emoji status, white color on chat photos, or another appropriate color in other places + NeedsRepainting *bool `json:"needs_repainting,omitempty"` + // Optional. File size in bytes + FileSize *int64 `json:"file_size,omitempty"` +} + +// This object represents a sticker set. +type StickerSet struct { + // Sticker set name + Name string `json:"name"` + // Sticker set title + Title string `json:"title"` + // Type of stickers in the set, currently one of “regular”, “mask”, “custom_emoji” + StickerType string `json:"sticker_type"` + // List of all set stickers + Stickers []Sticker `json:"stickers"` + // Optional. Sticker set thumbnail in the .WEBP, .TGS, or .WEBM format + Thumbnail *PhotoSize `json:"thumbnail,omitempty"` +} + +// This object describes the position on faces where a mask should be placed by default. +type MaskPosition struct { + // The part of the face relative to which the mask should be placed. One of “forehead”, “eyes”, “mouth”, or “chin”. + Point string `json:"point"` + // Shift by X-axis measured in widths of the mask scaled to the face size, from left to right. For example, choosing -1.0 will place mask just to the left of the default mask position. + XShift float64 `json:"x_shift"` + // Shift by Y-axis measured in heights of the mask scaled to the face size, from top to bottom. For example, 1.0 will place the mask just below the default mask position. + YShift float64 `json:"y_shift"` + // Mask scaling coefficient. For example, 2.0 means double size. + Scale float64 `json:"scale"` +} + +// This object describes a sticker to be added to a sticker set. +type InputSticker struct { + // The added sticker. Pass a file_id as a String to send a file that already exists on the Telegram servers, pass an HTTP URL as a String for Telegram to get a file from the Internet, or pass “attach://” to upload a new file using multipart/form-data under name. Animated and video stickers can't be uploaded via HTTP URL. More information on Sending Files » + Sticker string `json:"sticker"` + // Format of the added sticker, must be one of “static” for a .WEBP or .PNG image, “animated” for a .TGS animation, “video” for a .WEBM video + Format string `json:"format"` + // List of 1-20 emoji associated with the sticker + EmojiList []string `json:"emoji_list"` + // Optional. Position where the mask should be placed on faces. For “mask” stickers only. + MaskPosition *MaskPosition `json:"mask_position,omitempty"` + // Optional. List of 0-20 search keywords for the sticker with total length of up to 64 characters. For “regular” and “custom_emoji” stickers only. + Keywords []string `json:"keywords,omitempty"` +} + +// This object represents an incoming inline query. When the user sends an empty query, your bot could return some default or trending results. +type InlineQuery struct { + // Unique identifier for this query + ID string `json:"id"` + // Sender + From User `json:"from"` + // Text of the query (up to 256 characters) + Query string `json:"query"` + // Offset of the results to be returned, can be controlled by the bot + Offset string `json:"offset"` + // Optional. Type of the chat from which the inline query was sent. Can be either “sender” for a private chat with the inline query sender, “private”, “group”, “supergroup”, or “channel”. The chat type should be always known for requests sent from official clients and most third-party clients, unless the request was sent from a secret chat + ChatType string `json:"chat_type,omitempty"` + // Optional. Sender location, only for bots that request user location + Location *Location `json:"location,omitempty"` +} + +// This object represents a button to be shown above inline query results. You must use exactly one of the optional fields. +type InlineQueryResultsButton struct { + // Label text on the button + Text string `json:"text"` + // Optional. Description of the Web App that will be launched when the user presses the button. The Web App will be able to switch back to the inline mode using the method switchInlineQuery inside the Web App. + WebApp *WebAppInfo `json:"web_app,omitempty"` + // Optional. Deep-linking parameter for the /start message sent to the bot when a user presses the button. 1-64 characters, only A-Z, a-z, 0-9, _ and - are allowed.Example: An inline bot that sends YouTube videos can ask the user to connect the bot to their YouTube account to adapt search results accordingly. To do this, it displays a 'Connect your YouTube account' button above the results, or even before showing any. The user presses the button, switches to a private chat with the bot and, in doing so, passes a start parameter that instructs the bot to return an OAuth link. Once done, the bot can offer a switch_inline button so that the user can easily return to the chat where they wanted to use the bot's inline capabilities. + StartParameter string `json:"start_parameter,omitempty"` +} + +// InlineQueryResult is a union type. The following concrete variants implement +// it: +// - InlineQueryResultCachedAudio +// - InlineQueryResultCachedDocument +// - InlineQueryResultCachedGif +// - InlineQueryResultCachedMpeg4Gif +// - InlineQueryResultCachedPhoto +// - InlineQueryResultCachedSticker +// - InlineQueryResultCachedVideo +// - InlineQueryResultCachedVoice +// - InlineQueryResultArticle +// - InlineQueryResultAudio +// - InlineQueryResultContact +// - InlineQueryResultGame +// - InlineQueryResultDocument +// - InlineQueryResultGif +// - InlineQueryResultLocation +// - InlineQueryResultMpeg4Gif +// - InlineQueryResultPhoto +// - InlineQueryResultVenue +// - InlineQueryResultVideo +// - InlineQueryResultVoice +// +// This object represents one result of an inline query. Telegram clients currently support results of the following 20 types: +// Note: All URLs passed in inline query results will be available to end users and therefore must be assumed to be public. +type InlineQueryResult interface{ isInlineQueryResult() } + +// isInlineQueryResult is the marker method that makes InlineQueryResultCachedAudio implement InlineQueryResult. +func (*InlineQueryResultCachedAudio) isInlineQueryResult() {} + +// isInlineQueryResult is the marker method that makes InlineQueryResultCachedDocument implement InlineQueryResult. +func (*InlineQueryResultCachedDocument) isInlineQueryResult() {} + +// isInlineQueryResult is the marker method that makes InlineQueryResultCachedGif implement InlineQueryResult. +func (*InlineQueryResultCachedGif) isInlineQueryResult() {} + +// isInlineQueryResult is the marker method that makes InlineQueryResultCachedMpeg4Gif implement InlineQueryResult. +func (*InlineQueryResultCachedMpeg4Gif) isInlineQueryResult() {} + +// isInlineQueryResult is the marker method that makes InlineQueryResultCachedPhoto implement InlineQueryResult. +func (*InlineQueryResultCachedPhoto) isInlineQueryResult() {} + +// isInlineQueryResult is the marker method that makes InlineQueryResultCachedSticker implement InlineQueryResult. +func (*InlineQueryResultCachedSticker) isInlineQueryResult() {} + +// isInlineQueryResult is the marker method that makes InlineQueryResultCachedVideo implement InlineQueryResult. +func (*InlineQueryResultCachedVideo) isInlineQueryResult() {} + +// isInlineQueryResult is the marker method that makes InlineQueryResultCachedVoice implement InlineQueryResult. +func (*InlineQueryResultCachedVoice) isInlineQueryResult() {} + +// isInlineQueryResult is the marker method that makes InlineQueryResultArticle implement InlineQueryResult. +func (*InlineQueryResultArticle) isInlineQueryResult() {} + +// isInlineQueryResult is the marker method that makes InlineQueryResultAudio implement InlineQueryResult. +func (*InlineQueryResultAudio) isInlineQueryResult() {} + +// isInlineQueryResult is the marker method that makes InlineQueryResultContact implement InlineQueryResult. +func (*InlineQueryResultContact) isInlineQueryResult() {} + +// isInlineQueryResult is the marker method that makes InlineQueryResultGame implement InlineQueryResult. +func (*InlineQueryResultGame) isInlineQueryResult() {} + +// isInlineQueryResult is the marker method that makes InlineQueryResultDocument implement InlineQueryResult. +func (*InlineQueryResultDocument) isInlineQueryResult() {} + +// isInlineQueryResult is the marker method that makes InlineQueryResultGif implement InlineQueryResult. +func (*InlineQueryResultGif) isInlineQueryResult() {} + +// isInlineQueryResult is the marker method that makes InlineQueryResultLocation implement InlineQueryResult. +func (*InlineQueryResultLocation) isInlineQueryResult() {} + +// isInlineQueryResult is the marker method that makes InlineQueryResultMpeg4Gif implement InlineQueryResult. +func (*InlineQueryResultMpeg4Gif) isInlineQueryResult() {} + +// isInlineQueryResult is the marker method that makes InlineQueryResultPhoto implement InlineQueryResult. +func (*InlineQueryResultPhoto) isInlineQueryResult() {} + +// isInlineQueryResult is the marker method that makes InlineQueryResultVenue implement InlineQueryResult. +func (*InlineQueryResultVenue) isInlineQueryResult() {} + +// isInlineQueryResult is the marker method that makes InlineQueryResultVideo implement InlineQueryResult. +func (*InlineQueryResultVideo) isInlineQueryResult() {} + +// isInlineQueryResult is the marker method that makes InlineQueryResultVoice implement InlineQueryResult. +func (*InlineQueryResultVoice) isInlineQueryResult() {} + +// Represents a link to an article or web page. +type InlineQueryResultArticle struct { + // Type of the result, must be article + Type string `json:"type"` + // Unique identifier for this result, 1-64 Bytes + ID string `json:"id"` + // Title of the result + Title string `json:"title"` + // Content of the message to be sent + InputMessageContent InputMessageContent `json:"input_message_content"` + // Optional. Inline keyboard attached to the message + ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"` + // Optional. URL of the result + URL string `json:"url,omitempty"` + // Optional. Short description of the result + Description string `json:"description,omitempty"` + // Optional. Url of the thumbnail for the result + ThumbnailURL string `json:"thumbnail_url,omitempty"` + // Optional. Thumbnail width + ThumbnailWidth *int64 `json:"thumbnail_width,omitempty"` + // Optional. Thumbnail height + ThumbnailHeight *int64 `json:"thumbnail_height,omitempty"` +} + +// Represents a link to a photo. By default, this photo will be sent by the user with optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the photo. +type InlineQueryResultPhoto struct { + // Type of the result, must be photo + Type string `json:"type"` + // Unique identifier for this result, 1-64 bytes + ID string `json:"id"` + // A valid URL of the photo. Photo must be in JPEG format. Photo size must not exceed 5MB + PhotoURL string `json:"photo_url"` + // URL of the thumbnail for the photo + ThumbnailURL string `json:"thumbnail_url"` + // Optional. Width of the photo + PhotoWidth *int64 `json:"photo_width,omitempty"` + // Optional. Height of the photo + PhotoHeight *int64 `json:"photo_height,omitempty"` + // Optional. Title for the result + Title string `json:"title,omitempty"` + // Optional. Short description of the result + Description string `json:"description,omitempty"` + // Optional. Caption of the photo to be sent, 0-1024 characters after entities parsing + Caption string `json:"caption,omitempty"` + // Optional. Mode for parsing entities in the photo caption. See formatting options for more details. + ParseMode string `json:"parse_mode,omitempty"` + // Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode + CaptionEntities []MessageEntity `json:"caption_entities,omitempty"` + // Optional. Pass True, if the caption must be shown above the message media + ShowCaptionAboveMedia *bool `json:"show_caption_above_media,omitempty"` + // Optional. Inline keyboard attached to the message + ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"` + // Optional. Content of the message to be sent instead of the photo + InputMessageContent *InputMessageContent `json:"input_message_content,omitempty"` +} + +// Represents a link to an animated GIF file. By default, this animated GIF file will be sent by the user with optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the animation. +type InlineQueryResultGif struct { + // Type of the result, must be gif + Type string `json:"type"` + // Unique identifier for this result, 1-64 bytes + ID string `json:"id"` + // A valid URL for the GIF file + GifURL string `json:"gif_url"` + // Optional. Width of the GIF + GifWidth *int64 `json:"gif_width,omitempty"` + // Optional. Height of the GIF + GifHeight *int64 `json:"gif_height,omitempty"` + // Optional. Duration of the GIF in seconds + GifDuration *int64 `json:"gif_duration,omitempty"` + // URL of the static (JPEG or GIF) or animated (MPEG4) thumbnail for the result + ThumbnailURL string `json:"thumbnail_url"` + // Optional. MIME type of the thumbnail, must be one of “image/jpeg”, “image/gif”, or “video/mp4”. Defaults to “image/jpeg” + ThumbnailMimeType string `json:"thumbnail_mime_type,omitempty"` + // Optional. Title for the result + Title string `json:"title,omitempty"` + // Optional. Caption of the GIF file to be sent, 0-1024 characters after entities parsing + Caption string `json:"caption,omitempty"` + // Optional. Mode for parsing entities in the caption. See formatting options for more details. + ParseMode string `json:"parse_mode,omitempty"` + // Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode + CaptionEntities []MessageEntity `json:"caption_entities,omitempty"` + // Optional. Pass True, if the caption must be shown above the message media + ShowCaptionAboveMedia *bool `json:"show_caption_above_media,omitempty"` + // Optional. Inline keyboard attached to the message + ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"` + // Optional. Content of the message to be sent instead of the GIF animation + InputMessageContent *InputMessageContent `json:"input_message_content,omitempty"` +} + +// Represents a link to a video animation (H.264/MPEG-4 AVC video without sound). By default, this animated MPEG-4 file will be sent by the user with optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the animation. +type InlineQueryResultMpeg4Gif struct { + // Type of the result, must be mpeg4_gif + Type string `json:"type"` + // Unique identifier for this result, 1-64 bytes + ID string `json:"id"` + // A valid URL for the MPEG4 file + Mpeg4URL string `json:"mpeg4_url"` + // Optional. Video width + Mpeg4Width *int64 `json:"mpeg4_width,omitempty"` + // Optional. Video height + Mpeg4Height *int64 `json:"mpeg4_height,omitempty"` + // Optional. Video duration in seconds + Mpeg4Duration *int64 `json:"mpeg4_duration,omitempty"` + // URL of the static (JPEG or GIF) or animated (MPEG4) thumbnail for the result + ThumbnailURL string `json:"thumbnail_url"` + // Optional. MIME type of the thumbnail, must be one of “image/jpeg”, “image/gif”, or “video/mp4”. Defaults to “image/jpeg” + ThumbnailMimeType string `json:"thumbnail_mime_type,omitempty"` + // Optional. Title for the result + Title string `json:"title,omitempty"` + // Optional. Caption of the MPEG-4 file to be sent, 0-1024 characters after entities parsing + Caption string `json:"caption,omitempty"` + // Optional. Mode for parsing entities in the caption. See formatting options for more details. + ParseMode string `json:"parse_mode,omitempty"` + // Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode + CaptionEntities []MessageEntity `json:"caption_entities,omitempty"` + // Optional. Pass True, if the caption must be shown above the message media + ShowCaptionAboveMedia *bool `json:"show_caption_above_media,omitempty"` + // Optional. Inline keyboard attached to the message + ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"` + // Optional. Content of the message to be sent instead of the video animation + InputMessageContent *InputMessageContent `json:"input_message_content,omitempty"` +} + +// Represents a link to a page containing an embedded video player or a video file. By default, this video file will be sent by the user with an optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the video. +// If an InlineQueryResultVideo message contains an embedded video (e.g., YouTube), you must replace its content using input_message_content. +type InlineQueryResultVideo struct { + // Type of the result, must be video + Type string `json:"type"` + // Unique identifier for this result, 1-64 bytes + ID string `json:"id"` + // A valid URL for the embedded video player or video file + VideoURL string `json:"video_url"` + // MIME type of the content of the video URL, “text/html” or “video/mp4” + MimeType string `json:"mime_type"` + // URL of the thumbnail (JPEG only) for the video + ThumbnailURL string `json:"thumbnail_url"` + // Title for the result + Title string `json:"title"` + // Optional. Caption of the video to be sent, 0-1024 characters after entities parsing + Caption string `json:"caption,omitempty"` + // Optional. Mode for parsing entities in the video caption. See formatting options for more details. + ParseMode string `json:"parse_mode,omitempty"` + // Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode + CaptionEntities []MessageEntity `json:"caption_entities,omitempty"` + // Optional. Pass True, if the caption must be shown above the message media + ShowCaptionAboveMedia *bool `json:"show_caption_above_media,omitempty"` + // Optional. Video width + VideoWidth *int64 `json:"video_width,omitempty"` + // Optional. Video height + VideoHeight *int64 `json:"video_height,omitempty"` + // Optional. Video duration in seconds + VideoDuration *int64 `json:"video_duration,omitempty"` + // Optional. Short description of the result + Description string `json:"description,omitempty"` + // Optional. Inline keyboard attached to the message + ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"` + // Optional. Content of the message to be sent instead of the video. This field is required if InlineQueryResultVideo is used to send an HTML-page as a result (e.g., a YouTube video). + InputMessageContent *InputMessageContent `json:"input_message_content,omitempty"` +} + +// Represents a link to an MP3 audio file. By default, this audio file will be sent by the user. Alternatively, you can use input_message_content to send a message with the specified content instead of the audio. +type InlineQueryResultAudio struct { + // Type of the result, must be audio + Type string `json:"type"` + // Unique identifier for this result, 1-64 bytes + ID string `json:"id"` + // A valid URL for the audio file + AudioURL string `json:"audio_url"` + // Title + Title string `json:"title"` + // Optional. Caption, 0-1024 characters after entities parsing + Caption string `json:"caption,omitempty"` + // Optional. Mode for parsing entities in the audio caption. See formatting options for more details. + ParseMode string `json:"parse_mode,omitempty"` + // Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode + CaptionEntities []MessageEntity `json:"caption_entities,omitempty"` + // Optional. Performer + Performer string `json:"performer,omitempty"` + // Optional. Audio duration in seconds + AudioDuration *int64 `json:"audio_duration,omitempty"` + // Optional. Inline keyboard attached to the message + ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"` + // Optional. Content of the message to be sent instead of the audio + InputMessageContent *InputMessageContent `json:"input_message_content,omitempty"` +} + +// Represents a link to a voice recording in an .OGG container encoded with OPUS. By default, this voice recording will be sent by the user. Alternatively, you can use input_message_content to send a message with the specified content instead of the the voice message. +type InlineQueryResultVoice struct { + // Type of the result, must be voice + Type string `json:"type"` + // Unique identifier for this result, 1-64 bytes + ID string `json:"id"` + // A valid URL for the voice recording + VoiceURL string `json:"voice_url"` + // Recording title + Title string `json:"title"` + // Optional. Caption, 0-1024 characters after entities parsing + Caption string `json:"caption,omitempty"` + // Optional. Mode for parsing entities in the voice message caption. See formatting options for more details. + ParseMode string `json:"parse_mode,omitempty"` + // Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode + CaptionEntities []MessageEntity `json:"caption_entities,omitempty"` + // Optional. Recording duration in seconds + VoiceDuration *int64 `json:"voice_duration,omitempty"` + // Optional. Inline keyboard attached to the message + ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"` + // Optional. Content of the message to be sent instead of the voice recording + InputMessageContent *InputMessageContent `json:"input_message_content,omitempty"` +} + +// Represents a link to a file. By default, this file will be sent by the user with an optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the file. Currently, only .PDF and .ZIP files can be sent using this method. +type InlineQueryResultDocument struct { + // Type of the result, must be document + Type string `json:"type"` + // Unique identifier for this result, 1-64 bytes + ID string `json:"id"` + // Title for the result + Title string `json:"title"` + // Optional. Caption of the document to be sent, 0-1024 characters after entities parsing + Caption string `json:"caption,omitempty"` + // Optional. Mode for parsing entities in the document caption. See formatting options for more details. + ParseMode string `json:"parse_mode,omitempty"` + // Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode + CaptionEntities []MessageEntity `json:"caption_entities,omitempty"` + // A valid URL for the file + DocumentURL string `json:"document_url"` + // MIME type of the content of the file, either “application/pdf” or “application/zip” + MimeType string `json:"mime_type"` + // Optional. Short description of the result + Description string `json:"description,omitempty"` + // Optional. Inline keyboard attached to the message + ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"` + // Optional. Content of the message to be sent instead of the file + InputMessageContent *InputMessageContent `json:"input_message_content,omitempty"` + // Optional. URL of the thumbnail (JPEG only) for the file + ThumbnailURL string `json:"thumbnail_url,omitempty"` + // Optional. Thumbnail width + ThumbnailWidth *int64 `json:"thumbnail_width,omitempty"` + // Optional. Thumbnail height + ThumbnailHeight *int64 `json:"thumbnail_height,omitempty"` +} + +// Represents a location on a map. By default, the location will be sent by the user. Alternatively, you can use input_message_content to send a message with the specified content instead of the location. +type InlineQueryResultLocation struct { + // Type of the result, must be location + Type string `json:"type"` + // Unique identifier for this result, 1-64 Bytes + ID string `json:"id"` + // Location latitude in degrees + Latitude float64 `json:"latitude"` + // Location longitude in degrees + Longitude float64 `json:"longitude"` + // Location title + Title string `json:"title"` + // Optional. The radius of uncertainty for the location, measured in meters; 0-1500 + HorizontalAccuracy *float64 `json:"horizontal_accuracy,omitempty"` + // Optional. Period in seconds during which the location can be updated, should be between 60 and 86400, or 0x7FFFFFFF for live locations that can be edited indefinitely. + LivePeriod *int64 `json:"live_period,omitempty"` + // Optional. For live locations, a direction in which the user is moving, in degrees. Must be between 1 and 360 if specified. + Heading *int64 `json:"heading,omitempty"` + // Optional. For live locations, a maximum distance for proximity alerts about approaching another chat member, in meters. Must be between 1 and 100000 if specified. + ProximityAlertRadius *int64 `json:"proximity_alert_radius,omitempty"` + // Optional. Inline keyboard attached to the message + ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"` + // Optional. Content of the message to be sent instead of the location + InputMessageContent *InputMessageContent `json:"input_message_content,omitempty"` + // Optional. Url of the thumbnail for the result + ThumbnailURL string `json:"thumbnail_url,omitempty"` + // Optional. Thumbnail width + ThumbnailWidth *int64 `json:"thumbnail_width,omitempty"` + // Optional. Thumbnail height + ThumbnailHeight *int64 `json:"thumbnail_height,omitempty"` +} + +// Represents a venue. By default, the venue will be sent by the user. Alternatively, you can use input_message_content to send a message with the specified content instead of the venue. +type InlineQueryResultVenue struct { + // Type of the result, must be venue + Type string `json:"type"` + // Unique identifier for this result, 1-64 Bytes + ID string `json:"id"` + // Latitude of the venue location in degrees + Latitude float64 `json:"latitude"` + // Longitude of the venue location in degrees + Longitude float64 `json:"longitude"` + // Title of the venue + Title string `json:"title"` + // Address of the venue + Address string `json:"address"` + // Optional. Foursquare identifier of the venue if known + FoursquareID string `json:"foursquare_id,omitempty"` + // Optional. Foursquare type of the venue, if known. (For example, “arts_entertainment/default”, “arts_entertainment/aquarium” or “food/icecream”.) + FoursquareType string `json:"foursquare_type,omitempty"` + // Optional. Google Places identifier of the venue + GooglePlaceID string `json:"google_place_id,omitempty"` + // Optional. Google Places type of the venue. (See supported types.) + GooglePlaceType string `json:"google_place_type,omitempty"` + // Optional. Inline keyboard attached to the message + ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"` + // Optional. Content of the message to be sent instead of the venue + InputMessageContent *InputMessageContent `json:"input_message_content,omitempty"` + // Optional. Url of the thumbnail for the result + ThumbnailURL string `json:"thumbnail_url,omitempty"` + // Optional. Thumbnail width + ThumbnailWidth *int64 `json:"thumbnail_width,omitempty"` + // Optional. Thumbnail height + ThumbnailHeight *int64 `json:"thumbnail_height,omitempty"` +} + +// Represents a contact with a phone number. By default, this contact will be sent by the user. Alternatively, you can use input_message_content to send a message with the specified content instead of the contact. +type InlineQueryResultContact struct { + // Type of the result, must be contact + Type string `json:"type"` + // Unique identifier for this result, 1-64 Bytes + ID string `json:"id"` + // Contact's phone number + PhoneNumber string `json:"phone_number"` + // Contact's first name + FirstName string `json:"first_name"` + // Optional. Contact's last name + LastName string `json:"last_name,omitempty"` + // Optional. Additional data about the contact in the form of a vCard, 0-2048 bytes + Vcard string `json:"vcard,omitempty"` + // Optional. Inline keyboard attached to the message + ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"` + // Optional. Content of the message to be sent instead of the contact + InputMessageContent *InputMessageContent `json:"input_message_content,omitempty"` + // Optional. Url of the thumbnail for the result + ThumbnailURL string `json:"thumbnail_url,omitempty"` + // Optional. Thumbnail width + ThumbnailWidth *int64 `json:"thumbnail_width,omitempty"` + // Optional. Thumbnail height + ThumbnailHeight *int64 `json:"thumbnail_height,omitempty"` +} + +// Represents a Game. +type InlineQueryResultGame struct { + // Type of the result, must be game + Type string `json:"type"` + // Unique identifier for this result, 1-64 bytes + ID string `json:"id"` + // Short name of the game + GameShortName string `json:"game_short_name"` + // Optional. Inline keyboard attached to the message + ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"` +} + +// Represents a link to a photo stored on the Telegram servers. By default, this photo will be sent by the user with an optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the photo. +type InlineQueryResultCachedPhoto struct { + // Type of the result, must be photo + Type string `json:"type"` + // Unique identifier for this result, 1-64 bytes + ID string `json:"id"` + // A valid file identifier of the photo + PhotoFileID string `json:"photo_file_id"` + // Optional. Title for the result + Title string `json:"title,omitempty"` + // Optional. Short description of the result + Description string `json:"description,omitempty"` + // Optional. Caption of the photo to be sent, 0-1024 characters after entities parsing + Caption string `json:"caption,omitempty"` + // Optional. Mode for parsing entities in the photo caption. See formatting options for more details. + ParseMode string `json:"parse_mode,omitempty"` + // Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode + CaptionEntities []MessageEntity `json:"caption_entities,omitempty"` + // Optional. Pass True, if the caption must be shown above the message media + ShowCaptionAboveMedia *bool `json:"show_caption_above_media,omitempty"` + // Optional. Inline keyboard attached to the message + ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"` + // Optional. Content of the message to be sent instead of the photo + InputMessageContent *InputMessageContent `json:"input_message_content,omitempty"` +} + +// Represents a link to an animated GIF file stored on the Telegram servers. By default, this animated GIF file will be sent by the user with an optional caption. Alternatively, you can use input_message_content to send a message with specified content instead of the animation. +type InlineQueryResultCachedGif struct { + // Type of the result, must be gif + Type string `json:"type"` + // Unique identifier for this result, 1-64 bytes + ID string `json:"id"` + // A valid file identifier for the GIF file + GifFileID string `json:"gif_file_id"` + // Optional. Title for the result + Title string `json:"title,omitempty"` + // Optional. Caption of the GIF file to be sent, 0-1024 characters after entities parsing + Caption string `json:"caption,omitempty"` + // Optional. Mode for parsing entities in the caption. See formatting options for more details. + ParseMode string `json:"parse_mode,omitempty"` + // Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode + CaptionEntities []MessageEntity `json:"caption_entities,omitempty"` + // Optional. Pass True, if the caption must be shown above the message media + ShowCaptionAboveMedia *bool `json:"show_caption_above_media,omitempty"` + // Optional. Inline keyboard attached to the message + ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"` + // Optional. Content of the message to be sent instead of the GIF animation + InputMessageContent *InputMessageContent `json:"input_message_content,omitempty"` +} + +// Represents a link to a video animation (H.264/MPEG-4 AVC video without sound) stored on the Telegram servers. By default, this animated MPEG-4 file will be sent by the user with an optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the animation. +type InlineQueryResultCachedMpeg4Gif struct { + // Type of the result, must be mpeg4_gif + Type string `json:"type"` + // Unique identifier for this result, 1-64 bytes + ID string `json:"id"` + // A valid file identifier for the MPEG4 file + Mpeg4FileID string `json:"mpeg4_file_id"` + // Optional. Title for the result + Title string `json:"title,omitempty"` + // Optional. Caption of the MPEG-4 file to be sent, 0-1024 characters after entities parsing + Caption string `json:"caption,omitempty"` + // Optional. Mode for parsing entities in the caption. See formatting options for more details. + ParseMode string `json:"parse_mode,omitempty"` + // Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode + CaptionEntities []MessageEntity `json:"caption_entities,omitempty"` + // Optional. Pass True, if the caption must be shown above the message media + ShowCaptionAboveMedia *bool `json:"show_caption_above_media,omitempty"` + // Optional. Inline keyboard attached to the message + ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"` + // Optional. Content of the message to be sent instead of the video animation + InputMessageContent *InputMessageContent `json:"input_message_content,omitempty"` +} + +// Represents a link to a sticker stored on the Telegram servers. By default, this sticker will be sent by the user. Alternatively, you can use input_message_content to send a message with the specified content instead of the sticker. +type InlineQueryResultCachedSticker struct { + // Type of the result, must be sticker + Type string `json:"type"` + // Unique identifier for this result, 1-64 bytes + ID string `json:"id"` + // A valid file identifier of the sticker + StickerFileID string `json:"sticker_file_id"` + // Optional. Inline keyboard attached to the message + ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"` + // Optional. Content of the message to be sent instead of the sticker + InputMessageContent *InputMessageContent `json:"input_message_content,omitempty"` +} + +// Represents a link to a file stored on the Telegram servers. By default, this file will be sent by the user with an optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the file. +type InlineQueryResultCachedDocument struct { + // Type of the result, must be document + Type string `json:"type"` + // Unique identifier for this result, 1-64 bytes + ID string `json:"id"` + // Title for the result + Title string `json:"title"` + // A valid file identifier for the file + DocumentFileID string `json:"document_file_id"` + // Optional. Short description of the result + Description string `json:"description,omitempty"` + // Optional. Caption of the document to be sent, 0-1024 characters after entities parsing + Caption string `json:"caption,omitempty"` + // Optional. Mode for parsing entities in the document caption. See formatting options for more details. + ParseMode string `json:"parse_mode,omitempty"` + // Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode + CaptionEntities []MessageEntity `json:"caption_entities,omitempty"` + // Optional. Inline keyboard attached to the message + ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"` + // Optional. Content of the message to be sent instead of the file + InputMessageContent *InputMessageContent `json:"input_message_content,omitempty"` +} + +// Represents a link to a video file stored on the Telegram servers. By default, this video file will be sent by the user with an optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the video. +type InlineQueryResultCachedVideo struct { + // Type of the result, must be video + Type string `json:"type"` + // Unique identifier for this result, 1-64 bytes + ID string `json:"id"` + // A valid file identifier for the video file + VideoFileID string `json:"video_file_id"` + // Title for the result + Title string `json:"title"` + // Optional. Short description of the result + Description string `json:"description,omitempty"` + // Optional. Caption of the video to be sent, 0-1024 characters after entities parsing + Caption string `json:"caption,omitempty"` + // Optional. Mode for parsing entities in the video caption. See formatting options for more details. + ParseMode string `json:"parse_mode,omitempty"` + // Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode + CaptionEntities []MessageEntity `json:"caption_entities,omitempty"` + // Optional. Pass True, if the caption must be shown above the message media + ShowCaptionAboveMedia *bool `json:"show_caption_above_media,omitempty"` + // Optional. Inline keyboard attached to the message + ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"` + // Optional. Content of the message to be sent instead of the video + InputMessageContent *InputMessageContent `json:"input_message_content,omitempty"` +} + +// Represents a link to a voice message stored on the Telegram servers. By default, this voice message will be sent by the user. Alternatively, you can use input_message_content to send a message with the specified content instead of the voice message. +type InlineQueryResultCachedVoice struct { + // Type of the result, must be voice + Type string `json:"type"` + // Unique identifier for this result, 1-64 bytes + ID string `json:"id"` + // A valid file identifier for the voice message + VoiceFileID string `json:"voice_file_id"` + // Voice message title + Title string `json:"title"` + // Optional. Caption, 0-1024 characters after entities parsing + Caption string `json:"caption,omitempty"` + // Optional. Mode for parsing entities in the voice message caption. See formatting options for more details. + ParseMode string `json:"parse_mode,omitempty"` + // Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode + CaptionEntities []MessageEntity `json:"caption_entities,omitempty"` + // Optional. Inline keyboard attached to the message + ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"` + // Optional. Content of the message to be sent instead of the voice message + InputMessageContent *InputMessageContent `json:"input_message_content,omitempty"` +} + +// Represents a link to an MP3 audio file stored on the Telegram servers. By default, this audio file will be sent by the user. Alternatively, you can use input_message_content to send a message with the specified content instead of the audio. +type InlineQueryResultCachedAudio struct { + // Type of the result, must be audio + Type string `json:"type"` + // Unique identifier for this result, 1-64 bytes + ID string `json:"id"` + // A valid file identifier for the audio file + AudioFileID string `json:"audio_file_id"` + // Optional. Caption, 0-1024 characters after entities parsing + Caption string `json:"caption,omitempty"` + // Optional. Mode for parsing entities in the audio caption. See formatting options for more details. + ParseMode string `json:"parse_mode,omitempty"` + // Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode + CaptionEntities []MessageEntity `json:"caption_entities,omitempty"` + // Optional. Inline keyboard attached to the message + ReplyMarkup *InlineKeyboardMarkup `json:"reply_markup,omitempty"` + // Optional. Content of the message to be sent instead of the audio + InputMessageContent *InputMessageContent `json:"input_message_content,omitempty"` +} + +// InputMessageContent is a union type. The following concrete variants implement +// it: +// - InputTextMessageContent +// - InputLocationMessageContent +// - InputVenueMessageContent +// - InputContactMessageContent +// - InputInvoiceMessageContent +// +// This object represents the content of a message to be sent as a result of an inline query. Telegram clients currently support the following 5 types: +type InputMessageContent interface{ isInputMessageContent() } + +// isInputMessageContent is the marker method that makes InputTextMessageContent implement InputMessageContent. +func (*InputTextMessageContent) isInputMessageContent() {} + +// isInputMessageContent is the marker method that makes InputLocationMessageContent implement InputMessageContent. +func (*InputLocationMessageContent) isInputMessageContent() {} + +// isInputMessageContent is the marker method that makes InputVenueMessageContent implement InputMessageContent. +func (*InputVenueMessageContent) isInputMessageContent() {} + +// isInputMessageContent is the marker method that makes InputContactMessageContent implement InputMessageContent. +func (*InputContactMessageContent) isInputMessageContent() {} + +// isInputMessageContent is the marker method that makes InputInvoiceMessageContent implement InputMessageContent. +func (*InputInvoiceMessageContent) isInputMessageContent() {} + +// Represents the content of a text message to be sent as the result of an inline query. +type InputTextMessageContent struct { + // Text of the message to be sent, 1-4096 characters + MessageText string `json:"message_text"` + // Optional. Mode for parsing entities in the message text. See formatting options for more details. + ParseMode string `json:"parse_mode,omitempty"` + // Optional. List of special entities that appear in message text, which can be specified instead of parse_mode + Entities []MessageEntity `json:"entities,omitempty"` + // Optional. Link preview generation options for the message + LinkPreviewOptions *LinkPreviewOptions `json:"link_preview_options,omitempty"` +} + +// Represents the content of a location message to be sent as the result of an inline query. +type InputLocationMessageContent struct { + // Latitude of the location in degrees + Latitude float64 `json:"latitude"` + // Longitude of the location in degrees + Longitude float64 `json:"longitude"` + // Optional. The radius of uncertainty for the location, measured in meters; 0-1500 + HorizontalAccuracy *float64 `json:"horizontal_accuracy,omitempty"` + // Optional. Period in seconds during which the location can be updated, should be between 60 and 86400, or 0x7FFFFFFF for live locations that can be edited indefinitely. + LivePeriod *int64 `json:"live_period,omitempty"` + // Optional. For live locations, a direction in which the user is moving, in degrees. Must be between 1 and 360 if specified. + Heading *int64 `json:"heading,omitempty"` + // Optional. For live locations, a maximum distance for proximity alerts about approaching another chat member, in meters. Must be between 1 and 100000 if specified. + ProximityAlertRadius *int64 `json:"proximity_alert_radius,omitempty"` +} + +// Represents the content of a venue message to be sent as the result of an inline query. +type InputVenueMessageContent struct { + // Latitude of the venue in degrees + Latitude float64 `json:"latitude"` + // Longitude of the venue in degrees + Longitude float64 `json:"longitude"` + // Name of the venue + Title string `json:"title"` + // Address of the venue + Address string `json:"address"` + // Optional. Foursquare identifier of the venue, if known + FoursquareID string `json:"foursquare_id,omitempty"` + // Optional. Foursquare type of the venue, if known. (For example, “arts_entertainment/default”, “arts_entertainment/aquarium” or “food/icecream”.) + FoursquareType string `json:"foursquare_type,omitempty"` + // Optional. Google Places identifier of the venue + GooglePlaceID string `json:"google_place_id,omitempty"` + // Optional. Google Places type of the venue. (See supported types.) + GooglePlaceType string `json:"google_place_type,omitempty"` +} + +// Represents the content of a contact message to be sent as the result of an inline query. +type InputContactMessageContent struct { + // Contact's phone number + PhoneNumber string `json:"phone_number"` + // Contact's first name + FirstName string `json:"first_name"` + // Optional. Contact's last name + LastName string `json:"last_name,omitempty"` + // Optional. Additional data about the contact in the form of a vCard, 0-2048 bytes + Vcard string `json:"vcard,omitempty"` +} + +// Represents the content of an invoice message to be sent as the result of an inline query. +type InputInvoiceMessageContent struct { + // Product name, 1-32 characters + Title string `json:"title"` + // Product description, 1-255 characters + Description string `json:"description"` + // Bot-defined invoice payload, 1-128 bytes. This will not be displayed to the user, use it for your internal processes. + Payload string `json:"payload"` + // Optional. Payment provider token, obtained via @BotFather. Pass an empty string for payments in Telegram Stars. + ProviderToken string `json:"provider_token,omitempty"` + // Three-letter ISO 4217 currency code, see more on currencies. Pass “XTR” for payments in Telegram Stars. + Currency string `json:"currency"` + // Price breakdown, a JSON-serialized list of components (e.g. product price, tax, discount, delivery cost, delivery tax, bonus, etc.). Must contain exactly one item for payments in Telegram Stars. + Prices []LabeledPrice `json:"prices"` + // Optional. The maximum accepted amount for tips in the smallest units of the currency (integer, not float/double). For example, for a maximum tip of US$ 1.45 pass max_tip_amount = 145. See the exp parameter in currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies). Defaults to 0. Not supported for payments in Telegram Stars. + MaxTipAmount *int64 `json:"max_tip_amount,omitempty"` + // Optional. A JSON-serialized array of suggested amounts of tip in the smallest units of the currency (integer, not float/double). At most 4 suggested tip amounts can be specified. The suggested tip amounts must be positive, passed in a strictly increased order and must not exceed max_tip_amount. + SuggestedTipAmounts []int64 `json:"suggested_tip_amounts,omitempty"` + // Optional. A JSON-serialized object for data about the invoice, which will be shared with the payment provider. A detailed description of the required fields should be provided by the payment provider. + ProviderData string `json:"provider_data,omitempty"` + // Optional. URL of the product photo for the invoice. Can be a photo of the goods or a marketing image for a service. + PhotoURL string `json:"photo_url,omitempty"` + // Optional. Photo size in bytes + PhotoSize *int64 `json:"photo_size,omitempty"` + // Optional. Photo width + PhotoWidth *int64 `json:"photo_width,omitempty"` + // Optional. Photo height + PhotoHeight *int64 `json:"photo_height,omitempty"` + // Optional. Pass True if you require the user's full name to complete the order. Ignored for payments in Telegram Stars. + NeedName *bool `json:"need_name,omitempty"` + // Optional. Pass True if you require the user's phone number to complete the order. Ignored for payments in Telegram Stars. + NeedPhoneNumber *bool `json:"need_phone_number,omitempty"` + // Optional. Pass True if you require the user's email address to complete the order. Ignored for payments in Telegram Stars. + NeedEmail *bool `json:"need_email,omitempty"` + // Optional. Pass True if you require the user's shipping address to complete the order. Ignored for payments in Telegram Stars. + NeedShippingAddress *bool `json:"need_shipping_address,omitempty"` + // Optional. Pass True if the user's phone number should be sent to the provider. Ignored for payments in Telegram Stars. + SendPhoneNumberToProvider *bool `json:"send_phone_number_to_provider,omitempty"` + // Optional. Pass True if the user's email address should be sent to the provider. Ignored for payments in Telegram Stars. + SendEmailToProvider *bool `json:"send_email_to_provider,omitempty"` + // Optional. Pass True if the final price depends on the shipping method. Ignored for payments in Telegram Stars. + IsFlexible *bool `json:"is_flexible,omitempty"` +} + +// Represents a result of an inline query that was chosen by the user and sent to their chat partner. +// Note: It is necessary to enable inline feedback via @BotFather in order to receive these objects in updates. +type ChosenInlineResult struct { + // The unique identifier for the result that was chosen + ResultID string `json:"result_id"` + // The user that chose the result + From User `json:"from"` + // Optional. Sender location, only for bots that require user location + Location *Location `json:"location,omitempty"` + // Optional. Identifier of the sent inline message. Available only if there is an inline keyboard attached to the message. Will be also received in callback queries and can be used to edit the message. + InlineMessageID string `json:"inline_message_id,omitempty"` + // The query that was used to obtain the result + Query string `json:"query"` +} + +// This object represents a portion of the price for goods or services. +type LabeledPrice struct { + // Portion label + Label string `json:"label"` + // Price of the product in the smallest units of the currency (integer, not float/double). For example, for a price of US$ 1.45 pass amount = 145. See the exp parameter in currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies). + Amount int64 `json:"amount"` +} + +// This object contains basic information about an invoice. +type Invoice struct { + // Product name + Title string `json:"title"` + // Product description + Description string `json:"description"` + // Unique bot deep-linking parameter that can be used to generate this invoice + StartParameter string `json:"start_parameter"` + // Three-letter ISO 4217 currency code, or “XTR” for payments in Telegram Stars + Currency string `json:"currency"` + // Total price in the smallest units of the currency (integer, not float/double). For example, for a price of US$ 1.45 pass amount = 145. See the exp parameter in currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies). + TotalAmount int64 `json:"total_amount"` +} + +// This object represents a shipping address. +type ShippingAddress struct { + // Two-letter ISO 3166-1 alpha-2 country code + CountryCode string `json:"country_code"` + // State, if applicable + State string `json:"state"` + // City + City string `json:"city"` + // First line for the address + StreetLine1 string `json:"street_line1"` + // Second line for the address + StreetLine2 string `json:"street_line2"` + // Address post code + PostCode string `json:"post_code"` +} + +// This object represents information about an order. +type OrderInfo struct { + // Optional. User name + Name string `json:"name,omitempty"` + // Optional. User's phone number + PhoneNumber string `json:"phone_number,omitempty"` + // Optional. User email + Email string `json:"email,omitempty"` + // Optional. User shipping address + ShippingAddress *ShippingAddress `json:"shipping_address,omitempty"` +} + +// This object represents one shipping option. +type ShippingOption struct { + // Shipping option identifier + ID string `json:"id"` + // Option title + Title string `json:"title"` + // List of price portions + Prices []LabeledPrice `json:"prices"` +} + +// This object contains basic information about a successful payment. Note that if the buyer initiates a chargeback with the relevant payment provider following this transaction, the funds may be debited from your balance. This is outside of Telegram's control. +type SuccessfulPayment struct { + // Three-letter ISO 4217 currency code, or “XTR” for payments in Telegram Stars + Currency string `json:"currency"` + // Total price in the smallest units of the currency (integer, not float/double). For example, for a price of US$ 1.45 pass amount = 145. See the exp parameter in currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies). + TotalAmount int64 `json:"total_amount"` + // Bot-specified invoice payload + InvoicePayload string `json:"invoice_payload"` + // Optional. Expiration date of the subscription, in Unix time; for recurring payments only + SubscriptionExpirationDate *int64 `json:"subscription_expiration_date,omitempty"` + // Optional. True, if the payment is a recurring payment for a subscription + IsRecurring *bool `json:"is_recurring,omitempty"` + // Optional. True, if the payment is the first payment for a subscription + IsFirstRecurring *bool `json:"is_first_recurring,omitempty"` + // Optional. Identifier of the shipping option chosen by the user + ShippingOptionID string `json:"shipping_option_id,omitempty"` + // Optional. Order information provided by the user + OrderInfo *OrderInfo `json:"order_info,omitempty"` + // Telegram payment identifier + TelegramPaymentChargeID string `json:"telegram_payment_charge_id"` + // Provider payment identifier + ProviderPaymentChargeID string `json:"provider_payment_charge_id"` +} + +// This object contains basic information about a refunded payment. +type RefundedPayment struct { + // Three-letter ISO 4217 currency code, or “XTR” for payments in Telegram Stars. Currently, always “XTR” + Currency string `json:"currency"` + // Total refunded price in the smallest units of the currency (integer, not float/double). For example, for a price of US$ 1.45, total_amount = 145. See the exp parameter in currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies). + TotalAmount int64 `json:"total_amount"` + // Bot-specified invoice payload + InvoicePayload string `json:"invoice_payload"` + // Telegram payment identifier + TelegramPaymentChargeID string `json:"telegram_payment_charge_id"` + // Optional. Provider payment identifier + ProviderPaymentChargeID string `json:"provider_payment_charge_id,omitempty"` +} + +// This object contains information about an incoming shipping query. +type ShippingQuery struct { + // Unique query identifier + ID string `json:"id"` + // User who sent the query + From User `json:"from"` + // Bot-specified invoice payload + InvoicePayload string `json:"invoice_payload"` + // User specified shipping address + ShippingAddress ShippingAddress `json:"shipping_address"` +} + +// This object contains information about an incoming pre-checkout query. +type PreCheckoutQuery struct { + // Unique query identifier + ID string `json:"id"` + // User who sent the query + From User `json:"from"` + // Three-letter ISO 4217 currency code, or “XTR” for payments in Telegram Stars + Currency string `json:"currency"` + // Total price in the smallest units of the currency (integer, not float/double). For example, for a price of US$ 1.45 pass amount = 145. See the exp parameter in currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies). + TotalAmount int64 `json:"total_amount"` + // Bot-specified invoice payload + InvoicePayload string `json:"invoice_payload"` + // Optional. Identifier of the shipping option chosen by the user + ShippingOptionID string `json:"shipping_option_id,omitempty"` + // Optional. Order information provided by the user + OrderInfo *OrderInfo `json:"order_info,omitempty"` +} + +// This object contains information about a paid media purchase. +type PaidMediaPurchased struct { + // User who purchased the media + From User `json:"from"` + // Bot-specified paid media payload + PaidMediaPayload string `json:"paid_media_payload"` +} + +// RevenueWithdrawalState is a union type. The following concrete variants implement +// it: +// - RevenueWithdrawalStatePending +// - RevenueWithdrawalStateSucceeded +// - RevenueWithdrawalStateFailed +// +// This object describes the state of a revenue withdrawal operation. Currently, it can be one of +type RevenueWithdrawalState interface{ isRevenueWithdrawalState() } + +// isRevenueWithdrawalState is the marker method that makes RevenueWithdrawalStatePending implement RevenueWithdrawalState. +func (*RevenueWithdrawalStatePending) isRevenueWithdrawalState() {} + +// isRevenueWithdrawalState is the marker method that makes RevenueWithdrawalStateSucceeded implement RevenueWithdrawalState. +func (*RevenueWithdrawalStateSucceeded) isRevenueWithdrawalState() {} + +// isRevenueWithdrawalState is the marker method that makes RevenueWithdrawalStateFailed implement RevenueWithdrawalState. +func (*RevenueWithdrawalStateFailed) isRevenueWithdrawalState() {} + +// UnmarshalRevenueWithdrawalState decodes a RevenueWithdrawalState from JSON by inspecting the +// "type" field and dispatching to the correct concrete type. +func UnmarshalRevenueWithdrawalState(data []byte) (RevenueWithdrawalState, error) { + var probe struct { + V string `json:"type"` + } + if err := json.Unmarshal(data, &probe); err != nil { + return nil, err + } + var v RevenueWithdrawalState + switch probe.V { + case "failed": + v = &RevenueWithdrawalStateFailed{} + case "pending": + v = &RevenueWithdrawalStatePending{} + case "succeeded": + v = &RevenueWithdrawalStateSucceeded{} + default: + return nil, fmt.Errorf("RevenueWithdrawalState: unknown type %q", probe.V) + } + if err := json.Unmarshal(data, v); err != nil { + return nil, err + } + return v, nil +} + +// The withdrawal is in progress. +type RevenueWithdrawalStatePending struct { + // Type of the state, always “pending” + Type string `json:"type"` +} + +// The withdrawal succeeded. +type RevenueWithdrawalStateSucceeded struct { + // Type of the state, always “succeeded” + Type string `json:"type"` + // Date the withdrawal was completed in Unix time + Date int64 `json:"date"` + // An HTTPS URL that can be used to see transaction details + URL string `json:"url"` +} + +// The withdrawal failed and the transaction was refunded. +type RevenueWithdrawalStateFailed struct { + // Type of the state, always “failed” + Type string `json:"type"` +} + +// Contains information about the affiliate that received a commission via this transaction. +type AffiliateInfo struct { + // Optional. The bot or the user that received an affiliate commission if it was received by a bot or a user + AffiliateUser *User `json:"affiliate_user,omitempty"` + // Optional. The chat that received an affiliate commission if it was received by a chat + AffiliateChat *Chat `json:"affiliate_chat,omitempty"` + // The number of Telegram Stars received by the affiliate for each 1000 Telegram Stars received by the bot from referred users + CommissionPerMille int64 `json:"commission_per_mille"` + // Integer amount of Telegram Stars received by the affiliate from the transaction, rounded to 0; can be negative for refunds + Amount int64 `json:"amount"` + // Optional. The number of 1/1000000000 shares of Telegram Stars received by the affiliate; from -999999999 to 999999999; can be negative for refunds + NanostarAmount *int64 `json:"nanostar_amount,omitempty"` +} + +// TransactionPartner is a union type. The following concrete variants implement +// it: +// - TransactionPartnerUser +// - TransactionPartnerChat +// - TransactionPartnerAffiliateProgram +// - TransactionPartnerFragment +// - TransactionPartnerTelegramAds +// - TransactionPartnerTelegramApi +// - TransactionPartnerOther +// +// This object describes the source of a transaction, or its recipient for outgoing transactions. Currently, it can be one of +type TransactionPartner interface{ isTransactionPartner() } + +// isTransactionPartner is the marker method that makes TransactionPartnerUser implement TransactionPartner. +func (*TransactionPartnerUser) isTransactionPartner() {} + +// isTransactionPartner is the marker method that makes TransactionPartnerChat implement TransactionPartner. +func (*TransactionPartnerChat) isTransactionPartner() {} + +// isTransactionPartner is the marker method that makes TransactionPartnerAffiliateProgram implement TransactionPartner. +func (*TransactionPartnerAffiliateProgram) isTransactionPartner() {} + +// isTransactionPartner is the marker method that makes TransactionPartnerFragment implement TransactionPartner. +func (*TransactionPartnerFragment) isTransactionPartner() {} + +// isTransactionPartner is the marker method that makes TransactionPartnerTelegramAds implement TransactionPartner. +func (*TransactionPartnerTelegramAds) isTransactionPartner() {} + +// isTransactionPartner is the marker method that makes TransactionPartnerTelegramApi implement TransactionPartner. +func (*TransactionPartnerTelegramApi) isTransactionPartner() {} + +// isTransactionPartner is the marker method that makes TransactionPartnerOther implement TransactionPartner. +func (*TransactionPartnerOther) isTransactionPartner() {} + +// UnmarshalTransactionPartner decodes a TransactionPartner from JSON by inspecting the +// "type" field and dispatching to the correct concrete type. +func UnmarshalTransactionPartner(data []byte) (TransactionPartner, error) { + var probe struct { + V string `json:"type"` + } + if err := json.Unmarshal(data, &probe); err != nil { + return nil, err + } + var v TransactionPartner + switch probe.V { + case "fragment": + v = &TransactionPartnerFragment{} + case "other": + v = &TransactionPartnerOther{} + case "telegram_ads": + v = &TransactionPartnerTelegramAds{} + case "telegram_api": + v = &TransactionPartnerTelegramApi{} + case "user": + v = &TransactionPartnerUser{} + default: + return nil, fmt.Errorf("TransactionPartner: unknown type %q", probe.V) + } + if err := json.Unmarshal(data, v); err != nil { + return nil, err + } + return v, nil +} + +// Describes a transaction with a user. +type TransactionPartnerUser struct { + // Type of the transaction partner, always “user” + Type string `json:"type"` + // Type of the transaction, currently one of “invoice_payment” for payments via invoices, “paid_media_payment” for payments for paid media, “gift_purchase” for gifts sent by the bot, “premium_purchase” for Telegram Premium subscriptions gifted by the bot, “business_account_transfer” for direct transfers from managed business accounts + TransactionType string `json:"transaction_type"` + // Information about the user + User User `json:"user"` + // Optional. Information about the affiliate that received a commission via this transaction. Can be available only for “invoice_payment” and “paid_media_payment” transactions. + Affiliate *AffiliateInfo `json:"affiliate,omitempty"` + // Optional. Bot-specified invoice payload. Can be available only for “invoice_payment” transactions. + InvoicePayload string `json:"invoice_payload,omitempty"` + // Optional. The duration of the paid subscription. Can be available only for “invoice_payment” transactions. + SubscriptionPeriod *int64 `json:"subscription_period,omitempty"` + // Optional. Information about the paid media bought by the user; for “paid_media_payment” transactions only + PaidMedia []PaidMedia `json:"paid_media,omitempty"` + // Optional. Bot-specified paid media payload. Can be available only for “paid_media_payment” transactions. + PaidMediaPayload string `json:"paid_media_payload,omitempty"` + // Optional. The gift sent to the user by the bot; for “gift_purchase” transactions only + Gift *Gift `json:"gift,omitempty"` + // Optional. Number of months the gifted Telegram Premium subscription will be active for; for “premium_purchase” transactions only + PremiumSubscriptionDuration *int64 `json:"premium_subscription_duration,omitempty"` +} + +// UnmarshalJSON decodes TransactionPartnerUser by dispatching union-typed fields +// (PaidMedia) through their concrete UnmarshalXxx helpers. +func (m *TransactionPartnerUser) UnmarshalJSON(data []byte) error { + type Alias TransactionPartnerUser + aux := &struct { + PaidMedia json.RawMessage `json:"paid_media,omitempty"` + *Alias + }{Alias: (*Alias)(m)} + if err := json.Unmarshal(data, aux); err != nil { + return err + } + + if len(aux.PaidMedia) > 0 && string(aux.PaidMedia) != "null" { + var raws []json.RawMessage + if err := json.Unmarshal(aux.PaidMedia, &raws); err != nil { + return fmt.Errorf("decoding paid_media: %w", err) + } + decoded := make([]PaidMedia, 0, len(raws)) + for i, r := range raws { + v, err := UnmarshalPaidMedia(r) + if err != nil { + return fmt.Errorf("decoding paid_media[%d]: %w", i, err) + } + decoded = append(decoded, v) + } + m.PaidMedia = decoded + + } + + return nil +} + +// Describes a transaction with a chat. +type TransactionPartnerChat struct { + // Type of the transaction partner, always “chat” + Type string `json:"type"` + // Information about the chat + Chat Chat `json:"chat"` + // Optional. The gift sent to the chat by the bot + Gift *Gift `json:"gift,omitempty"` +} + +// Describes the affiliate program that issued the affiliate commission received via this transaction. +type TransactionPartnerAffiliateProgram struct { + // Type of the transaction partner, always “affiliate_program” + Type string `json:"type"` + // Optional. Information about the bot that sponsored the affiliate program + SponsorUser *User `json:"sponsor_user,omitempty"` + // The number of Telegram Stars received by the bot for each 1000 Telegram Stars received by the affiliate program sponsor from referred users + CommissionPerMille int64 `json:"commission_per_mille"` +} + +// Describes a withdrawal transaction with Fragment. +type TransactionPartnerFragment struct { + // Type of the transaction partner, always “fragment” + Type string `json:"type"` + // Optional. State of the transaction if the transaction is outgoing + WithdrawalState RevenueWithdrawalState `json:"withdrawal_state,omitempty"` +} + +// UnmarshalJSON decodes TransactionPartnerFragment by dispatching union-typed fields +// (WithdrawalState) through their concrete UnmarshalXxx helpers. +func (m *TransactionPartnerFragment) UnmarshalJSON(data []byte) error { + type Alias TransactionPartnerFragment + aux := &struct { + WithdrawalState json.RawMessage `json:"withdrawal_state,omitempty"` + *Alias + }{Alias: (*Alias)(m)} + if err := json.Unmarshal(data, aux); err != nil { + return err + } + + if len(aux.WithdrawalState) > 0 && string(aux.WithdrawalState) != "null" { + v, err := UnmarshalRevenueWithdrawalState(aux.WithdrawalState) + if err != nil { + return fmt.Errorf("decoding withdrawal_state: %w", err) + } + m.WithdrawalState = v + + } + + return nil +} + +// Describes a withdrawal transaction to the Telegram Ads platform. +type TransactionPartnerTelegramAds struct { + // Type of the transaction partner, always “telegram_ads” + Type string `json:"type"` +} + +// Describes a transaction with payment for paid broadcasting. +type TransactionPartnerTelegramApi struct { + // Type of the transaction partner, always “telegram_api” + Type string `json:"type"` + // The number of successful requests that exceeded regular limits and were therefore billed + RequestCount int64 `json:"request_count"` +} + +// Describes a transaction with an unknown source or recipient. +type TransactionPartnerOther struct { + // Type of the transaction partner, always “other” + Type string `json:"type"` +} + +// Describes a Telegram Star transaction. Note that if the buyer initiates a chargeback with the payment provider from whom they acquired Stars (e.g., Apple, Google) following this transaction, the refunded Stars will be deducted from the bot's balance. This is outside of Telegram's control. +type StarTransaction struct { + // Unique identifier of the transaction. Coincides with the identifier of the original transaction for refund transactions. Coincides with SuccessfulPayment.telegram_payment_charge_id for successful incoming payments from users. + ID string `json:"id"` + // Integer amount of Telegram Stars transferred by the transaction + Amount int64 `json:"amount"` + // Optional. The number of 1/1000000000 shares of Telegram Stars transferred by the transaction; from 0 to 999999999 + NanostarAmount *int64 `json:"nanostar_amount,omitempty"` + // Date the transaction was created in Unix time + Date int64 `json:"date"` + // Optional. Source of an incoming transaction (e.g., a user purchasing goods or services, Fragment refunding a failed withdrawal). Only for incoming transactions + Source TransactionPartner `json:"source,omitempty"` + // Optional. Receiver of an outgoing transaction (e.g., a user for a purchase refund, Fragment for a withdrawal). Only for outgoing transactions + Receiver TransactionPartner `json:"receiver,omitempty"` +} + +// UnmarshalJSON decodes StarTransaction by dispatching union-typed fields +// (Source, Receiver) through their concrete UnmarshalXxx helpers. +func (m *StarTransaction) UnmarshalJSON(data []byte) error { + type Alias StarTransaction + aux := &struct { + Source json.RawMessage `json:"source,omitempty"` + Receiver json.RawMessage `json:"receiver,omitempty"` + *Alias + }{Alias: (*Alias)(m)} + if err := json.Unmarshal(data, aux); err != nil { + return err + } + + if len(aux.Source) > 0 && string(aux.Source) != "null" { + v, err := UnmarshalTransactionPartner(aux.Source) + if err != nil { + return fmt.Errorf("decoding source: %w", err) + } + m.Source = v + + } + + if len(aux.Receiver) > 0 && string(aux.Receiver) != "null" { + v, err := UnmarshalTransactionPartner(aux.Receiver) + if err != nil { + return fmt.Errorf("decoding receiver: %w", err) + } + m.Receiver = v + + } + + return nil +} + +// Contains a list of Telegram Star transactions. +type StarTransactions struct { + // The list of transactions + Transactions []StarTransaction `json:"transactions"` +} + +// Describes Telegram Passport data shared with the bot by the user. +type PassportData struct { + // Array with information about documents and other Telegram Passport elements that was shared with the bot + Data []EncryptedPassportElement `json:"data"` + // Encrypted credentials required to decrypt the data + Credentials EncryptedCredentials `json:"credentials"` +} + +// This object represents a file uploaded to Telegram Passport. Currently all Telegram Passport files are in JPEG format when decrypted and don't exceed 10MB. +type PassportFile struct { + // Identifier for this file, which can be used to download or reuse the file + FileID string `json:"file_id"` + // Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file. + FileUniqueID string `json:"file_unique_id"` + // File size in bytes + FileSize int64 `json:"file_size"` + // Unix time when the file was uploaded + FileDate int64 `json:"file_date"` +} + +// Describes documents or other Telegram Passport elements shared with the bot by the user. +type EncryptedPassportElement struct { + // Element type. One of “personal_details”, “passport”, “driver_license”, “identity_card”, “internal_passport”, “address”, “utility_bill”, “bank_statement”, “rental_agreement”, “passport_registration”, “temporary_registration”, “phone_number”, “email”. + Type string `json:"type"` + // Optional. Base64-encoded encrypted Telegram Passport element data provided by the user; available only for “personal_details”, “passport”, “driver_license”, “identity_card”, “internal_passport” and “address” types. Can be decrypted and verified using the accompanying EncryptedCredentials. + Data string `json:"data,omitempty"` + // Optional. User's verified phone number; available only for “phone_number” type + PhoneNumber string `json:"phone_number,omitempty"` + // Optional. User's verified email address; available only for “email” type + Email string `json:"email,omitempty"` + // Optional. Array of encrypted files with documents provided by the user; available only for “utility_bill”, “bank_statement”, “rental_agreement”, “passport_registration” and “temporary_registration” types. Files can be decrypted and verified using the accompanying EncryptedCredentials. + Files []PassportFile `json:"files,omitempty"` + // Optional. Encrypted file with the front side of the document, provided by the user; available only for “passport”, “driver_license”, “identity_card” and “internal_passport”. The file can be decrypted and verified using the accompanying EncryptedCredentials. + FrontSide *PassportFile `json:"front_side,omitempty"` + // Optional. Encrypted file with the reverse side of the document, provided by the user; available only for “driver_license” and “identity_card”. The file can be decrypted and verified using the accompanying EncryptedCredentials. + ReverseSide *PassportFile `json:"reverse_side,omitempty"` + // Optional. Encrypted file with the selfie of the user holding a document, provided by the user; available if requested for “passport”, “driver_license”, “identity_card” and “internal_passport”. The file can be decrypted and verified using the accompanying EncryptedCredentials. + Selfie *PassportFile `json:"selfie,omitempty"` + // Optional. Array of encrypted files with translated versions of documents provided by the user; available if requested for “passport”, “driver_license”, “identity_card”, “internal_passport”, “utility_bill”, “bank_statement”, “rental_agreement”, “passport_registration” and “temporary_registration” types. Files can be decrypted and verified using the accompanying EncryptedCredentials. + Translation []PassportFile `json:"translation,omitempty"` + // Base64-encoded element hash for using in PassportElementErrorUnspecified + Hash string `json:"hash"` +} + +// Describes data required for decrypting and authenticating EncryptedPassportElement. See the Telegram Passport Documentation for a complete description of the data decryption and authentication processes. +type EncryptedCredentials struct { + // Base64-encoded encrypted JSON-serialized data with unique user's payload, data hashes and secrets required for EncryptedPassportElement decryption and authentication + Data string `json:"data"` + // Base64-encoded data hash for data authentication + Hash string `json:"hash"` + // Base64-encoded secret, encrypted with the bot's public RSA key, required for data decryption + Secret string `json:"secret"` +} + +// PassportElementError is a union type. The following concrete variants implement +// it: +// - PassportElementErrorDataField +// - PassportElementErrorFrontSide +// - PassportElementErrorReverseSide +// - PassportElementErrorSelfie +// - PassportElementErrorFile +// - PassportElementErrorFiles +// - PassportElementErrorTranslationFile +// - PassportElementErrorTranslationFiles +// - PassportElementErrorUnspecified +// +// This object represents an error in the Telegram Passport element which was submitted that should be resolved by the user. It should be one of: +type PassportElementError interface{ isPassportElementError() } + +// isPassportElementError is the marker method that makes PassportElementErrorDataField implement PassportElementError. +func (*PassportElementErrorDataField) isPassportElementError() {} + +// isPassportElementError is the marker method that makes PassportElementErrorFrontSide implement PassportElementError. +func (*PassportElementErrorFrontSide) isPassportElementError() {} + +// isPassportElementError is the marker method that makes PassportElementErrorReverseSide implement PassportElementError. +func (*PassportElementErrorReverseSide) isPassportElementError() {} + +// isPassportElementError is the marker method that makes PassportElementErrorSelfie implement PassportElementError. +func (*PassportElementErrorSelfie) isPassportElementError() {} + +// isPassportElementError is the marker method that makes PassportElementErrorFile implement PassportElementError. +func (*PassportElementErrorFile) isPassportElementError() {} + +// isPassportElementError is the marker method that makes PassportElementErrorFiles implement PassportElementError. +func (*PassportElementErrorFiles) isPassportElementError() {} + +// isPassportElementError is the marker method that makes PassportElementErrorTranslationFile implement PassportElementError. +func (*PassportElementErrorTranslationFile) isPassportElementError() {} + +// isPassportElementError is the marker method that makes PassportElementErrorTranslationFiles implement PassportElementError. +func (*PassportElementErrorTranslationFiles) isPassportElementError() {} + +// isPassportElementError is the marker method that makes PassportElementErrorUnspecified implement PassportElementError. +func (*PassportElementErrorUnspecified) isPassportElementError() {} + +// Represents an issue in one of the data fields that was provided by the user. The error is considered resolved when the field's value changes. +type PassportElementErrorDataField struct { + // Error source, must be data + Source string `json:"source"` + // The section of the user's Telegram Passport which has the error, one of “personal_details”, “passport”, “driver_license”, “identity_card”, “internal_passport”, “address” + Type string `json:"type"` + // Name of the data field which has the error + FieldName string `json:"field_name"` + // Base64-encoded data hash + DataHash string `json:"data_hash"` + // Error message + Message string `json:"message"` +} + +// Represents an issue with the front side of a document. The error is considered resolved when the file with the front side of the document changes. +type PassportElementErrorFrontSide struct { + // Error source, must be front_side + Source string `json:"source"` + // The section of the user's Telegram Passport which has the issue, one of “passport”, “driver_license”, “identity_card”, “internal_passport” + Type string `json:"type"` + // Base64-encoded hash of the file with the front side of the document + FileHash string `json:"file_hash"` + // Error message + Message string `json:"message"` +} + +// Represents an issue with the reverse side of a document. The error is considered resolved when the file with reverse side of the document changes. +type PassportElementErrorReverseSide struct { + // Error source, must be reverse_side + Source string `json:"source"` + // The section of the user's Telegram Passport which has the issue, one of “driver_license”, “identity_card” + Type string `json:"type"` + // Base64-encoded hash of the file with the reverse side of the document + FileHash string `json:"file_hash"` + // Error message + Message string `json:"message"` +} + +// Represents an issue with the selfie with a document. The error is considered resolved when the file with the selfie changes. +type PassportElementErrorSelfie struct { + // Error source, must be selfie + Source string `json:"source"` + // The section of the user's Telegram Passport which has the issue, one of “passport”, “driver_license”, “identity_card”, “internal_passport” + Type string `json:"type"` + // Base64-encoded hash of the file with the selfie + FileHash string `json:"file_hash"` + // Error message + Message string `json:"message"` +} + +// Represents an issue with a document scan. The error is considered resolved when the file with the document scan changes. +type PassportElementErrorFile struct { + // Error source, must be file + Source string `json:"source"` + // The section of the user's Telegram Passport which has the issue, one of “utility_bill”, “bank_statement”, “rental_agreement”, “passport_registration”, “temporary_registration” + Type string `json:"type"` + // Base64-encoded file hash + FileHash string `json:"file_hash"` + // Error message + Message string `json:"message"` +} + +// Represents an issue with a list of scans. The error is considered resolved when the list of files containing the scans changes. +type PassportElementErrorFiles struct { + // Error source, must be files + Source string `json:"source"` + // The section of the user's Telegram Passport which has the issue, one of “utility_bill”, “bank_statement”, “rental_agreement”, “passport_registration”, “temporary_registration” + Type string `json:"type"` + // List of base64-encoded file hashes + FileHashes []string `json:"file_hashes"` + // Error message + Message string `json:"message"` +} + +// Represents an issue with one of the files that constitute the translation of a document. The error is considered resolved when the file changes. +type PassportElementErrorTranslationFile struct { + // Error source, must be translation_file + Source string `json:"source"` + // Type of element of the user's Telegram Passport which has the issue, one of “passport”, “driver_license”, “identity_card”, “internal_passport”, “utility_bill”, “bank_statement”, “rental_agreement”, “passport_registration”, “temporary_registration” + Type string `json:"type"` + // Base64-encoded file hash + FileHash string `json:"file_hash"` + // Error message + Message string `json:"message"` +} + +// Represents an issue with the translated version of a document. The error is considered resolved when a file with the document translation change. +type PassportElementErrorTranslationFiles struct { + // Error source, must be translation_files + Source string `json:"source"` + // Type of element of the user's Telegram Passport which has the issue, one of “passport”, “driver_license”, “identity_card”, “internal_passport”, “utility_bill”, “bank_statement”, “rental_agreement”, “passport_registration”, “temporary_registration” + Type string `json:"type"` + // List of base64-encoded file hashes + FileHashes []string `json:"file_hashes"` + // Error message + Message string `json:"message"` +} + +// Represents an issue in an unspecified place. The error is considered resolved when new data is added. +type PassportElementErrorUnspecified struct { + // Error source, must be unspecified + Source string `json:"source"` + // Type of element of the user's Telegram Passport which has the issue + Type string `json:"type"` + // Base64-encoded element hash + ElementHash string `json:"element_hash"` + // Error message + Message string `json:"message"` +} + +// This object represents a game. Use BotFather to create and edit games, their short names will act as unique identifiers. +type Game struct { + // Title of the game + Title string `json:"title"` + // Description of the game + Description string `json:"description"` + // Photo that will be displayed in the game message in chats. + Photo []PhotoSize `json:"photo"` + // Optional. Brief description of the game or high scores included in the game message. Can be automatically edited to include current high scores for the game when the bot calls setGameScore, or manually edited using editMessageText. 0-4096 characters. + Text string `json:"text,omitempty"` + // Optional. Special entities that appear in text, such as usernames, URLs, bot commands, etc. + TextEntities []MessageEntity `json:"text_entities,omitempty"` + // Optional. Animation that will be displayed in the game message in chats. Upload via BotFather + Animation *Animation `json:"animation,omitempty"` +} + +// A placeholder, currently holds no information. Use BotFather to set up your game. +type CallbackGame struct { +} + +// This object represents one row of the high scores table for a game. +// And that's about all we've got for now.If you've got any questions, please check out our Bot FAQ » +type GameHighScore struct { + // Position in high score table for the game + Position int64 `json:"position"` + // User + User User `json:"user"` + // Score + Score int64 `json:"score"` +} diff --git a/client/call.go b/client/call.go new file mode 100644 index 0000000..1c20c77 --- /dev/null +++ b/client/call.go @@ -0,0 +1,171 @@ +package client + +import ( + "bytes" + "context" + "errors" + "github.com/goccy/go-json" + "io" + "net/http" + "reflect" +) + +// Call is the single point through which every Telegram Bot API method +// invocation flows. It marshals the request, signs the URL with the bot +// token, dispatches via HTTPDoer, decodes the Result envelope, and +// translates non-OK responses into typed errors. +// +// It is generic over both request and response types. Methods with no +// parameters may pass a nil Req; the helper sends "{}" in that case so +// Telegram receives a syntactically valid empty object. +// +// Call is exported because the api package (which lives outside this one) +// invokes it from generated method wrappers. User code should not normally +// call it directly — use the typed wrappers in package api instead. +func Call[Req any, Resp any](ctx context.Context, b *Bot, method string, req Req) (Resp, error) { + var zero Resp + + if mp, ok := any(req).(multipartRequest); ok { + if mp == nil { + return zero, &ParseError{Err: errors.New("client: nil multipart request")} + } + if mp.HasFile() { + return callMultipart[Resp](ctx, b, method, mp) + } + } + + body, err := encodeJSONBody(b.codec, req) + if err != nil { + return zero, err + } + + url := b.base + "/bot" + b.token + "/" + method + httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, url, body) + if err != nil { + return zero, &NetworkError{Err: err} + } + httpReq.Header.Set("Content-Type", "application/json") + httpReq.Header.Set("Accept", "application/json") + + resp, err := b.http.Do(httpReq) + if err != nil { + // Surface ctx errors faithfully so callers can errors.Is(err, ctx.Err()). + if ctxErr := ctx.Err(); ctxErr != nil { + return zero, ctxErr + } + return zero, &NetworkError{Err: err} + } + defer func() { _ = resp.Body.Close() }() + + raw, err := io.ReadAll(resp.Body) + if err != nil { + return zero, &NetworkError{Err: err} + } + + return decodeResult[Resp](b.codec, raw) +} + +// CallRaw is like Call but returns the raw JSON of the result field +// instead of decoding it into a typed value. Generated method wrappers +// for sealed-interface return types (ChatMember, MenuButton, etc.) use +// this helper, then dispatch through the union's UnmarshalXxx function. +// +// CallRaw still translates non-OK responses into *APIError just like Call. +func CallRaw[Req any](ctx context.Context, b *Bot, method string, req Req) (json.RawMessage, error) { + if mp, ok := any(req).(multipartRequest); ok { + if mp == nil { + return nil, &ParseError{Err: errors.New("client: nil multipart request")} + } + if mp.HasFile() { + return callMultipartRaw(ctx, b, method, mp) + } + } + + body, err := encodeJSONBody(b.codec, req) + if err != nil { + return nil, err + } + + url := b.base + "/bot" + b.token + "/" + method + httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, url, body) + if err != nil { + return nil, &NetworkError{Err: err} + } + httpReq.Header.Set("Content-Type", "application/json") + httpReq.Header.Set("Accept", "application/json") + + resp, err := b.http.Do(httpReq) + if err != nil { + if ctxErr := ctx.Err(); ctxErr != nil { + return nil, ctxErr + } + return nil, &NetworkError{Err: err} + } + defer func() { _ = resp.Body.Close() }() + + raw, err := io.ReadAll(resp.Body) + if err != nil { + return nil, &NetworkError{Err: err} + } + + return decodeResultRaw(b.codec, raw) +} + +// decodeResultRaw is decodeResult's sibling that returns the raw result +// field instead of typing it. +func decodeResultRaw(codec Codec, raw []byte) (json.RawMessage, error) { + var env Result[json.RawMessage] + if err := codec.Unmarshal(raw, &env); err != nil { + return nil, &ParseError{Err: err, Body: copyBody(raw)} + } + if !env.OK { + return nil, mapAPIError(env.ErrorCode, env.Description, env.Parameters) + } + return env.Result, nil +} + +// encodeJSONBody marshals req to a JSON body. A nil interface or nil +// pointer req yields "{}" so Telegram receives a valid empty object. +func encodeJSONBody(codec Codec, req any) (io.Reader, error) { + if req == nil || isNilPointer(req) { + return bytes.NewBufferString("{}"), nil + } + data, err := codec.Marshal(req) + if err != nil { + return nil, &ParseError{Err: err} + } + return bytes.NewReader(data), nil +} + +// decodeResult unmarshals raw into Result[Resp] and translates non-OK +// responses into *APIError. +func decodeResult[Resp any](codec Codec, raw []byte) (Resp, error) { + var zero Resp + var env Result[Resp] + if err := codec.Unmarshal(raw, &env); err != nil { + return zero, &ParseError{Err: err, Body: copyBody(raw)} + } + if !env.OK { + return zero, mapAPIError(env.ErrorCode, env.Description, env.Parameters) + } + return env.Result, nil +} + +// isNilPointer returns true when v is a typed nil pointer (the interface +// itself is non-nil because it carries a type, but the underlying value +// is nil). One reflect call per request; not on a hot path that demands +// allocation-freedom. +func isNilPointer(v any) bool { + rv := reflect.ValueOf(v) + return rv.Kind() == reflect.Ptr && rv.IsNil() +} + +func copyBody(b []byte) []byte { + const max = 4096 + if len(b) > max { + b = b[:max] + } + out := make([]byte, len(b)) + copy(out, b) + return out +} diff --git a/client/call_test.go b/client/call_test.go new file mode 100644 index 0000000..6a9bf2b --- /dev/null +++ b/client/call_test.go @@ -0,0 +1,121 @@ +package client + +import ( + "bytes" + "context" + "errors" + "io" + "net/http" + "strings" + "testing" + + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" +) + +type mockDoer struct{ mock.Mock } + +func (m *mockDoer) Do(r *http.Request) (*http.Response, error) { + args := m.Called(r) + if v := args.Get(0); v != nil { + return v.(*http.Response), args.Error(1) + } + return nil, args.Error(1) +} + +func newResp(status int, body string) *http.Response { + return &http.Response{ + StatusCode: status, + Body: io.NopCloser(bytes.NewBufferString(body)), + Header: http.Header{"Content-Type": []string{"application/json"}}, + } +} + +type echoReq struct { + ChatID int64 `json:"chat_id"` + Text string `json:"text"` +} +type echoResp struct { + MessageID int64 `json:"message_id"` +} + +func TestCall_Success(t *testing.T) { + m := &mockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + if !strings.HasSuffix(r.URL.Path, "/bot123:abc/sendEcho") { + return false + } + buf := new(bytes.Buffer) + _, _ = buf.ReadFrom(r.Body) + return strings.Contains(buf.String(), `"chat_id":42`) + })).Return(newResp(200, `{"ok":true,"result":{"message_id":7}}`), nil) + + b := New("123:abc", WithHTTPClient(m)) + out, err := Call[*echoReq, *echoResp](context.Background(), b, "sendEcho", &echoReq{ChatID: 42, Text: "hi"}) + require.NoError(t, err) + require.Equal(t, int64(7), out.MessageID) + m.AssertExpectations(t) +} + +func TestCall_APIError(t *testing.T) { + m := &mockDoer{} + m.On("Do", mock.Anything).Return( + newResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests: retry after 3","parameters":{"retry_after":3}}`), nil) + + b := New("t", WithHTTPClient(m)) + _, err := Call[*echoReq, *echoResp](context.Background(), b, "x", &echoReq{}) + require.Error(t, err) + var ae *APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) + require.True(t, errors.Is(err, ErrTooManyRequests)) +} + +func TestCall_NetworkError(t *testing.T) { + m := &mockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial timeout")) + + b := New("t", WithHTTPClient(m)) + _, err := Call[*echoReq, *echoResp](context.Background(), b, "x", &echoReq{}) + require.Error(t, err) + var ne *NetworkError + require.ErrorAs(t, err, &ne) +} + +func TestCall_ParseError(t *testing.T) { + m := &mockDoer{} + m.On("Do", mock.Anything).Return(newResp(200, `not json`), nil) + + b := New("t", WithHTTPClient(m)) + _, err := Call[*echoReq, *echoResp](context.Background(), b, "x", &echoReq{}) + require.Error(t, err) + var pe *ParseError + require.ErrorAs(t, err, &pe) +} + +func TestCall_ContextCanceled(t *testing.T) { + m := &mockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + b := New("t", WithHTTPClient(m)) + _, err := Call[*echoReq, *echoResp](ctx, b, "x", &echoReq{}) + require.ErrorIs(t, err, context.Canceled) +} + +func TestCall_NilRequest(t *testing.T) { + // Methods with no params (e.g. getMe) may pass a nil Req value. + m := &mockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + buf := new(bytes.Buffer) + _, _ = buf.ReadFrom(r.Body) + return buf.String() == "{}" + })).Return(newResp(200, `{"ok":true,"result":{"message_id":0}}`), nil) + + b := New("t", WithHTTPClient(m)) + _, err := Call[*echoReq, *echoResp](context.Background(), b, "x", nil) + require.NoError(t, err) +} diff --git a/client/client.go b/client/client.go new file mode 100644 index 0000000..49a4874 --- /dev/null +++ b/client/client.go @@ -0,0 +1,48 @@ +package client + +const defaultBaseURL = "https://api.telegram.org" + +// Bot is the Telegram Bot API client. Construct via New. All API methods +// (declared in package api) hang off *Bot via thin wrappers around call. +type Bot struct { + token string + base string + http HTTPDoer + codec Codec + logger Logger +} + +// Token returns the bot token. Exposed for advanced use cases (custom +// transports, manual URL building); ordinary code does not need it. +func (b *Bot) Token() string { return b.token } + +// BaseURL returns the configured Telegram API base URL. +func (b *Bot) BaseURL() string { return b.base } + +// HTTP returns the underlying HTTPDoer. Exposed for adapters that need +// to share connection pools or for diagnostic checks. +func (b *Bot) HTTP() HTTPDoer { return b.http } + +// Codec returns the configured Codec. +func (b *Bot) Codec() Codec { return b.codec } + +// Logger returns the configured Logger. +func (b *Bot) Logger() Logger { return b.logger } + +// New constructs a Bot with the given token and optional configuration. +// The default HTTP client is tuned for long-poll workloads (see +// NewDefaultHTTPDoer); the default codec wraps encoding/json; the default +// logger discards records. +func New(token string, opts ...Option) *Bot { + b := &Bot{ + token: token, + base: defaultBaseURL, + http: NewDefaultHTTPDoer(), + codec: DefaultCodec{}, + logger: NoopLogger{}, + } + for _, o := range opts { + o(b) + } + return b +} diff --git a/client/client_test.go b/client/client_test.go new file mode 100644 index 0000000..1430828 --- /dev/null +++ b/client/client_test.go @@ -0,0 +1,42 @@ +package client + +import ( + "net/http" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestNew_Defaults(t *testing.T) { + b := New("123:abc") + require.Equal(t, "123:abc", b.token) + require.Equal(t, defaultBaseURL, b.base) + require.NotNil(t, b.http) + require.NotNil(t, b.codec) + require.NotNil(t, b.logger) +} + +func TestNew_OptionsApplied(t *testing.T) { + custom := &http.Client{} + type fakeCodec struct{ DefaultCodec } + c := fakeCodec{} + + b := New("t", + WithHTTPClient(custom), + WithCodec(c), + WithBaseURL("https://example.test"), + WithLogger(NoopLogger{}), + ) + require.Same(t, custom, b.http) + require.Equal(t, c, b.codec) + require.Equal(t, "https://example.test", b.base) +} + +func TestResultRoundTrip(t *testing.T) { + in := Result[int64]{OK: true, Result: 42} + data, err := DefaultCodec{}.Marshal(in) + require.NoError(t, err) + var out Result[int64] + require.NoError(t, DefaultCodec{}.Unmarshal(data, &out)) + require.Equal(t, in, out) +} diff --git a/client/codec.go b/client/codec.go new file mode 100644 index 0000000..f62e15c --- /dev/null +++ b/client/codec.go @@ -0,0 +1,22 @@ +// Package client provides HTTP client primitives for the Telegram Bot API. +package client + +import "github.com/goccy/go-json" + +// Codec encodes/decodes JSON payloads exchanged with the Telegram Bot API. +// The default implementation wraps goccy/go-json. Users may plug in +// bytedance/sonic or any compatible encoder by passing +// WithCodec to New. +type Codec interface { + Marshal(v any) ([]byte, error) + Unmarshal(data []byte, v any) error +} + +// DefaultCodec wraps goccy/go-json. It is the zero-value safe default. +type DefaultCodec struct{} + +// Marshal calls json.Marshal. +func (DefaultCodec) Marshal(v any) ([]byte, error) { return json.Marshal(v) } + +// Unmarshal calls json.Unmarshal. +func (DefaultCodec) Unmarshal(data []byte, v any) error { return json.Unmarshal(data, v) } diff --git a/client/codec_test.go b/client/codec_test.go new file mode 100644 index 0000000..11ee0d4 --- /dev/null +++ b/client/codec_test.go @@ -0,0 +1,29 @@ +package client + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +func TestDefaultCodec_RoundTrip(t *testing.T) { + c := DefaultCodec{} + type payload struct { + Name string `json:"name"` + N int `json:"n"` + } + in := payload{Name: "x", N: 7} + data, err := c.Marshal(in) + require.NoError(t, err) + require.JSONEq(t, `{"name":"x","n":7}`, string(data)) + + var out payload + require.NoError(t, c.Unmarshal(data, &out)) + require.Equal(t, in, out) +} + +func TestDefaultCodec_UnmarshalError(t *testing.T) { + var v map[string]any + err := DefaultCodec{}.Unmarshal([]byte(`not json`), &v) + require.Error(t, err) +} diff --git a/client/errors.go b/client/errors.go new file mode 100644 index 0000000..9ed0c7e --- /dev/null +++ b/client/errors.go @@ -0,0 +1,107 @@ +package client + +import ( + "errors" + "fmt" + "strings" + "time" +) + +// APIError represents a non-OK Telegram Bot API response. +// It satisfies error and unwraps to a sentinel (ErrUnauthorized, etc.) +// where the description matches a known prefix, enabling errors.Is checks. +type APIError struct { + Code int + Description string + Parameters *ResponseParameters + + // sentinel, if non-nil, is the wrapped sentinel error returned by + // Unwrap. It is set by mapAPIError based on Code+Description. + sentinel error +} + +// Error implements error. +func (e *APIError) Error() string { + return fmt.Sprintf("telegram: %d %s", e.Code, e.Description) +} + +// Unwrap returns the matched sentinel error, if any. +func (e *APIError) Unwrap() error { return e.sentinel } + +// IsRetryable returns true for transient HTTP statuses (429, 5xx). +func (e *APIError) IsRetryable() bool { + return e.Code == 429 || (e.Code >= 500 && e.Code < 600) +} + +// RetryAfter returns the recommended back-off duration. It honours the +// Telegram-supplied retry_after parameter; if absent, returns 0. +func (e *APIError) RetryAfter() time.Duration { + if e.Parameters == nil { + return 0 + } + return time.Duration(e.Parameters.RetryAfter) * time.Second +} + +// NetworkError wraps a transport-level failure (DNS, TCP, TLS, timeout +// short of an HTTP response). +type NetworkError struct{ Err error } + +func (e *NetworkError) Error() string { return "telegram: network: " + redactToken(e.Err.Error()) } + +func (e *NetworkError) Unwrap() error { return e.Err } + +// ParseError wraps a JSON decode failure on a response body. Body is +// retained (truncated to 4 KiB); Error() displays up to 256 bytes for diagnostics. +type ParseError struct { + Err error + Body []byte +} + +func (e *ParseError) Error() string { + body := e.Body + if len(body) > 256 { + body = body[:256] + } + return fmt.Sprintf("telegram: parse: %s (body=%q)", redactToken(e.Err.Error()), body) +} + +func (e *ParseError) Unwrap() error { return e.Err } + +// Sentinel errors returned via APIError.Unwrap when the description matches. +// Compare with errors.Is. +var ( + ErrUnauthorized = errors.New("telegram: unauthorized") + ErrChatNotFound = errors.New("telegram: chat not found") + ErrMessageNotModified = errors.New("telegram: message is not modified") + ErrTooManyRequests = errors.New("telegram: too many requests") + ErrBadRequest = errors.New("telegram: bad request") + ErrForbidden = errors.New("telegram: forbidden") + ErrUserNotFound = errors.New("telegram: user not found") + ErrMessageNotFound = errors.New("telegram: message not found") +) + +// mapAPIError builds an *APIError and attaches the appropriate sentinel +// based on Code+Description. It is the single point where wire-level +// failures are translated into the Go error taxonomy. +func mapAPIError(code int, description string, params *ResponseParameters) *APIError { + e := &APIError{Code: code, Description: description, Parameters: params} + switch { + case code == 401: + e.sentinel = ErrUnauthorized + case code == 403: + e.sentinel = ErrForbidden + case code == 429: + e.sentinel = ErrTooManyRequests + case code == 400 && strings.Contains(description, "user not found"): + e.sentinel = ErrUserNotFound + case code == 400 && strings.Contains(description, "message to") && strings.Contains(description, "not found"): + e.sentinel = ErrMessageNotFound + case code == 400 && strings.Contains(description, "chat not found"): + e.sentinel = ErrChatNotFound + case code == 400 && strings.Contains(description, "message is not modified"): + e.sentinel = ErrMessageNotModified + case code == 400: + e.sentinel = ErrBadRequest + } + return e +} diff --git a/client/errors_test.go b/client/errors_test.go new file mode 100644 index 0000000..81537a1 --- /dev/null +++ b/client/errors_test.go @@ -0,0 +1,58 @@ +package client + +import ( + "errors" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +func TestAPIError_FieldsAndMethods(t *testing.T) { + e := &APIError{ + Code: 429, + Description: "Too Many Requests: retry after 5", + Parameters: &ResponseParameters{RetryAfter: 5}, + } + require.Equal(t, "telegram: 429 Too Many Requests: retry after 5", e.Error()) + require.True(t, e.IsRetryable()) + require.Equal(t, 5*time.Second, e.RetryAfter()) +} + +func TestAPIError_Sentinels(t *testing.T) { + cases := []struct { + code int + desc string + sentinel error + }{ + {401, "Unauthorized", ErrUnauthorized}, + {400, "Bad Request: chat not found", ErrChatNotFound}, + {400, "Bad Request: message is not modified", ErrMessageNotModified}, + {429, "Too Many Requests: retry after 1", ErrTooManyRequests}, + {400, "Bad Request: user not found", ErrUserNotFound}, + {400, "Bad Request: message to delete not found", ErrMessageNotFound}, + } + for _, c := range cases { + t.Run(c.desc, func(t *testing.T) { + e := mapAPIError(c.code, c.desc, nil) + require.True(t, errors.Is(e, c.sentinel), "expected %v to wrap %v", e, c.sentinel) + }) + } +} + +func TestAPIError_IsRetryable(t *testing.T) { + require.True(t, (&APIError{Code: 500}).IsRetryable()) + require.True(t, (&APIError{Code: 502}).IsRetryable()) + require.True(t, (&APIError{Code: 429}).IsRetryable()) + require.False(t, (&APIError{Code: 400}).IsRetryable()) + require.False(t, (&APIError{Code: 401}).IsRetryable()) +} + +func TestNetworkAndParseErrorWrapping(t *testing.T) { + inner := errors.New("dial tcp: timeout") + ne := &NetworkError{Err: inner} + require.ErrorIs(t, ne, inner) + + pe := &ParseError{Err: errors.New("unexpected EOF"), Body: []byte("garbage")} + require.Contains(t, pe.Error(), "garbage") +} diff --git a/client/extra_test.go b/client/extra_test.go new file mode 100644 index 0000000..542770f --- /dev/null +++ b/client/extra_test.go @@ -0,0 +1,226 @@ +package client + +import ( + "bytes" + "context" + "errors" + "io" + "net/http" + "testing" + "time" + + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" +) + +// --------------------------------------------------------------------------- +// client.go option getters +// --------------------------------------------------------------------------- + +func TestBot_Getters(t *testing.T) { + b := New("mytoken", + WithBaseURL("http://localhost:9999"), + WithCodec(DefaultCodec{}), + WithLogger(NoopLogger{}), + ) + require.Equal(t, "mytoken", b.Token()) + require.Equal(t, "http://localhost:9999", b.BaseURL()) + require.NotNil(t, b.HTTP()) + require.NotNil(t, b.Codec()) + require.NotNil(t, b.Logger()) +} + +func TestWithLogger_NilBecomesNoop(t *testing.T) { + b := New("t", WithLogger(nil)) + require.IsType(t, NoopLogger{}, b.Logger()) +} + +func TestNoopLogger_AllMethods(t *testing.T) { + l := NoopLogger{} + // None of these should panic. + l.Debug("msg") + l.Info("msg", "k", "v") + l.Warn("msg") + l.Error("msg", "err", "oops") +} + +// --------------------------------------------------------------------------- +// RetryOption setters +// --------------------------------------------------------------------------- + +func TestRetryOptions_Applied(t *testing.T) { + d := NewRetryDoer(nil, + WithMaxAttempts(7), + WithBaseBackoff(1*time.Second), + WithMaxBackoff(60*time.Second), + WithBackoffFactor(3.0), + WithJitter(0.5), + ) + require.Equal(t, 7, d.maxAttempts) + require.Equal(t, 1*time.Second, d.base) + require.Equal(t, 60*time.Second, d.max) + require.Equal(t, 3.0, d.factor) + require.Equal(t, 0.5, d.jitter) +} + +// --------------------------------------------------------------------------- +// RetryDoer.delay — override path +// --------------------------------------------------------------------------- + +func TestRetryDoer_DelayOverride(t *testing.T) { + d := NewRetryDoer(nil) + got := d.delay(1, 5*time.Second) + require.Equal(t, 5*time.Second, got) +} + +func TestRetryDoer_DelayExponential(t *testing.T) { + d := NewRetryDoer(nil, + WithBaseBackoff(100*time.Millisecond), + WithMaxBackoff(10*time.Second), + WithJitter(0), // no jitter for deterministic test + WithBackoffFactor(2.0), + ) + d1 := d.delay(1, 0) + d2 := d.delay(2, 0) + require.Greater(t, int64(d2), int64(d1), "backoff should grow") +} + +func TestRetryDoer_DelayMaxCap(t *testing.T) { + d := NewRetryDoer(nil, + WithBaseBackoff(1*time.Second), + WithMaxBackoff(2*time.Second), + WithJitter(0), + WithBackoffFactor(100.0), + ) + delay := d.delay(10, 0) + require.LessOrEqual(t, delay, 2*time.Second) +} + +// --------------------------------------------------------------------------- +// errors.go — RetryAfter nil parameters + ParseError.Unwrap +// --------------------------------------------------------------------------- + +func TestAPIError_RetryAfterNilParams(t *testing.T) { + e := &APIError{Code: 429, Description: "Too Many Requests", Parameters: nil} + require.Equal(t, time.Duration(0), e.RetryAfter()) +} + +func TestParseError_Unwrap(t *testing.T) { + inner := errors.New("decode error") + pe := &ParseError{Err: inner, Body: []byte("body")} + require.ErrorIs(t, pe, inner) +} + +func TestParseError_LongBodyTruncated(t *testing.T) { + body := bytes.Repeat([]byte("x"), 1000) + pe := &ParseError{Err: errors.New("e"), Body: body} + msg := pe.Error() + // Error() truncates body to 256 for display — should not include all 1000 chars + require.Less(t, len(msg), 800, "should truncate body in Error()") +} + +func TestNetworkError_Unwrap(t *testing.T) { + inner := errors.New("tcp error") + ne := &NetworkError{Err: inner} + require.ErrorIs(t, ne, inner) +} + +// --------------------------------------------------------------------------- +// mapAPIError — missing sentinel branches (generic 400, unmapped 500) +// --------------------------------------------------------------------------- + +func TestMapAPIError_Generic400(t *testing.T) { + e := mapAPIError(400, "Bad Request: some unknown thing", nil) + require.True(t, errors.Is(e, ErrBadRequest)) +} + +func TestMapAPIError_Unmapped500(t *testing.T) { + e := mapAPIError(500, "Internal Server Error", nil) + require.Nil(t, e.sentinel) + require.Equal(t, 500, e.Code) +} + +func TestMapAPIError_403(t *testing.T) { + e := mapAPIError(403, "Forbidden: bot was blocked", nil) + require.True(t, errors.Is(e, ErrForbidden)) +} + +// --------------------------------------------------------------------------- +// callMultipart — ctx cancelled +// --------------------------------------------------------------------------- + +func TestCallMultipart_ContextCancelled(t *testing.T) { + // A doer that blocks then returns context error. + blocker := &extraBlockingDoer{done: make(chan struct{})} + + b := New("t", WithHTTPClient(blocker)) + ctx, cancel := context.WithCancel(context.Background()) + + mp := &extraFakeMultipartReq{ + fields: map[string]string{"chat_id": "1"}, + files: []MultipartFile{ + {FieldName: "document", Filename: "f.txt", Reader: bytes.NewReader([]byte("data"))}, + }, + } + + go func() { + time.Sleep(10 * time.Millisecond) + cancel() + close(blocker.done) + }() + + _, err := callMultipart[*struct{}](ctx, b, "sendDocument", mp) + require.Error(t, err) +} + +type extraBlockingDoer struct{ done chan struct{} } + +func (b *extraBlockingDoer) Do(r *http.Request) (*http.Response, error) { + <-b.done + return nil, r.Context().Err() +} + +type extraFakeMultipartReq struct { + fields map[string]string + files []MultipartFile +} + +func (f *extraFakeMultipartReq) HasFile() bool { return len(f.files) > 0 } +func (f *extraFakeMultipartReq) MultipartFiles() []MultipartFile { return f.files } +func (f *extraFakeMultipartReq) MultipartFields() map[string]string { return f.fields } + +// --------------------------------------------------------------------------- +// copyBody size cap +// --------------------------------------------------------------------------- + +func TestCopyBody_LargeBodyCapped(t *testing.T) { + big := bytes.Repeat([]byte("a"), 8000) + out := copyBody(big) + require.Len(t, out, 4096) +} + +func TestCopyBody_SmallBody(t *testing.T) { + small := []byte("hello") + out := copyBody(small) + require.Equal(t, small, out) +} + +// --------------------------------------------------------------------------- +// Call — 5xx non-200 HTTP status (transport level) +// --------------------------------------------------------------------------- + +func TestCall_5xxHTTPStatus(t *testing.T) { + m := &mockDoer{} + m.On("Do", mock.Anything).Return(&http.Response{ + StatusCode: 500, + Body: io.NopCloser(bytes.NewBufferString(`{"ok":false,"error_code":500,"description":"Internal"}`)), + Header: http.Header{"Content-Type": []string{"application/json"}}, + }, nil) + + b := New("t", WithHTTPClient(m)) + _, err := Call[*echoReq, *echoResp](context.Background(), b, "x", &echoReq{}) + require.Error(t, err) + var ae *APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) +} diff --git a/client/httpclient.go b/client/httpclient.go new file mode 100644 index 0000000..dc8d844 --- /dev/null +++ b/client/httpclient.go @@ -0,0 +1,40 @@ +package client + +import ( + "net" + "net/http" + "time" +) + +// HTTPDoer abstracts the HTTP transport. The default is a net/http client +// tuned for Telegram's long-poll usage. Users may plug in valyala/fasthttp +// (via an adapter), or any custom retry/circuit-breaker client by passing +// WithHTTPClient to New. +type HTTPDoer interface { + Do(req *http.Request) (*http.Response, error) +} + +// NewDefaultHTTPDoer returns an *http.Client with sensible defaults for +// Telegram Bot API usage: +// - 60s overall timeout (longer than typical long-poll Timeout=30s). +// - Connection pooling sized for a small number of long-lived hosts. +// - HTTP/2 enabled (default in net/http). +func NewDefaultHTTPDoer() *http.Client { + t := &http.Transport{ + Proxy: http.ProxyFromEnvironment, + DialContext: (&net.Dialer{ + Timeout: 10 * time.Second, + KeepAlive: 30 * time.Second, + }).DialContext, + MaxIdleConns: 16, + MaxIdleConnsPerHost: 8, + IdleConnTimeout: 90 * time.Second, + TLSHandshakeTimeout: 10 * time.Second, + ExpectContinueTimeout: 1 * time.Second, + ForceAttemptHTTP2: true, + } + return &http.Client{ + Transport: t, + Timeout: 60 * time.Second, + } +} diff --git a/client/httpclient_test.go b/client/httpclient_test.go new file mode 100644 index 0000000..bc04c27 --- /dev/null +++ b/client/httpclient_test.go @@ -0,0 +1,24 @@ +package client + +import ( + "net/http" + "net/http/httptest" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestDefaultHTTPClient_Do(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusTeapot) + })) + t.Cleanup(srv.Close) + + doer := NewDefaultHTTPDoer() + req, err := http.NewRequest(http.MethodGet, srv.URL, nil) + require.NoError(t, err) + resp, err := doer.Do(req) + require.NoError(t, err) + defer resp.Body.Close() + require.Equal(t, http.StatusTeapot, resp.StatusCode) +} diff --git a/client/logger.go b/client/logger.go new file mode 100644 index 0000000..a0f6e85 --- /dev/null +++ b/client/logger.go @@ -0,0 +1,19 @@ +package client + +// Logger is a slog-shaped logging interface. Users pass any compatible +// implementation via WithLogger. The default is NoopLogger, which discards +// everything. +type Logger interface { + Debug(msg string, attrs ...any) + Info(msg string, attrs ...any) + Warn(msg string, attrs ...any) + Error(msg string, attrs ...any) +} + +// NoopLogger discards all log records. It is the zero-value safe default. +type NoopLogger struct{} + +func (NoopLogger) Debug(string, ...any) {} +func (NoopLogger) Info(string, ...any) {} +func (NoopLogger) Warn(string, ...any) {} +func (NoopLogger) Error(string, ...any) {} diff --git a/client/logger_test.go b/client/logger_test.go new file mode 100644 index 0000000..1fee472 --- /dev/null +++ b/client/logger_test.go @@ -0,0 +1,11 @@ +package client + +import "testing" + +func TestNoopLogger_DoesNotPanic(t *testing.T) { + var l Logger = NoopLogger{} + l.Debug("d", "k", "v") + l.Info("i") + l.Warn("w") + l.Error("e") +} diff --git a/client/multipart.go b/client/multipart.go new file mode 100644 index 0000000..722d7ad --- /dev/null +++ b/client/multipart.go @@ -0,0 +1,146 @@ +package client + +import ( + "context" + "github.com/goccy/go-json" + "io" + "mime/multipart" + "net/http" +) + +// multipartRequest is implemented by request structs that may carry an +// InputFile. The codegen emits this interface for any method whose IR +// MethodDecl.HasFiles is true. +// +// HasFile returns true if at least one file field is set; if false, the +// request is sent as plain JSON via the regular Call path. +// +// MultipartFiles returns one entry per file field that should be uploaded. +// The accompanying scalar/object fields are returned by MultipartFields. +type multipartRequest interface { + HasFile() bool + MultipartFiles() []MultipartFile + MultipartFields() map[string]string +} + +// MultipartFile describes a single file part in a multipart upload. +type MultipartFile struct { + FieldName string + Filename string + Reader io.Reader +} + +// callMultipart performs a multipart/form-data POST. It is invoked by Call +// when the request implements multipartRequest and HasFile() is true. +func callMultipart[Resp any](ctx context.Context, b *Bot, method string, mp multipartRequest) (Resp, error) { + var zero Resp + + pr, pw := io.Pipe() + mw := multipart.NewWriter(pw) + + // Stream-write the multipart body in a goroutine so we don't buffer + // large files in memory. + go func() { + defer func() { _ = pw.Close() }() + defer func() { _ = mw.Close() }() + for k, v := range mp.MultipartFields() { + if err := mw.WriteField(k, v); err != nil { + _ = pw.CloseWithError(err) + return + } + } + for _, f := range mp.MultipartFiles() { + part, err := mw.CreateFormFile(f.FieldName, f.Filename) + if err != nil { + _ = pw.CloseWithError(err) + return + } + if _, err := io.Copy(part, f.Reader); err != nil { + _ = pw.CloseWithError(err) + return + } + } + }() + + url := b.base + "/bot" + b.token + "/" + method + req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, pr) + if err != nil { + _ = pr.CloseWithError(err) + return zero, &NetworkError{Err: err} + } + req.Header.Set("Content-Type", mw.FormDataContentType()) + req.Header.Set("Accept", "application/json") + + resp, err := b.http.Do(req) + if err != nil { + _ = pr.CloseWithError(err) + if ctxErr := ctx.Err(); ctxErr != nil { + return zero, ctxErr + } + return zero, &NetworkError{Err: err} + } + defer func() { _ = resp.Body.Close() }() + + raw, err := io.ReadAll(resp.Body) + if err != nil { + _ = pr.CloseWithError(err) + return zero, &NetworkError{Err: err} + } + return decodeResult[Resp](b.codec, raw) +} + +// callMultipartRaw is callMultipart's sibling that returns the raw result +// JSON instead of decoding into a typed value. Used by generated method +// wrappers whose return type is a sealed-interface union. +func callMultipartRaw(ctx context.Context, b *Bot, method string, mp multipartRequest) (json.RawMessage, error) { + pr, pw := io.Pipe() + mw := multipart.NewWriter(pw) + + go func() { + defer func() { _ = pw.Close() }() + defer func() { _ = mw.Close() }() + for k, v := range mp.MultipartFields() { + if err := mw.WriteField(k, v); err != nil { + _ = pw.CloseWithError(err) + return + } + } + for _, f := range mp.MultipartFiles() { + part, err := mw.CreateFormFile(f.FieldName, f.Filename) + if err != nil { + _ = pw.CloseWithError(err) + return + } + if _, err := io.Copy(part, f.Reader); err != nil { + _ = pw.CloseWithError(err) + return + } + } + }() + + url := b.base + "/bot" + b.token + "/" + method + req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, pr) + if err != nil { + _ = pr.CloseWithError(err) + return nil, &NetworkError{Err: err} + } + req.Header.Set("Content-Type", mw.FormDataContentType()) + req.Header.Set("Accept", "application/json") + + resp, err := b.http.Do(req) + if err != nil { + _ = pr.CloseWithError(err) + if ctxErr := ctx.Err(); ctxErr != nil { + return nil, ctxErr + } + return nil, &NetworkError{Err: err} + } + defer func() { _ = resp.Body.Close() }() + + raw, err := io.ReadAll(resp.Body) + if err != nil { + _ = pr.CloseWithError(err) + return nil, &NetworkError{Err: err} + } + return decodeResultRaw(b.codec, raw) +} diff --git a/client/multipart_test.go b/client/multipart_test.go new file mode 100644 index 0000000..ef28b55 --- /dev/null +++ b/client/multipart_test.go @@ -0,0 +1,103 @@ +package client + +import ( + "context" + "errors" + "io" + "mime" + "mime/multipart" + "net/http" + "runtime" + "strings" + "testing" + "time" + + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" +) + +type fakeMultipartReq struct { + chatID int64 + body string +} + +func (f *fakeMultipartReq) HasFile() bool { return true } +func (f *fakeMultipartReq) MultipartFields() map[string]string { + return map[string]string{"chat_id": "42"} +} +func (f *fakeMultipartReq) MultipartFiles() []MultipartFile { + return []MultipartFile{{ + FieldName: "document", + Filename: "hello.txt", + Reader: strings.NewReader(f.body), + }} +} + +type fileResp struct { + MessageID int64 `json:"message_id"` +} + +func TestCallMultipart_Success(t *testing.T) { + m := &mockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + ct := r.Header.Get("Content-Type") + if !strings.HasPrefix(ct, "multipart/form-data") { + return false + } + _, params, err := mime.ParseMediaType(ct) + if err != nil { + return false + } + mr := multipart.NewReader(r.Body, params["boundary"]) + seenChat := false + seenFile := false + for { + p, err := mr.NextPart() + if err == io.EOF { + break + } + if err != nil { + return false + } + switch p.FormName() { + case "chat_id": + body, _ := io.ReadAll(p) + seenChat = string(body) == "42" + case "document": + body, _ := io.ReadAll(p) + seenFile = string(body) == "hello world" + } + } + return seenChat && seenFile + })).Return(newResp(200, `{"ok":true,"result":{"message_id":99}}`), nil) + + b := New("t", WithHTTPClient(m)) + out, err := Call[*fakeMultipartReq, *fileResp](context.Background(), b, "sendDocument", &fakeMultipartReq{chatID: 42, body: "hello world"}) + require.NoError(t, err) + require.Equal(t, int64(99), out.MessageID) +} + +func TestCallMultipart_NoGoroutineLeakOnError(t *testing.T) { + m := &mockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial timeout")) + + b := New("t", WithHTTPClient(m)) + before := runtime.NumGoroutine() + + for i := 0; i < 50; i++ { + _, _ = Call[*fakeMultipartReq, *fileResp]( + context.Background(), b, "sendDocument", + &fakeMultipartReq{chatID: 42, body: strings.Repeat("x", 1<<14)}, + ) + } + + // Allow goroutines to finish exiting after Close propagates. + time.Sleep(50 * time.Millisecond) + runtime.GC() + after := runtime.NumGoroutine() + + // A small drift is normal (timers, finalizers); 5 is generous. + if after-before > 5 { + t.Fatalf("goroutine leak: before=%d after=%d", before, after) + } +} diff --git a/client/options.go b/client/options.go new file mode 100644 index 0000000..d9b7d70 --- /dev/null +++ b/client/options.go @@ -0,0 +1,29 @@ +package client + +// Option configures a Bot at construction time. Per-call configuration is +// expressed via typed parameter structs (e.g. SendMessageParams), not options. +type Option func(*Bot) + +// WithHTTPClient overrides the HTTP transport. Pass any HTTPDoer +// implementation (e.g. an *http.Client wrapping a custom RoundTripper, or +// a fasthttp adapter). +func WithHTTPClient(c HTTPDoer) Option { return func(b *Bot) { b.http = c } } + +// WithCodec overrides the JSON codec. Pass goccy/go-json, sonic, or any +// type implementing Codec to swap out encoding/json. +func WithCodec(c Codec) Option { return func(b *Bot) { b.codec = c } } + +// WithBaseURL overrides the API base URL. Useful for testing against a +// local httptest.Server, or for self-hosted Bot API servers. +func WithBaseURL(url string) Option { return func(b *Bot) { b.base = url } } + +// WithLogger sets the logger used for diagnostic events. Passing nil +// silently disables logging. +func WithLogger(l Logger) Option { + return func(b *Bot) { + if l == nil { + l = NoopLogger{} + } + b.logger = l + } +} diff --git a/client/redact.go b/client/redact.go new file mode 100644 index 0000000..ad0d5a9 --- /dev/null +++ b/client/redact.go @@ -0,0 +1,15 @@ +package client + +import "regexp" + +// tokenInURL matches a Telegram bot token segment in a URL path. Tokens +// have the form :, where bot_id is digits and api_key +// is 35 base64-url characters. The pattern is conservative: matches +// /bot:/ to avoid false positives. +var tokenInURL = regexp.MustCompile(`/bot(\d{5,15}):([A-Za-z0-9_-]{30,40})/`) + +// redactToken replaces any bot token in s with /bot/. Used by +// error formatters so logs don't leak credentials. +func redactToken(s string) string { + return tokenInURL.ReplaceAllString(s, "/bot/") +} diff --git a/client/redact_test.go b/client/redact_test.go new file mode 100644 index 0000000..752a1c0 --- /dev/null +++ b/client/redact_test.go @@ -0,0 +1,46 @@ +package client + +import ( + "errors" + "fmt" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestRedactToken(t *testing.T) { + cases := []struct { + name string + in string + want string + }{ + {"plain bot URL", "https://api.telegram.org/bot123456789:ABCdefGHIjklMNOpqrSTUvwxYZ0123456789/getMe", + "https://api.telegram.org/bot/getMe"}, + {"in net/http error", `Post "https://api.telegram.org/bot987654321:Z9YxWvUtSrQpOnMlKjIhGfEdCbA9876543210/sendMessage": dial tcp: lookup api.telegram.org: no such host`, + `Post "https://api.telegram.org/bot/sendMessage": dial tcp: lookup api.telegram.org: no such host`}, + {"no token", "regular error message", "regular error message"}, + {"underscore + dash in token", "/bot123456789:abc-def_ghi-jkl_mno-pqr_stu-vwx_yz/sendDocument", + "/bot/sendDocument"}, + {"too short id (no match)", "/bot123:abc/getMe", "/bot123:abc/getMe"}, + {"too short key (no match)", "/bot123456789:short/getMe", "/bot123456789:short/getMe"}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + require.Equal(t, c.want, redactToken(c.in)) + }) + } +} + +func TestNetworkError_RedactsToken(t *testing.T) { + inner := errors.New(`Post "https://api.telegram.org/bot1234567890:ABCdefGHIjklMNOpqrSTUvwxYZ0123456789/getMe": dial tcp: timeout`) + e := &NetworkError{Err: inner} + require.NotContains(t, e.Error(), "ABCdefGHIjklMNOpqrSTUvwxYZ") + require.Contains(t, e.Error(), "") +} + +func TestParseError_RedactsToken(t *testing.T) { + inner := fmt.Errorf(`unexpected response from /bot1234567890:ABCdefGHIjklMNOpqrSTUvwxYZ0123456789/getMe`) + e := &ParseError{Err: inner, Body: []byte("garbage")} + require.NotContains(t, e.Error(), "ABCdefGHI") + require.Contains(t, e.Error(), "") +} diff --git a/client/result.go b/client/result.go new file mode 100644 index 0000000..11aff41 --- /dev/null +++ b/client/result.go @@ -0,0 +1,27 @@ +package client + +// Result is the universal Telegram API response envelope. Every successful +// response is shaped {"ok":true,"result":T,...}; failure responses set ok +// to false and populate ErrorCode / Description / Parameters. +// +// Result is generic over T so generated method wrappers can decode the +// strongly-typed payload directly. Users do not normally construct or +// inspect Result values; method wrappers unwrap them and return either +// the typed payload or a *APIError. +type Result[T any] struct { + OK bool `json:"ok"` + Result T `json:"result,omitempty"` + ErrorCode int `json:"error_code,omitempty"` + Description string `json:"description,omitempty"` + Parameters *ResponseParameters `json:"parameters,omitempty"` +} + +// ResponseParameters is the optional metadata Telegram includes on certain +// failures. The most common is RetryAfter (seconds) on 429 responses. +// +// This type is duplicated in package api for users; keeping a copy here +// avoids an import cycle (api imports client, not vice versa). +type ResponseParameters struct { + MigrateToChatID int64 `json:"migrate_to_chat_id,omitempty"` + RetryAfter int `json:"retry_after,omitempty"` +} diff --git a/client/retry.go b/client/retry.go new file mode 100644 index 0000000..10804d5 --- /dev/null +++ b/client/retry.go @@ -0,0 +1,225 @@ +package client + +import ( + "bytes" + "context" + crand "crypto/rand" + "encoding/binary" + "github.com/goccy/go-json" + "io" + "math" + "net/http" + "time" +) + +// RetryDoer is an HTTPDoer that retries transient failures (429, 5xx, +// and network errors) with exponential backoff. It honours the +// retry_after value Telegram supplies on rate-limit responses. +// +// Wrap any HTTPDoer to add retry behaviour: +// +// bot := client.New(token, client.WithHTTPClient( +// client.NewRetryDoer(client.NewDefaultHTTPDoer()))) +type RetryDoer struct { + inner HTTPDoer + maxAttempts int + base time.Duration + max time.Duration + factor float64 + jitter float64 +} + +// RetryOption configures a RetryDoer. +type RetryOption func(*RetryDoer) + +// WithMaxAttempts sets the maximum number of attempts (including the +// initial one). Default 4 (one initial + three retries). +func WithMaxAttempts(n int) RetryOption { + return func(d *RetryDoer) { d.maxAttempts = n } +} + +// WithBaseBackoff sets the initial backoff duration. Default 500ms. +func WithBaseBackoff(d time.Duration) RetryOption { + return func(r *RetryDoer) { r.base = d } +} + +// WithMaxBackoff caps the backoff at max. Default 30s. +func WithMaxBackoff(d time.Duration) RetryOption { + return func(r *RetryDoer) { r.max = d } +} + +// WithBackoffFactor sets the exponential growth factor. Default 2.0. +func WithBackoffFactor(f float64) RetryOption { + return func(r *RetryDoer) { r.factor = f } +} + +// WithJitter sets the jitter fraction (0..1) applied to each backoff. +// Default 0.2. +func WithJitter(j float64) RetryOption { + return func(r *RetryDoer) { r.jitter = j } +} + +// NewRetryDoer wraps inner with retry behaviour. +func NewRetryDoer(inner HTTPDoer, opts ...RetryOption) *RetryDoer { + d := &RetryDoer{ + inner: inner, + maxAttempts: 4, + base: 500 * time.Millisecond, + max: 30 * time.Second, + factor: 2.0, + jitter: 0.2, + } + for _, o := range opts { + o(d) + } + return d +} + +// Do dispatches via the inner HTTPDoer and retries on transient failures. +// The request body is buffered on first attempt so it can be replayed. +func (d *RetryDoer) Do(req *http.Request) (*http.Response, error) { + // Buffer the body so we can replay it across attempts. + var body []byte + if req.Body != nil { + b, err := io.ReadAll(req.Body) + if err != nil { + return nil, &NetworkError{Err: err} + } + _ = req.Body.Close() + body = b + } + + var lastResp *http.Response + var lastErr error + + for attempt := 1; attempt <= d.maxAttempts; attempt++ { + if body != nil { + req.Body = io.NopCloser(bytes.NewReader(body)) + } + resp, err := d.inner.Do(req) + + // Network errors: maybe retry. + if err != nil { + // Honour ctx cancellation. + if ctxErr := req.Context().Err(); ctxErr != nil { + return nil, ctxErr + } + lastErr = err + if attempt < d.maxAttempts { + if !d.sleep(req.Context(), d.delay(attempt, 0)) { + return nil, req.Context().Err() + } + continue + } + return nil, err + } + + // HTTP 200: Telegram almost always returns 200 even for errors. + // Peek the body to detect retryable Telegram error payloads. + if resp.StatusCode == http.StatusOK { + data, readErr := io.ReadAll(resp.Body) + _ = resp.Body.Close() + if readErr != nil { + return nil, &NetworkError{Err: readErr} + } + // Re-attach the buffered body for the caller. + resp.Body = io.NopCloser(bytes.NewReader(data)) + + if isRetryablePayload(data) && attempt < d.maxAttempts { + lastResp = resp + wait := retryAfterFromPayload(data) + if !d.sleep(req.Context(), d.delay(attempt, wait)) { + return nil, req.Context().Err() + } + continue + } + return resp, nil + } + + // Non-200 status (rare with Telegram; usually 200 + ok:false). + // Treat 5xx and 429 as retryable. + if (resp.StatusCode == http.StatusTooManyRequests || + resp.StatusCode >= http.StatusInternalServerError) && attempt < d.maxAttempts { + _ = resp.Body.Close() + lastResp = resp + if !d.sleep(req.Context(), d.delay(attempt, 0)) { + return nil, req.Context().Err() + } + continue + } + return resp, nil + } + + if lastErr != nil { + return nil, lastErr + } + return lastResp, nil +} + +// delay computes the wait duration for the given attempt (1-based). +// override, when non-zero, takes precedence (used to honour Telegram's +// retry_after value). +func (d *RetryDoer) delay(attempt int, override time.Duration) time.Duration { + if override > 0 { + return override + } + delay := float64(d.base) * math.Pow(d.factor, float64(attempt-1)) + if d.jitter > 0 { + var b [8]byte + _, _ = crand.Read(b[:]) + f := float64(binary.LittleEndian.Uint64(b[:])) / (1 << 64) + delay *= 1 + (f*2-1)*d.jitter + } + if delay > float64(d.max) { + delay = float64(d.max) + } + if delay < 0 { + delay = 0 + } + return time.Duration(delay) +} + +// sleep waits for dur or ctx cancellation. Returns false if cancelled. +func (d *RetryDoer) sleep(ctx context.Context, dur time.Duration) bool { + if dur <= 0 { + return true + } + t := time.NewTimer(dur) + defer t.Stop() + select { + case <-t.C: + return true + case <-ctx.Done(): + return false + } +} + +// isRetryablePayload reports whether body is a Telegram error response +// indicating a retryable failure (429 or 5xx error_code). +func isRetryablePayload(body []byte) bool { + var env struct { + OK bool `json:"ok"` + ErrorCode int `json:"error_code"` + } + if err := json.Unmarshal(body, &env); err != nil { + return false + } + if env.OK { + return false + } + return env.ErrorCode == 429 || (env.ErrorCode >= 500 && env.ErrorCode < 600) +} + +// retryAfterFromPayload extracts the retry_after value from a Telegram +// error response body and returns it as a duration. Returns 0 if absent. +func retryAfterFromPayload(body []byte) time.Duration { + var env struct { + Parameters struct { + RetryAfter int `json:"retry_after"` + } `json:"parameters"` + } + if err := json.Unmarshal(body, &env); err != nil { + return 0 + } + return time.Duration(env.Parameters.RetryAfter) * time.Second +} diff --git a/client/retry_test.go b/client/retry_test.go new file mode 100644 index 0000000..a416ee4 --- /dev/null +++ b/client/retry_test.go @@ -0,0 +1,144 @@ +package client + +import ( + "bytes" + "context" + "errors" + "io" + "net/http" + "strings" + "testing" + "time" + + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" +) + +type retryMockDoer struct{ mock.Mock } + +func (m *retryMockDoer) Do(r *http.Request) (*http.Response, error) { + args := m.Called(r) + if v := args.Get(0); v != nil { + return v.(*http.Response), args.Error(1) + } + return nil, args.Error(1) +} + +func okResp(body string) *http.Response { + return &http.Response{ + StatusCode: 200, + Body: io.NopCloser(bytes.NewBufferString(body)), + Header: http.Header{"Content-Type": []string{"application/json"}}, + } +} + +func TestRetryDoer_HappyPath(t *testing.T) { + m := &retryMockDoer{} + m.On("Do", mock.Anything).Return(okResp(`{"ok":true,"result":"hi"}`), nil).Once() + + d := NewRetryDoer(m) + req, _ := http.NewRequest("POST", "http://x", strings.NewReader(`{}`)) + resp, err := d.Do(req) + require.NoError(t, err) + require.Equal(t, 200, resp.StatusCode) + m.AssertExpectations(t) +} + +func TestRetryDoer_RetriesOnNetworkError(t *testing.T) { + m := &retryMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial timeout")).Once() + m.On("Do", mock.Anything).Return(okResp(`{"ok":true,"result":"hi"}`), nil).Once() + + d := NewRetryDoer(m, WithBaseBackoff(time.Millisecond)) + req, _ := http.NewRequest("POST", "http://x", strings.NewReader(`{}`)) + resp, err := d.Do(req) + require.NoError(t, err) + require.Equal(t, 200, resp.StatusCode) + m.AssertExpectations(t) +} + +func TestRetryDoer_HonoursRetryAfter(t *testing.T) { + m := &retryMockDoer{} + m.On("Do", mock.Anything).Return( + okResp(`{"ok":false,"error_code":429,"description":"Too Many","parameters":{"retry_after":1}}`), nil).Once() + m.On("Do", mock.Anything).Return(okResp(`{"ok":true,"result":1}`), nil).Once() + + // base is 10s — retry_after=1s should override it (much shorter wait). + d := NewRetryDoer(m, WithBaseBackoff(10*time.Second)) + req, _ := http.NewRequest("POST", "http://x", strings.NewReader(`{}`)) + start := time.Now() + resp, err := d.Do(req) + elapsed := time.Since(start) + require.NoError(t, err) + require.Equal(t, 200, resp.StatusCode) + require.GreaterOrEqual(t, elapsed, 900*time.Millisecond, "should honour retry_after=1s") + require.Less(t, elapsed, 3*time.Second, "should NOT use base backoff (10s)") + m.AssertExpectations(t) +} + +func TestRetryDoer_Retries5xx(t *testing.T) { + m := &retryMockDoer{} + m.On("Do", mock.Anything).Return( + okResp(`{"ok":false,"error_code":500,"description":"Internal Server Error"}`), nil).Once() + m.On("Do", mock.Anything).Return(okResp(`{"ok":true,"result":1}`), nil).Once() + + d := NewRetryDoer(m, WithBaseBackoff(time.Millisecond)) + req, _ := http.NewRequest("POST", "http://x", strings.NewReader(`{}`)) + resp, err := d.Do(req) + require.NoError(t, err) + require.Equal(t, 200, resp.StatusCode) + m.AssertExpectations(t) +} + +func TestRetryDoer_AllAttemptsFail(t *testing.T) { + m := &retryMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial timeout")) + + d := NewRetryDoer(m, WithMaxAttempts(3), WithBaseBackoff(time.Millisecond)) + req, _ := http.NewRequest("POST", "http://x", strings.NewReader(`{}`)) + _, err := d.Do(req) + require.Error(t, err) + require.Contains(t, err.Error(), "dial timeout") + require.Equal(t, 3, len(m.Calls)) +} + +func TestRetryDoer_ContextCancellationAborts(t *testing.T) { + m := &retryMockDoer{} + m.On("Do", mock.Anything).Return( + okResp(`{"ok":false,"error_code":500,"description":"server error"}`), nil).Maybe() + + d := NewRetryDoer(m, WithBaseBackoff(100*time.Millisecond)) + ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) + defer cancel() + req, _ := http.NewRequestWithContext(ctx, "POST", "http://x", strings.NewReader(`{}`)) + _, err := d.Do(req) + require.Error(t, err) + require.True(t, errors.Is(err, context.DeadlineExceeded)) +} + +func TestRetryDoer_ReplaysBody(t *testing.T) { + m := &retryMockDoer{} + var seen []string + + // First call: capture body, return 500 to trigger retry. + m.On("Do", mock.Anything).Return(okResp(`{"ok":false,"error_code":500}`), nil).Once().Run(func(args mock.Arguments) { + r := args.Get(0).(*http.Request) + body, _ := io.ReadAll(r.Body) + seen = append(seen, string(body)) + }) + // Second call: capture body, return success. + m.On("Do", mock.Anything).Return(okResp(`{"ok":true}`), nil).Once().Run(func(args mock.Arguments) { + r := args.Get(0).(*http.Request) + body, _ := io.ReadAll(r.Body) + seen = append(seen, string(body)) + }) + + d := NewRetryDoer(m, WithBaseBackoff(time.Millisecond)) + req, _ := http.NewRequest("POST", "http://x", strings.NewReader(`{"chat_id":42}`)) + _, err := d.Do(req) + require.NoError(t, err) + require.Len(t, seen, 2) + require.Equal(t, seen[0], seen[1]) + require.Equal(t, `{"chat_id":42}`, seen[0]) + m.AssertExpectations(t) +} diff --git a/cmd/audit/extra_test.go b/cmd/audit/extra_test.go new file mode 100644 index 0000000..723a975 --- /dev/null +++ b/cmd/audit/extra_test.go @@ -0,0 +1,378 @@ +package main + +import ( + "encoding/json" + "flag" + "fmt" + "os" + "os/exec" + "path/filepath" + "runtime" + "testing" + + "github.com/lukaszraczylo/go-telegram/internal/spec" + "github.com/stretchr/testify/require" +) + +// --------------------------------------------------------------------------- +// loadIR +// --------------------------------------------------------------------------- + +func TestLoadIR_ValidFile(t *testing.T) { + api := &spec.API{ + Methods: []spec.MethodDecl{ + {Name: "getMe", Returns: spec.TypeRef{Kind: spec.KindNamed, Name: "User"}}, + }, + } + data, err := json.Marshal(api) + require.NoError(t, err) + + tmp := filepath.Join(t.TempDir(), "api.json") + require.NoError(t, os.WriteFile(tmp, data, 0o600)) + + loaded, err := loadIR(tmp) + require.NoError(t, err) + require.Len(t, loaded.Methods, 1) + require.Equal(t, "getMe", loaded.Methods[0].Name) +} + +func TestLoadIR_MissingFile(t *testing.T) { + _, err := loadIR("/nonexistent/path/api.json") + require.Error(t, err) + require.Contains(t, err.Error(), "open IR") +} + +func TestLoadIR_InvalidJSON(t *testing.T) { + tmp := filepath.Join(t.TempDir(), "bad.json") + require.NoError(t, os.WriteFile(tmp, []byte("not json"), 0o600)) + + _, err := loadIR(tmp) + require.Error(t, err) + require.Contains(t, err.Error(), "decode IR") +} + +// --------------------------------------------------------------------------- +// auditBool +// --------------------------------------------------------------------------- + +func TestAuditBool_LongDocTruncated(t *testing.T) { + longDoc := make([]byte, 200) + for i := range longDoc { + longDoc[i] = 'a' + } + api := &spec.API{ + Methods: []spec.MethodDecl{ + {Name: "myMethod", Doc: string(longDoc), Returns: spec.TypeRef{Kind: spec.KindPrimitive, Name: "bool"}}, + }, + } + problems := auditBool(api, &spec.Overrides{}) + require.Len(t, problems, 1) + require.Contains(t, problems[0], "…") +} + +func TestAuditBool_TrueIsReturnedVariant(t *testing.T) { + api := &spec.API{ + Methods: []spec.MethodDecl{ + {Name: "doThing", Doc: "true is returned on success.", Returns: spec.TypeRef{Kind: spec.KindPrimitive, Name: "bool"}}, + }, + } + require.Empty(t, auditBool(api, &spec.Overrides{})) +} + +func TestAuditBool_ReturnsBoolean(t *testing.T) { + api := &spec.API{ + Methods: []spec.MethodDecl{ + {Name: "doThing", Doc: "Returns Boolean on success.", Returns: spec.TypeRef{Kind: spec.KindPrimitive, Name: "bool"}}, + }, + } + require.Empty(t, auditBool(api, &spec.Overrides{})) +} + +// --------------------------------------------------------------------------- +// formatTypeRef +// --------------------------------------------------------------------------- + +func TestFormatTypeRef_AllBranches(t *testing.T) { + cases := []struct { + tr spec.TypeRef + want string + }{ + {spec.TypeRef{Kind: spec.KindPrimitive, Name: "bool"}, "bool"}, + {spec.TypeRef{Kind: spec.KindNamed, Name: "User"}, "User"}, + {spec.TypeRef{Kind: spec.KindArray, ElemType: &spec.TypeRef{Kind: spec.KindNamed, Name: "Update"}}, "[]Update"}, + {spec.TypeRef{Kind: spec.KindArray}, "[]any"}, + {spec.TypeRef{Kind: spec.KindOneOf, Variants: []string{"int64", "string"}}, "(int64 | string)"}, + {spec.TypeRef{Kind: spec.Kind(99)}, "?"}, + } + for _, c := range cases { + got := formatTypeRef(c.tr) + require.Equal(t, c.want, got, "for kind=%v name=%v", c.tr.Kind, c.tr.Name) + } +} + +// --------------------------------------------------------------------------- +// auditDrift +// --------------------------------------------------------------------------- + +func TestAuditDrift_InvalidRefReturnsError(t *testing.T) { + cur := &spec.API{ + Methods: []spec.MethodDecl{ + {Name: "getMe", Returns: spec.TypeRef{Kind: spec.KindNamed, Name: "User"}}, + }, + } + _, err := auditDrift("internal/spec/api.json", "THIS_REF_DOES_NOT_EXIST", cur) + require.Error(t, err) +} + +func TestAuditDrift_SameRefNoDrift(t *testing.T) { + irPath := "../../internal/spec/api.json" + cur, err := loadIR(irPath) + if err != nil { + t.Skip("api.json not available, skipping drift test") + } + changes, err := auditDrift(irPath, "HEAD", cur) + require.NoError(t, err) + require.Empty(t, changes) +} + +func TestAuditDrift_InvalidJSONFromGit(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("shell script not supported on Windows") + } + tmp := t.TempDir() + fakeGit := filepath.Join(tmp, "git") + require.NoError(t, os.WriteFile(fakeGit, []byte("#!/bin/sh\necho 'not valid json'\n"), 0o600)) + require.NoError(t, os.Chmod(fakeGit, 0o755)) + + origPATH := os.Getenv("PATH") + t.Cleanup(func() { _ = os.Setenv("PATH", origPATH) }) + _ = os.Setenv("PATH", tmp+string(os.PathListSeparator)+origPATH) + + _, err := auditDrift("internal/spec/api.json", "HEAD", &spec.API{}) + require.Error(t, err) + require.Contains(t, err.Error(), "decode") +} + +// --------------------------------------------------------------------------- +// auditAny +// --------------------------------------------------------------------------- + +func TestAuditAny_FlagsUnknownMethodReturn(t *testing.T) { + api := &spec.API{ + Methods: []spec.MethodDecl{ + { + Name: "weirdMethod", + Returns: spec.TypeRef{Kind: spec.KindOneOf, Variants: []string{"A", "B", "C"}}, + }, + }, + } + out := auditAny(api) + require.Len(t, out, 1) + require.Contains(t, out[0], "any return: weirdMethod") +} + +func TestAuditAny_FlagsUnknownMethodParam(t *testing.T) { + api := &spec.API{ + Methods: []spec.MethodDecl{ + { + Name: "weirdMethod", + Params: []spec.Field{ + {Name: "Thing", JSONName: "thing", Type: spec.TypeRef{Kind: spec.KindOneOf, Variants: []string{"X", "Y", "Z"}}}, + }, + }, + }, + } + out := auditAny(api) + require.Len(t, out, 1) + require.Contains(t, out[0], "any param: weirdMethod.Thing") +} + +// --------------------------------------------------------------------------- +// diffSignatures +// --------------------------------------------------------------------------- + +func TestDiffSignatures_UnchangedNoDrift(t *testing.T) { + prev := &spec.API{ + Methods: []spec.MethodDecl{ + {Name: "getMe", Returns: spec.TypeRef{Kind: spec.KindNamed, Name: "User"}}, + }, + } + cur := &spec.API{ + Methods: []spec.MethodDecl{ + {Name: "getMe", Returns: spec.TypeRef{Kind: spec.KindNamed, Name: "User"}}, + }, + } + require.Empty(t, diffSignatures(prev, cur)) +} + +// --------------------------------------------------------------------------- +// typeRefEqual +// --------------------------------------------------------------------------- + +func TestTypeRefEqual_ArrayNilElemDiffers(t *testing.T) { + a := spec.TypeRef{Kind: spec.KindArray} + b := spec.TypeRef{Kind: spec.KindArray, ElemType: &spec.TypeRef{Kind: spec.KindNamed, Name: "Update"}} + require.False(t, typeRefEqual(a, b)) + require.False(t, typeRefEqual(b, a)) +} + +// --------------------------------------------------------------------------- +// TestHelperMain: subprocess helper for main() coverage. +// +// When AUDIT_HELPER_MAIN=1 is set, this function: +// 1. Resets flag.CommandLine so main()'s flag.Parse() gets a clean slate. +// 2. Sets os.Args to the args encoded in AUDIT_HELPER_ARGS. +// 3. Calls main() which calls os.Exit — the test process terminates with +// main's exit code, which the parent test captures. +// --------------------------------------------------------------------------- + +func TestHelperMain(t *testing.T) { + if os.Getenv("AUDIT_HELPER_MAIN") != "1" { + t.Skip("not running as subprocess helper") + } + // Reset flag.CommandLine so main()'s flag.Parse() gets a clean slate. + flag.CommandLine = flag.NewFlagSet(os.Args[0], flag.ExitOnError) + + // Decode args from JSON-encoded env var. + encoded := os.Getenv("AUDIT_HELPER_ARGS") + if encoded != "" { + var args []string + if err := json.Unmarshal([]byte(encoded), &args); err == nil { + os.Args = append([]string{os.Args[0]}, args...) + } + } else { + os.Args = os.Args[:1] + } + + main() +} + +// runMain runs main() via the test binary subprocess so that coverage counters +// from main() are included in the profile. Args are JSON-encoded in an env var +// to avoid conflicts with the test binary's own flag parsing. +func runMain(t *testing.T, extraEnv []string, args ...string) (string, int) { + t.Helper() + argsJSON, _ := json.Marshal(args) + cmd := exec.Command(os.Args[0], "-test.run=TestHelperMain", "-test.v=false") + cmd.Env = append(os.Environ(), "AUDIT_HELPER_MAIN=1", "AUDIT_HELPER_ARGS="+string(argsJSON)) + cmd.Env = append(cmd.Env, extraEnv...) + out, err := cmd.CombinedOutput() + code := 0 + if err != nil { + if ee, ok := err.(*exec.ExitError); ok { + code = ee.ExitCode() + } + } + return string(out), code +} + +// --------------------------------------------------------------------------- +// main() integration tests — exercise main() code paths via subprocess +// --------------------------------------------------------------------------- + +func TestMain_CleanExitsZero(t *testing.T) { + tmp := t.TempDir() + ir := writeIR(t, tmp, &spec.API{ + Methods: []spec.MethodDecl{ + {Name: "getMe", Doc: "Returns True on success.", Returns: spec.TypeRef{Kind: spec.KindNamed, Name: "User"}}, + }, + }) + ov := writeOverrides(t, tmp) + + out, code := runMain(t, nil, "-ir", ir, "-overrides", ov) + require.Equal(t, exitClean, code, "expected exit 0 (clean)\nout: %s", out) + require.Contains(t, out, "clean") +} + +func TestMain_FallbackExitsOne(t *testing.T) { + tmp := t.TempDir() + ir := writeIR(t, tmp, &spec.API{ + Methods: []spec.MethodDecl{ + {Name: "doSomething", Doc: "Does something.", Returns: spec.TypeRef{Kind: spec.KindPrimitive, Name: "bool"}}, + }, + }) + ov := writeOverrides(t, tmp) + + out, code := runMain(t, nil, "-ir", ir, "-overrides", ov) + require.Equal(t, exitFallback, code, "expected exit 1 (fallback)\nout: %s", out) + require.Contains(t, out, "bool fallback") +} + +func TestMain_InvalidIRExitsThree(t *testing.T) { + tmp := t.TempDir() + bad := filepath.Join(tmp, "bad.json") + require.NoError(t, os.WriteFile(bad, []byte("not json"), 0o600)) + ov := writeOverrides(t, tmp) + + out, code := runMain(t, nil, "-ir", bad, "-overrides", ov) + require.Equal(t, exitInvalid, code, "expected exit 3 (invalid IR)\nout: %s", out) +} + +func TestMain_InvalidOverridesExitsThree(t *testing.T) { + tmp := t.TempDir() + ir := writeIR(t, tmp, &spec.API{}) + bad := filepath.Join(tmp, "bad_ov.json") + require.NoError(t, os.WriteFile(bad, []byte("not json"), 0o600)) + + out, code := runMain(t, nil, "-ir", ir, "-overrides", bad) + require.Equal(t, exitInvalid, code, "expected exit 3 (invalid overrides)\nout: %s", out) +} + +func TestMain_DriftDetectedExitsTwo(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("shell script not supported on Windows") + } + tmp := t.TempDir() + + prevAPI := &spec.API{ + Methods: []spec.MethodDecl{ + {Name: "getMe", Returns: spec.TypeRef{Kind: spec.KindNamed, Name: "User"}}, + }, + } + curAPI := &spec.API{ + Methods: []spec.MethodDecl{ + {Name: "getMe", Returns: spec.TypeRef{Kind: spec.KindNamed, Name: "Message"}}, + }, + } + + curIR := writeIR(t, tmp, curAPI) + ov := writeOverrides(t, tmp) + + prevData, err := json.Marshal(prevAPI) + require.NoError(t, err) + prevFile := filepath.Join(tmp, "prev.json") + require.NoError(t, os.WriteFile(prevFile, prevData, 0o600)) + + fakeGit := filepath.Join(tmp, "git") + script := fmt.Sprintf("#!/bin/sh\ncat %s\n", prevFile) + require.NoError(t, os.WriteFile(fakeGit, []byte(script), 0o600)) + require.NoError(t, os.Chmod(fakeGit, 0o755)) + + newPATH := tmp + string(os.PathListSeparator) + os.Getenv("PATH") + + out, code := runMain(t, + []string{"PATH=" + newPATH}, + "-ir", curIR, "-overrides", ov, "-drift", "-against", "HEAD~1", + ) + require.Equal(t, exitDrift, code, "expected exit 2 (drift)\nout: %s", out) +} + +// --------------------------------------------------------------------------- +// helpers +// --------------------------------------------------------------------------- + +func writeIR(t *testing.T, dir string, api *spec.API) string { + t.Helper() + data, err := json.Marshal(api) + require.NoError(t, err) + p := filepath.Join(dir, "api.json") + require.NoError(t, os.WriteFile(p, data, 0o600)) + return p +} + +func writeOverrides(t *testing.T, dir string) string { + t.Helper() + p := filepath.Join(dir, "overrides.json") + require.NoError(t, os.WriteFile(p, []byte("{}"), 0o600)) + return p +} diff --git a/cmd/audit/main.go b/cmd/audit/main.go new file mode 100644 index 0000000..8865e63 --- /dev/null +++ b/cmd/audit/main.go @@ -0,0 +1,291 @@ +// Command audit reports IR-level codegen fallbacks and signature drift. +// +// Usage: +// +// audit -ir (default internal/spec/api.json) +// audit -overrides (default internal/spec/overrides.json) +// audit -drift (compare against -against ref's IR; off by default) +// audit -against (git ref to diff drift against; default HEAD~1) +// +// Exit codes: +// +// 0 — clean +// 1 — unaccounted bool fallbacks or any-typed fields +// 2 — drift detected (signature changed) +// 3 — invalid IR or overrides +package main + +import ( + "flag" + "fmt" + "github.com/goccy/go-json" + "os" + "os/exec" + "strings" + + "github.com/lukaszraczylo/go-telegram/internal/spec" +) + +const ( + exitClean = 0 + exitFallback = 1 + exitDrift = 2 + exitInvalid = 3 +) + +func main() { + irPath := flag.String("ir", "internal/spec/api.json", "path to IR JSON") + ovPath := flag.String("overrides", "internal/spec/overrides.json", "path to overrides JSON") + checkDrift := flag.Bool("drift", false, "compare against -against ref's IR for signature changes") + againstRef := flag.String("against", "HEAD~1", "git ref to diff drift against (e.g. origin/main, HEAD~1)") + flag.Parse() + + api, err := loadIR(*irPath) + if err != nil { + fmt.Fprintln(os.Stderr, "audit:", err) + os.Exit(exitInvalid) + } + overrides, err := spec.LoadOverrides(*ovPath) + if err != nil { + fmt.Fprintln(os.Stderr, "audit:", err) + os.Exit(exitInvalid) + } + + var problems []string + + problems = append(problems, auditBool(api, overrides)...) + problems = append(problems, auditAny(api)...) + + driftFound := false + if *checkDrift { + if d, err := auditDrift(*irPath, *againstRef, api); err != nil { + fmt.Fprintln(os.Stderr, "audit: drift check skipped:", err) + } else if len(d) > 0 { + fmt.Println("Drift detected (signatures changed since HEAD):") + for _, p := range d { + fmt.Println(" ", p) + } + driftFound = true + } + } + + if len(problems) == 0 && !driftFound { + fmt.Println("audit: clean") + os.Exit(exitClean) + } + + if len(problems) > 0 { + fmt.Println("Codegen fallbacks requiring action:") + for _, p := range problems { + fmt.Println(" ", p) + } + fmt.Println() + fmt.Println("To resolve: extend cmd/scrape/method.go regex patterns OR") + fmt.Println("add an entry to internal/spec/overrides.json.") + os.Exit(exitFallback) + } + + // drift only, no fallbacks + os.Exit(exitDrift) +} + +func loadIR(path string) (*spec.API, error) { + f, err := os.Open(path) + if err != nil { + return nil, fmt.Errorf("open IR: %w", err) + } + defer func() { _ = f.Close() }() + var api spec.API + if err := json.NewDecoder(f).Decode(&api); err != nil { + return nil, fmt.Errorf("decode IR: %w", err) + } + return &api, nil +} + +// auditBool returns problems for methods returning bool whose docs don't +// actually say "Returns True" / etc. and which aren't in the approved list. +func auditBool(api *spec.API, ov *spec.Overrides) []string { + var out []string + for _, m := range api.Methods { + if m.Returns.Kind != spec.KindPrimitive || m.Returns.Name != "bool" { + continue + } + if ov.IsBoolApproved(m.Name) { + continue + } + if looksGenuinelyBool(m.Doc) { + continue + } + snippet := m.Doc + if len(snippet) > 120 { + snippet = snippet[:120] + "…" + } + out = append(out, fmt.Sprintf("bool fallback: %s — doc: %q", m.Name, snippet)) + } + return out +} + +func looksGenuinelyBool(doc string) bool { + for _, p := range []string{ + "Returns True", "Returns true", + "True is returned", "true is returned", + "Returns Boolean", "Returns Bool", + } { + if strings.Contains(doc, p) { + return true + } + } + return false +} + +// auditAny scans the IR for any KindOneOf TypeRef that would render as +// `any` in generated code (not matched by ChatID/InputFile-or-string/known +// union heuristics). Reports each occurrence with location. +func auditAny(api *spec.API) []string { + var out []string + isKnownUnion := func(variants []string) bool { + if hasVariants(variants, "int64", "string") { + return true // ChatID + } + if hasVariants(variants, "InputFile", "string") { + return true // *InputFile + } + // ReplyMarkup union: all four keyboard types — emitter renders as `any` intentionally + if hasVariants(variants, "InlineKeyboardMarkup", "ReplyKeyboardMarkup", "ReplyKeyboardRemove", "ForceReply") { + return true + } + for _, t := range api.Types { + if len(t.OneOf) > 0 && sameSet(variants, t.OneOf) { + return true + } + } + return false + } + isAny := func(tr spec.TypeRef) bool { + return tr.Kind == spec.KindOneOf && !isKnownUnion(tr.Variants) + } + for _, t := range api.Types { + for _, f := range t.Fields { + if isAny(f.Type) { + out = append(out, fmt.Sprintf("any field: %s.%s (variants=%v)", t.Name, f.Name, f.Type.Variants)) + } + } + } + for _, m := range api.Methods { + if isAny(m.Returns) { + out = append(out, fmt.Sprintf("any return: %s (variants=%v)", m.Name, m.Returns.Variants)) + } + for _, p := range m.Params { + if isAny(p.Type) { + out = append(out, fmt.Sprintf("any param: %s.%s (variants=%v)", m.Name, p.Name, p.Type.Variants)) + } + } + } + return out +} + +func hasVariants(got []string, want ...string) bool { + if len(got) != len(want) { + return false + } + seen := map[string]int{} + for _, g := range got { + seen[g]++ + } + for _, w := range want { + seen[w]-- + } + for _, v := range seen { + if v != 0 { + return false + } + } + return true +} + +func sameSet(a, b []string) bool { + if len(a) != len(b) { + return false + } + return hasVariants(a, b...) +} + +// auditDrift compares method/return signatures between the given git ref's +// version of irPath and the in-memory current IR. Returns a list of +// human-readable change descriptions. +func auditDrift(irPath, againstRef string, current *spec.API) ([]string, error) { + cmd := exec.Command("git", "show", againstRef+":"+irPath) // #nosec G204 - operator tool, ref controlled by caller + out, err := cmd.Output() + if err != nil { + return nil, fmt.Errorf("git show %s: %w", againstRef, err) + } + var prev spec.API + if err := json.Unmarshal(out, &prev); err != nil { + return nil, fmt.Errorf("decode %s IR: %w", againstRef, err) + } + return diffSignatures(&prev, current), nil +} + +func diffSignatures(prev, cur *spec.API) []string { + var changes []string + + pmeth := indexByName(prev.Methods, func(m spec.MethodDecl) string { return m.Name }) + cmeth := indexByName(cur.Methods, func(m spec.MethodDecl) string { return m.Name }) + + for name, p := range pmeth { + c, ok := cmeth[name] + if !ok { + changes = append(changes, fmt.Sprintf("removed method: %s", name)) + continue + } + if !typeRefEqual(p.Returns, c.Returns) { + changes = append(changes, fmt.Sprintf( + "method %s return changed: %s → %s", + name, formatTypeRef(p.Returns), formatTypeRef(c.Returns))) + } + } + for name := range cmeth { + if _, ok := pmeth[name]; !ok { + changes = append(changes, fmt.Sprintf("added method: %s", name)) + } + } + return changes +} + +func indexByName[T any](xs []T, f func(T) string) map[string]T { + out := map[string]T{} + for _, x := range xs { + out[f(x)] = x + } + return out +} + +func typeRefEqual(a, b spec.TypeRef) bool { + if a.Kind != b.Kind || a.Name != b.Name { + return false + } + if (a.ElemType == nil) != (b.ElemType == nil) { + return false + } + if a.ElemType != nil && !typeRefEqual(*a.ElemType, *b.ElemType) { + return false + } + return sameSet(a.Variants, b.Variants) +} + +func formatTypeRef(t spec.TypeRef) string { + switch t.Kind { + case spec.KindPrimitive: + return t.Name + case spec.KindNamed: + return t.Name + case spec.KindArray: + if t.ElemType != nil { + return "[]" + formatTypeRef(*t.ElemType) + } + return "[]any" + case spec.KindOneOf: + return "(" + strings.Join(t.Variants, " | ") + ")" + } + return "?" +} diff --git a/cmd/audit/main_test.go b/cmd/audit/main_test.go new file mode 100644 index 0000000..d34f81d --- /dev/null +++ b/cmd/audit/main_test.go @@ -0,0 +1,216 @@ +package main + +import ( + "testing" + + "github.com/lukaszraczylo/go-telegram/internal/spec" + "github.com/stretchr/testify/require" +) + +// ---- auditBool ----------------------------------------------------------- + +func TestAuditBool_FlagsUnapprovedBoolMethod(t *testing.T) { + api := &spec.API{ + Methods: []spec.MethodDecl{ + {Name: "getMe", Doc: "A simple method.", Returns: spec.TypeRef{Kind: spec.KindPrimitive, Name: "bool"}}, + }, + } + ov := &spec.Overrides{} + problems := auditBool(api, ov) + require.Len(t, problems, 1) + require.Contains(t, problems[0], "bool fallback: getMe") +} + +func TestAuditBool_SkipsApprovedBoolMethod(t *testing.T) { + api := &spec.API{ + Methods: []spec.MethodDecl{ + {Name: "setWebhook", Doc: "Use this to set webhook.", Returns: spec.TypeRef{Kind: spec.KindPrimitive, Name: "bool"}}, + }, + } + ov := &spec.Overrides{ApprovedBoolMethods: []string{"setWebhook"}} + problems := auditBool(api, ov) + require.Empty(t, problems) +} + +func TestAuditBool_SkipsMethodWithReturnsTrueDoc(t *testing.T) { + api := &spec.API{ + Methods: []spec.MethodDecl{ + {Name: "doThing", Doc: "Returns True on success.", Returns: spec.TypeRef{Kind: spec.KindPrimitive, Name: "bool"}}, + }, + } + ov := &spec.Overrides{} + problems := auditBool(api, ov) + require.Empty(t, problems) +} + +func TestAuditBool_SkipsNonBoolMethods(t *testing.T) { + api := &spec.API{ + Methods: []spec.MethodDecl{ + {Name: "getMe", Doc: "Gets user.", Returns: spec.TypeRef{Kind: spec.KindNamed, Name: "User"}}, + }, + } + ov := &spec.Overrides{} + require.Empty(t, auditBool(api, ov)) +} + +// ---- auditAny ------------------------------------------------------------ + +func TestAuditAny_FlagsUnrecognisedOneOf(t *testing.T) { + api := &spec.API{ + Types: []spec.TypeDecl{ + { + Name: "Foo", + Fields: []spec.Field{ + {Name: "Bar", JSONName: "bar", Type: spec.TypeRef{Kind: spec.KindOneOf, Variants: []string{"A", "B", "C"}}}, + }, + }, + }, + } + out := auditAny(api) + require.Len(t, out, 1) + require.Contains(t, out[0], "any field: Foo.Bar") +} + +func TestAuditAny_SkipsChatIDShape(t *testing.T) { + api := &spec.API{ + Types: []spec.TypeDecl{ + { + Name: "SendMessage", + Fields: []spec.Field{ + {Name: "ChatID", JSONName: "chat_id", Type: spec.TypeRef{Kind: spec.KindOneOf, Variants: []string{"int64", "string"}}}, + }, + }, + }, + } + require.Empty(t, auditAny(api)) +} + +func TestAuditAny_SkipsKnownUnion(t *testing.T) { + api := &spec.API{ + Types: []spec.TypeDecl{ + {Name: "InputMedia", OneOf: []string{"InputMediaPhoto", "InputMediaVideo"}}, + { + Name: "SomeMethod", + Fields: []spec.Field{ + {Name: "Media", JSONName: "media", Type: spec.TypeRef{Kind: spec.KindOneOf, Variants: []string{"InputMediaPhoto", "InputMediaVideo"}}}, + }, + }, + }, + } + require.Empty(t, auditAny(api)) +} + +func TestAuditAny_SkipsReplyMarkupShape(t *testing.T) { + api := &spec.API{ + Methods: []spec.MethodDecl{ + { + Name: "sendMessage", + Params: []spec.Field{ + {Name: "ReplyMarkup", JSONName: "reply_markup", Type: spec.TypeRef{Kind: spec.KindOneOf, Variants: []string{"InlineKeyboardMarkup", "ReplyKeyboardMarkup", "ReplyKeyboardRemove", "ForceReply"}}}, + }, + }, + }, + } + require.Empty(t, auditAny(api)) +} + +func TestAuditAny_SkipsInputFileShape(t *testing.T) { + api := &spec.API{ + Methods: []spec.MethodDecl{ + { + Name: "sendPhoto", + Params: []spec.Field{ + {Name: "Photo", JSONName: "photo", Type: spec.TypeRef{Kind: spec.KindOneOf, Variants: []string{"InputFile", "string"}}}, + }, + }, + }, + } + require.Empty(t, auditAny(api)) +} + +// ---- diffSignatures ------------------------------------------------------ + +func TestDiffSignatures_AddedMethod(t *testing.T) { + prev := &spec.API{} + cur := &spec.API{ + Methods: []spec.MethodDecl{ + {Name: "newMethod", Returns: spec.TypeRef{Kind: spec.KindPrimitive, Name: "bool"}}, + }, + } + changes := diffSignatures(prev, cur) + require.Len(t, changes, 1) + require.Contains(t, changes[0], "added method: newMethod") +} + +func TestDiffSignatures_RemovedMethod(t *testing.T) { + prev := &spec.API{ + Methods: []spec.MethodDecl{ + {Name: "oldMethod", Returns: spec.TypeRef{Kind: spec.KindPrimitive, Name: "bool"}}, + }, + } + cur := &spec.API{} + changes := diffSignatures(prev, cur) + require.Len(t, changes, 1) + require.Contains(t, changes[0], "removed method: oldMethod") +} + +func TestDiffSignatures_ChangedReturn(t *testing.T) { + prev := &spec.API{ + Methods: []spec.MethodDecl{ + {Name: "getMe", Returns: spec.TypeRef{Kind: spec.KindPrimitive, Name: "bool"}}, + }, + } + cur := &spec.API{ + Methods: []spec.MethodDecl{ + {Name: "getMe", Returns: spec.TypeRef{Kind: spec.KindNamed, Name: "User"}}, + }, + } + changes := diffSignatures(prev, cur) + require.Len(t, changes, 1) + require.Contains(t, changes[0], "getMe") + require.Contains(t, changes[0], "bool") + require.Contains(t, changes[0], "User") +} + +func TestDiffSignatures_Clean(t *testing.T) { + api := &spec.API{ + Methods: []spec.MethodDecl{ + {Name: "getMe", Returns: spec.TypeRef{Kind: spec.KindNamed, Name: "User"}}, + }, + } + require.Empty(t, diffSignatures(api, api)) +} + +// ---- typeRefEqual -------------------------------------------------------- + +func TestTypeRefEqual_Primitive(t *testing.T) { + a := spec.TypeRef{Kind: spec.KindPrimitive, Name: "bool"} + require.True(t, typeRefEqual(a, a)) + b := spec.TypeRef{Kind: spec.KindPrimitive, Name: "string"} + require.False(t, typeRefEqual(a, b)) +} + +func TestTypeRefEqual_Array(t *testing.T) { + elem := &spec.TypeRef{Kind: spec.KindNamed, Name: "Update"} + a := spec.TypeRef{Kind: spec.KindArray, ElemType: elem} + b := spec.TypeRef{Kind: spec.KindArray, ElemType: &spec.TypeRef{Kind: spec.KindNamed, Name: "Update"}} + require.True(t, typeRefEqual(a, b)) + + c := spec.TypeRef{Kind: spec.KindArray, ElemType: &spec.TypeRef{Kind: spec.KindNamed, Name: "Message"}} + require.False(t, typeRefEqual(a, c)) +} + +func TestTypeRefEqual_OneOf(t *testing.T) { + a := spec.TypeRef{Kind: spec.KindOneOf, Variants: []string{"int64", "string"}} + b := spec.TypeRef{Kind: spec.KindOneOf, Variants: []string{"string", "int64"}} + require.True(t, typeRefEqual(a, b)) + + c := spec.TypeRef{Kind: spec.KindOneOf, Variants: []string{"int64"}} + require.False(t, typeRefEqual(a, c)) +} + +func TestTypeRefEqual_NilVsNonNilElem(t *testing.T) { + a := spec.TypeRef{Kind: spec.KindArray} + b := spec.TypeRef{Kind: spec.KindArray, ElemType: &spec.TypeRef{Kind: spec.KindNamed, Name: "Update"}} + require.False(t, typeRefEqual(a, b)) +} diff --git a/cmd/genapi/emitter.go b/cmd/genapi/emitter.go new file mode 100644 index 0000000..550c7d6 --- /dev/null +++ b/cmd/genapi/emitter.go @@ -0,0 +1,749 @@ +package main + +import ( + "bytes" + _ "embed" + "fmt" + "github.com/goccy/go-json" + "go/format" + "os" + "path/filepath" + "sort" + "text/template" + + "github.com/lukaszraczylo/go-telegram/internal/spec" +) + +//go:embed types.tmpl +var typesTmpl string + +//go:embed methods.tmpl +var methodsTmpl string + +//go:embed enums.tmpl +var enumsTmpl string + +//go:embed tests.tmpl +var testsTmpl string + +// runtimeTypes lists types that are intentionally hand-coded and must not be +// emitted by the code generator. Skipping them prevents collisions between +// generated and hand-coded definitions. +var runtimeTypes = map[string]bool{ + "InputFile": true, + "ResponseParameters": true, + "ChatID": true, + "MessageOrBool": true, +} + +// discriminatorSpec describes how to decode a sealed-interface union by +// peeking at a single JSON field. +type discriminatorSpec struct { + Field string // JSON field name to peek at + Variants map[string]string // discriminator value → concrete Go type name +} + +// knownDiscriminators maps parent union name → discriminator spec. +// Used by the template helpers hasDiscriminator / discriminatorField / +// discriminatorMap to emit UnmarshalXxx helpers. +var knownDiscriminators = map[string]discriminatorSpec{ + "ChatMember": { + Field: "status", + Variants: map[string]string{ + "creator": "ChatMemberOwner", + "administrator": "ChatMemberAdministrator", + "member": "ChatMemberMember", + "restricted": "ChatMemberRestricted", + "left": "ChatMemberLeft", + "kicked": "ChatMemberBanned", + }, + }, + "MessageOrigin": { + Field: "type", + Variants: map[string]string{ + "user": "MessageOriginUser", + "hidden_user": "MessageOriginHiddenUser", + "chat": "MessageOriginChat", + "channel": "MessageOriginChannel", + }, + }, + "ReactionType": { + Field: "type", + Variants: map[string]string{ + "emoji": "ReactionTypeEmoji", + "custom_emoji": "ReactionTypeCustomEmoji", + "paid": "ReactionTypePaid", + }, + }, + "PaidMedia": { + Field: "type", + Variants: map[string]string{ + "preview": "PaidMediaPreview", + "photo": "PaidMediaPhoto", + "video": "PaidMediaVideo", + }, + }, + "BackgroundType": { + Field: "type", + Variants: map[string]string{ + "fill": "BackgroundTypeFill", + "wallpaper": "BackgroundTypeWallpaper", + "pattern": "BackgroundTypePattern", + "chat_theme": "BackgroundTypeChatTheme", + }, + }, + "BackgroundFill": { + Field: "type", + Variants: map[string]string{ + "solid": "BackgroundFillSolid", + "gradient": "BackgroundFillGradient", + "freeform_gradient": "BackgroundFillFreeformGradient", + }, + }, + "ChatBoostSource": { + Field: "source", + Variants: map[string]string{ + "premium": "ChatBoostSourcePremium", + "gift_code": "ChatBoostSourceGiftCode", + "giveaway": "ChatBoostSourceGiveaway", + }, + }, + "RevenueWithdrawalState": { + Field: "type", + Variants: map[string]string{ + "pending": "RevenueWithdrawalStatePending", + "succeeded": "RevenueWithdrawalStateSucceeded", + "failed": "RevenueWithdrawalStateFailed", + }, + }, + "TransactionPartner": { + Field: "type", + Variants: map[string]string{ + "fragment": "TransactionPartnerFragment", + "user": "TransactionPartnerUser", + "telegram_ads": "TransactionPartnerTelegramAds", + "telegram_api": "TransactionPartnerTelegramApi", + "other": "TransactionPartnerOther", + }, + }, + "MenuButton": { + Field: "type", + Variants: map[string]string{ + "commands": "MenuButtonCommands", + "web_app": "MenuButtonWebApp", + "default": "MenuButtonDefault", + }, + }, + "OwnedGift": { + Field: "type", + Variants: map[string]string{ + "regular": "OwnedGiftRegular", + "unique": "OwnedGiftUnique", + }, + }, + "StoryAreaType": { + Field: "type", + Variants: map[string]string{ + "location": "StoryAreaTypeLocation", + "suggested_reaction": "StoryAreaTypeSuggestedReaction", + "link": "StoryAreaTypeLink", + "weather": "StoryAreaTypeWeather", + "unique_gift": "StoryAreaTypeUniqueGift", + }, + }, + // MaybeInaccessibleMessage uses an integer discriminator (date field). + // Variants is nil — the standard template block is skipped; a + // hand-coded UnmarshalMaybeInaccessibleMessage is emitted instead. + "MaybeInaccessibleMessage": { + Field: "", + Variants: nil, + }, +} + +// emitter renders Go source from a spec.API IR. +type emitter struct { + api *spec.API + outDir string +} + +func newEmitter(api *spec.API, outDir string) *emitter { + return &emitter{api: api, outDir: outDir} +} + +// emitTypes renders types.gen.go. +func (e *emitter) emitTypes() error { + t, err := template.New("types").Funcs(funcs()).Parse(typesTmpl) + if err != nil { + return fmt.Errorf("parse types.tmpl: %w", err) + } + filtered := *e.api + filtered.Types = nil + for _, typ := range e.api.Types { + if !runtimeTypes[typ.Name] { + filtered.Types = append(filtered.Types, typ) + } + } + var buf bytes.Buffer + if execErr := t.Execute(&buf, &filtered); execErr != nil { + return fmt.Errorf("execute types.tmpl: %w", execErr) + } + src, err := format.Source(buf.Bytes()) + if err != nil { + // Surface the unformatted output so debugging is possible. + return fmt.Errorf("gofmt types.gen.go: %w\n--- unformatted ---\n%s", err, buf.String()) + } + return os.WriteFile(filepath.Join(e.outDir, "types.gen.go"), src, 0o600) +} + +// loadAPI reads and decodes the IR JSON. +func loadAPI(path string) (*spec.API, error) { + data, err := os.ReadFile(path) + if err != nil { + return nil, err + } + var api spec.API + if err := json.Unmarshal(data, &api); err != nil { + return nil, err + } + return &api, nil +} + +// funcs is the FuncMap shared across templates. +func funcs() template.FuncMap { + return template.FuncMap{ + "goType": goType, + "goField": goField, + "docComment": docComment, + "isOptional": func(f spec.Field) bool { return !f.Required }, + "not": func(b bool) bool { return !b }, + "title": title, + "isFileField": isFileField, + "fileCheck": fileCheck, + "multipartFieldEntry": multipartFieldEntry, + "multipartFileEntry": multipartFileEntry, + "returnGoType": returnGoType, + // discriminator helpers for types.tmpl + "hasDiscriminator": func(name string) bool { s, ok := knownDiscriminators[name]; return ok && len(s.Variants) > 0 }, + "isSealedUnionReturn": func(tr spec.TypeRef) bool { + if tr.Kind != spec.KindNamed { + return false + } + s, ok := knownDiscriminators[tr.Name] + return ok && len(s.Variants) > 0 + }, + "isMaybeInaccessibleMessage": func(name string) bool { return name == "MaybeInaccessibleMessage" }, + "discriminatorField": func(name string) string { return knownDiscriminators[name].Field }, + "discriminatorMap": func(name string) map[string]string { return knownDiscriminators[name].Variants }, + // union-field helpers for per-struct UnmarshalJSON emission + "unionFields": unionFieldsOf, + "isArrayUnion": func(tr spec.TypeRef) bool { return hasUnionElem(tr) }, + "unionTypeName": func(tr spec.TypeRef) string { name, _ := unionTypeFor(tr); return name }, + } +} + +// title upper-cases the first byte of s (ASCII only — all Telegram method names are ASCII). +func title(s string) string { + if s == "" { + return "" + } + r := s[0] + if r >= 'a' && r <= 'z' { + r = r - 'a' + 'A' + } + return string(r) + s[1:] +} + +// isFileField reports whether the field carries an InputFile. +func isFileField(f spec.Field) bool { + return mentionsInputFileTr(f.Type) +} + +func mentionsInputFileTr(tr spec.TypeRef) bool { + switch tr.Kind { + case spec.KindNamed: + return tr.Name == "InputFile" + case spec.KindArray: + if tr.ElemType != nil { + return mentionsInputFileTr(*tr.ElemType) + } + case spec.KindOneOf: + for _, v := range tr.Variants { + if v == "InputFile" { + return true + } + } + } + return false +} + +// fileCheck returns the HasFile guard line for a file-carrying field. +// Both named InputFile and InputFile-or-String oneOf fields are now *InputFile, +// so no type assertion is needed in either case. +func fileCheck(f spec.Field) string { + return fmt.Sprintf("\tif p.%s != nil && p.%s.IsLocalUpload() { return true }\n", f.Name, f.Name) +} + +// multipartFileEntry returns the MultipartFiles append block for a file field. +// Both named InputFile and InputFile-or-String oneOf fields are now *InputFile, +// so the same code works for both cases. +func multipartFileEntry(f spec.Field) string { + jsonName := f.JSONName + return fmt.Sprintf( + "\tif p.%s != nil && p.%s.IsLocalUpload() {\n\t\tname := p.%s.Filename\n\t\tif name == \"\" { name = %q }\n\t\tfiles = append(files, client.MultipartFile{FieldName: %q, Filename: name, Reader: p.%s.Reader})\n\t}\n", + f.Name, f.Name, f.Name, jsonName, jsonName, f.Name) +} + +// multipartFieldEntry generates the line that adds f to the multipart map. +// Required scalar fields go in unconditionally; optional ones go in only +// when non-zero/non-empty. +func multipartFieldEntry(f spec.Field) string { + switch f.Type.Kind { + case spec.KindPrimitive: + switch f.Type.Name { + case "int64": + if f.Required { + return fmt.Sprintf("\tout[%q] = strconv.FormatInt(p.%s, 10)\n", f.JSONName, f.Name) + } + return fmt.Sprintf("\tif p.%s != nil { out[%q] = strconv.FormatInt(*p.%s, 10) }\n", f.Name, f.JSONName, f.Name) + case "string": + if f.Required { + return fmt.Sprintf("\tout[%q] = p.%s\n", f.JSONName, f.Name) + } + return fmt.Sprintf("\tif p.%s != \"\" { out[%q] = p.%s }\n", f.Name, f.JSONName, f.Name) + case "bool": + if f.Required { + return fmt.Sprintf("\tout[%q] = strconv.FormatBool(p.%s)\n", f.JSONName, f.Name) + } + return fmt.Sprintf("\tif p.%s != nil { out[%q] = strconv.FormatBool(*p.%s) }\n", f.Name, f.JSONName, f.Name) + case "float64": + if f.Required { + return fmt.Sprintf("\tout[%q] = strconv.FormatFloat(p.%s, 'f', -1, 64)\n", f.JSONName, f.Name) + } + return fmt.Sprintf("\tif p.%s != nil { out[%q] = strconv.FormatFloat(*p.%s, 'f', -1, 64) }\n", f.Name, f.JSONName, f.Name) + } + case spec.KindOneOf: + // Integer-or-String → ChatID: use .String() wire form. + if matchesVariants(f.Type.Variants, "int64", "string") { + if f.Required { + return fmt.Sprintf("\tout[%q] = p.%s.String()\n", f.JSONName, f.Name) + } + return fmt.Sprintf("\tif !p.%s.IsZero() { out[%q] = p.%s.String() }\n", f.Name, f.JSONName, f.Name) + } + // InputFile-or-String → *InputFile: non-upload branch sends PathOrID. + if matchesVariants(f.Type.Variants, "InputFile", "string") { + return fmt.Sprintf("\tif p.%s != nil && !p.%s.IsLocalUpload() && p.%s.PathOrID != \"\" { out[%q] = p.%s.PathOrID }\n", + f.Name, f.Name, f.Name, f.JSONName, f.Name) + } + // Sealed-interface unions — JSON-marshal. + if f.Required { + return fmt.Sprintf("\tif b, _ := json.Marshal(p.%s); len(b) > 0 && string(b) != \"null\" { out[%q] = string(b) }\n", f.Name, f.JSONName) + } + return fmt.Sprintf("\tif p.%s != nil { if b, _ := json.Marshal(p.%s); len(b) > 0 && string(b) != \"null\" { out[%q] = string(b) } }\n", f.Name, f.Name, f.JSONName) + } + // Named or array: fall back to JSON-marshal to JSON string. + if f.Required { + return fmt.Sprintf("\tif b, _ := json.Marshal(p.%s); len(b) > 0 { out[%q] = string(b) }\n", f.Name, f.JSONName) + } + return fmt.Sprintf("\tif p.%s != nil { if b, _ := json.Marshal(p.%s); len(b) > 0 { out[%q] = string(b) } }\n", f.Name, f.Name, f.JSONName) +} + +func returnGoType(tr spec.TypeRef) string { + switch tr.Kind { + case spec.KindPrimitive: + return tr.Name + case spec.KindNamed: + // Sealed-interface unions are returned by interface value, not pointer + // (you can't take a pointer to an interface in any useful way; the + // generated UnmarshalXxx returns the interface directly). + if _, ok := knownDiscriminators[tr.Name]; ok { + return tr.Name + } + // MessageOrBool is a hand-coded runtime wrapper — pointer return. + return "*" + tr.Name + case spec.KindArray: + if tr.ElemType == nil { + return "[]any" + } + return "[]" + returnGoElem(*tr.ElemType) + case spec.KindOneOf: + // Integer-or-String return (rare but possible). + if matchesVariants(tr.Variants, "int64", "string") { + return "ChatID" + } + return "any" + } + return "any" +} + +func returnGoElem(tr spec.TypeRef) string { + switch tr.Kind { + case spec.KindPrimitive: + return tr.Name + case spec.KindNamed: + return tr.Name + case spec.KindArray: + if tr.ElemType == nil { + return "any" + } + return "[]" + returnGoElem(*tr.ElemType) + } + return "any" +} + +// emitMethods renders methods.gen.go. +func (e *emitter) emitMethods() error { + t, err := template.New("methods").Funcs(funcs()).Parse(methodsTmpl) + if err != nil { + return fmt.Errorf("parse methods.tmpl: %w", err) + } + var buf bytes.Buffer + if execErr := t.Execute(&buf, e.api); execErr != nil { + return fmt.Errorf("execute methods.tmpl: %w", execErr) + } + src, err := format.Source(buf.Bytes()) + if err != nil { + return fmt.Errorf("gofmt methods.gen.go: %w\n--- unformatted ---\n%s", err, buf.String()) + } + return os.WriteFile(filepath.Join(e.outDir, "methods.gen.go"), src, 0o600) +} + +// emitEnums renders enums.gen.go. +func (e *emitter) emitEnums() error { + t, err := template.New("enums").Funcs(funcs()).Parse(enumsTmpl) + if err != nil { + return fmt.Errorf("parse enums.tmpl: %w", err) + } + var buf bytes.Buffer + if execErr := t.Execute(&buf, e.api); execErr != nil { + return fmt.Errorf("execute enums.tmpl: %w", execErr) + } + src, err := format.Source(buf.Bytes()) + if err != nil { + return fmt.Errorf("gofmt enums.gen.go: %w\n--- unformatted ---\n%s", err, buf.String()) + } + return os.WriteFile(filepath.Join(e.outDir, "enums.gen.go"), src, 0o600) +} + +// goType returns the Go type expression for a TypeRef. +// Optional fields use pointer types for primitives and named types, +// or rely on omitempty for slices and maps. parameter `optional` controls +// whether to wrap pointer-style. +func goType(tr spec.TypeRef, optional bool) string { + switch tr.Kind { + case spec.KindPrimitive: + if optional && (tr.Name == "bool" || tr.Name == "int64" || tr.Name == "float64") { + return "*" + tr.Name + } + return tr.Name + case spec.KindNamed: + // Named types are always pointer-optional when optional, except: + // 1. Union (interface) types — they are naturally nil-able; pointer-to-interface is invalid. + // 2. InputFile is always pointer-typed even when required: the + // multipart helpers (fileCheck, multipartFileEntry) call + // f.IsLocalUpload() and dereference Reader, both of which + // expect a pointer receiver. + if _, isUnion := knownDiscriminators[tr.Name]; isUnion { + // Interface type — never add *. + return tr.Name + } + if optional || tr.Name == "InputFile" { + return "*" + tr.Name + } + return tr.Name + case spec.KindArray: + if tr.ElemType == nil { + return "[]any" + } + // Inside slices, the element shape is its own thing — never wrap + // the element in a pointer just because the field is optional. + return "[]" + goType(*tr.ElemType, false) + case spec.KindOneOf: + // Integer-or-String: typed ChatID wrapper. + if matchesVariants(tr.Variants, "int64", "string") { + if optional { + return "*ChatID" + } + return "ChatID" + } + // InputFile-or-String: *InputFile runtime helper handles both. + if matchesVariants(tr.Variants, "InputFile", "string") { + return "*InputFile" + } + // All-named variants sealed interface: fall back to interface. + return "any" + } + return "any" +} + +// unionField pairs a struct field with the name of its union type. +type unionField struct { + Field spec.Field + UnionName string // e.g. "ChatMember" +} + +// unionFieldsOf returns the subset of t.Fields whose type is a known +// discriminated union (directly or as array element). +func unionFieldsOf(t spec.TypeDecl) []unionField { + var out []unionField + for _, f := range t.Fields { + if u, ok := unionTypeFor(f.Type); ok { + out = append(out, unionField{Field: f, UnionName: u}) + } + } + return out +} + +// unionTypeFor inspects a TypeRef and reports whether it (or its array +// element) is a known discriminated union. Returns the union name and true. +func unionTypeFor(tr spec.TypeRef) (string, bool) { + switch tr.Kind { + case spec.KindNamed: + if _, ok := knownDiscriminators[tr.Name]; ok { + return tr.Name, true + } + case spec.KindArray: + if tr.ElemType != nil { + return unionTypeFor(*tr.ElemType) + } + case spec.KindOneOf: + if u := unionNameByVariants(tr.Variants); u != "" { + return u, true + } + } + return "", false +} + +// unionNameByVariants finds the parent union whose variant type names exactly +// match the given variant set (order-insensitive). +func unionNameByVariants(variants []string) string { + for parentName, ds := range knownDiscriminators { + wanted := make([]string, 0, len(ds.Variants)) + for _, vt := range ds.Variants { + wanted = append(wanted, vt) + } + if matchesVariants(variants, wanted...) { + return parentName + } + } + return "" +} + +// hasUnionElem reports whether tr is an array whose element type is a known union. +func hasUnionElem(tr spec.TypeRef) bool { + if tr.Kind != spec.KindArray || tr.ElemType == nil { + return false + } + _, ok := unionTypeFor(*tr.ElemType) + return ok +} + +// matchesVariants reports whether got equals want as a set (order-insensitive). +func matchesVariants(got []string, want ...string) bool { + if len(got) != len(want) { + return false + } + seen := make(map[string]int, len(got)) + for _, g := range got { + seen[g]++ + } + for _, w := range want { + seen[w]-- + } + for _, v := range seen { + if v != 0 { + return false + } + } + return true +} + +// goField returns the Go struct-field declaration for a Field. +func goField(f spec.Field) string { + tag := fmt.Sprintf("`json:%q`", f.JSONName+omitempty(f)) + return fmt.Sprintf("%s %s %s", f.Name, goType(f.Type, !f.Required), tag) +} + +func omitempty(f spec.Field) string { + if f.Required { + return "" + } + return ",omitempty" +} + +// docComment converts a doc string into a Go-style block comment with +// a leading "// " on each line. +func docComment(s string) string { + if s == "" { + return "" + } + var buf bytes.Buffer + for _, line := range splitLines(s) { + buf.WriteString("// ") + buf.WriteString(line) + buf.WriteByte('\n') + } + return buf.String() +} + +func splitLines(s string) []string { + var out []string + start := 0 + for i := 0; i < len(s); i++ { + if s[i] == '\n' { + out = append(out, s[start:i]) + start = i + 1 + } + } + if start < len(s) { + out = append(out, s[start:]) + } + return out +} + +// hasVariants reports whether the variant list contains all of the named strings (order-insensitive). +func hasVariants(variants []string, names ...string) bool { + return matchesVariants(variants, names...) +} + +// buildUnionTypeSet returns the set of all type names that generate interface types +// (i.e., types with one_of). This includes knownDiscriminators and marker-interface +// unions not covered by the discriminator map. +func buildUnionTypeSet(api *spec.API) map[string]bool { + s := make(map[string]bool, len(knownDiscriminators)+16) + for name := range knownDiscriminators { + s[name] = true + } + for _, t := range api.Types { + if len(t.OneOf) > 0 { + s[t.Name] = true + } + } + return s +} + +// makeSentinelValue returns a sentinelValue func that uses the given union type set. +// It returns a minimal valid Go expression for a spec.Field's type, +// used in generated test param literals. +func makeSentinelValue(unionTypes map[string]bool) func(spec.Field) string { + return func(f spec.Field) string { + return sentinelForField(f, unionTypes) + } +} + +func sentinelForField(f spec.Field, unionTypes map[string]bool) string { + tr := f.Type + switch tr.Kind { + case spec.KindPrimitive: + switch tr.Name { + case "int64": + return "42" + case "string": + return `"test_value"` + case "bool": + return "true" + case "float64": + return "1.0" + } + case spec.KindNamed: + switch tr.Name { + case "ChatID": + return "ChatIDFromInt(123)" + case "InputFile": + return `&InputFile{PathOrID: "file_id_test"}` + } + // Interface (union) types are nil-able. + if unionTypes[tr.Name] { + return "nil" + } + // Required named struct types are value types in the generated struct. + if f.Required { + return tr.Name + "{}" + } + return "&" + tr.Name + "{}" + case spec.KindArray: + return "nil" + case spec.KindOneOf: + if hasVariants(tr.Variants, "int64", "string") { + return "ChatIDFromInt(123)" + } + if hasVariants(tr.Variants, "InputFile", "string") { + return `&InputFile{PathOrID: "file_id_test"}` + } + // Sealed named-union interface: use nil (any). + return "nil" + } + return "nil" +} + +// successResp returns a backtick Go string literal containing a minimal +// {"ok":true,"result":...} JSON body for the method's return type. +func successResp(m spec.MethodDecl) string { + body := successBody(m.Returns) + return "`{\"ok\":true,\"result\":" + body + "}`" +} + +func successBody(tr spec.TypeRef) string { + switch tr.Kind { + case spec.KindPrimitive: + switch tr.Name { + case "bool": + return "true" + case "int64", "float64": + return "0" + case "string": + return `""` + } + case spec.KindNamed: + if tr.Name == "MessageOrBool" { + return "true" + } + // Sealed-interface unions need a discriminator field so UnmarshalXxx can dispatch. + // Pick the lexicographically first variant value for determinism (map + // iteration order in Go is randomized — using `range` directly produces + // non-deterministic regen output). + if disc, ok := knownDiscriminators[tr.Name]; ok && disc.Field != "" { + values := make([]string, 0, len(disc.Variants)) + for v := range disc.Variants { + values = append(values, v) + } + sort.Strings(values) + if len(values) > 0 { + return fmt.Sprintf(`{"%s":"%s"}`, disc.Field, values[0]) + } + } + // MaybeInaccessibleMessage uses date==0 → InaccessibleMessage variant. + if tr.Name == "MaybeInaccessibleMessage" { + return `{"date":0,"chat":{"id":1,"type":"private"},"message_id":1}` + } + return "{}" + case spec.KindArray: + return "[]" + case spec.KindOneOf: + return "null" + } + return "null" +} + +// emitTests renders methods_gen_test.go. +func (e *emitter) emitTests() error { + unionTypes := buildUnionTypeSet(e.api) + + // Add test-specific helpers to the shared func map. + fm := funcs() + fm["sentinelValue"] = makeSentinelValue(unionTypes) + fm["successResp"] = successResp + + t, err := template.New("tests").Funcs(fm).Parse(testsTmpl) + if err != nil { + return fmt.Errorf("parse tests.tmpl: %w", err) + } + var buf bytes.Buffer + if execErr := t.Execute(&buf, e.api); execErr != nil { + return fmt.Errorf("execute tests.tmpl: %w", execErr) + } + src, err := format.Source(buf.Bytes()) + if err != nil { + return fmt.Errorf("gofmt methods_gen_test.go: %w\n--- unformatted ---\n%s", err, buf.String()) + } + return os.WriteFile(filepath.Join(e.outDir, "methods_gen_test.go"), src, 0o600) +} diff --git a/cmd/genapi/emitter_test.go b/cmd/genapi/emitter_test.go new file mode 100644 index 0000000..2961546 --- /dev/null +++ b/cmd/genapi/emitter_test.go @@ -0,0 +1,97 @@ +package main + +import ( + "flag" + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/require" +) + +var updateGolden = flag.Bool("update", false, "update golden files") + +func TestEmit_Types_FixtureGolden(t *testing.T) { + api, err := loadAPI("../../testdata/golden/api_small_fixture.json") + require.NoError(t, err) + + tmp := t.TempDir() + e := newEmitter(api, tmp) + require.NoError(t, e.emitTypes()) + + got, err := os.ReadFile(filepath.Join(tmp, "types.gen.go")) + require.NoError(t, err) + + goldenPath := "../../testdata/golden/types.gen.go" + if *updateGolden { + require.NoError(t, os.WriteFile(goldenPath, got, 0o600)) + return + } + expected, err := os.ReadFile(goldenPath) + require.NoError(t, err, "missing golden; run `go test -update ./cmd/genapi/...`") + require.Equal(t, string(expected), string(got)) +} + +func TestEmit_Enums_FixtureGolden(t *testing.T) { + api, err := loadAPI("../../testdata/golden/api_small_fixture.json") + require.NoError(t, err) + + tmp := t.TempDir() + e := newEmitter(api, tmp) + require.NoError(t, e.emitEnums()) + + got, err := os.ReadFile(filepath.Join(tmp, "enums.gen.go")) + require.NoError(t, err) + + goldenPath := "../../testdata/golden/enums.gen.go" + if *updateGolden { + require.NoError(t, os.WriteFile(goldenPath, got, 0o600)) + return + } + expected, err := os.ReadFile(goldenPath) + require.NoError(t, err, "missing golden; run `go test -update ./cmd/genapi/...`") + require.Equal(t, string(expected), string(got)) +} + +func TestEmit_Methods_FixtureGolden(t *testing.T) { + api, err := loadAPI("../../testdata/golden/api_small_fixture.json") + require.NoError(t, err) + + tmp := t.TempDir() + e := newEmitter(api, tmp) + require.NoError(t, e.emitTypes()) // some methods reference types + require.NoError(t, e.emitMethods()) + + got, err := os.ReadFile(filepath.Join(tmp, "methods.gen.go")) + require.NoError(t, err) + + goldenPath := "../../testdata/golden/methods.gen.go" + if *updateGolden { + require.NoError(t, os.WriteFile(goldenPath, got, 0o600)) + return + } + expected, err := os.ReadFile(goldenPath) + require.NoError(t, err, "missing golden; run `go test -update ./cmd/genapi/...`") + require.Equal(t, string(expected), string(got)) +} + +func TestEmit_Tests_FixtureGolden(t *testing.T) { + api, err := loadAPI("../../testdata/golden/api_small_fixture.json") + require.NoError(t, err) + + tmp := t.TempDir() + e := newEmitter(api, tmp) + require.NoError(t, e.emitTests()) + + got, err := os.ReadFile(filepath.Join(tmp, "methods_gen_test.go")) + require.NoError(t, err) + + goldenPath := "../../testdata/golden/methods_gen_test.go" + if *updateGolden { + require.NoError(t, os.WriteFile(goldenPath, got, 0o600)) + return + } + expected, err := os.ReadFile(goldenPath) + require.NoError(t, err, "missing golden; run `go test -update ./cmd/genapi/...`") + require.Equal(t, string(expected), string(got)) +} diff --git a/cmd/genapi/enums.tmpl b/cmd/genapi/enums.tmpl new file mode 100644 index 0000000..93e4c31 --- /dev/null +++ b/cmd/genapi/enums.tmpl @@ -0,0 +1,60 @@ +// Code generated by cmd/genapi. DO NOT EDIT. + +//go:build !ignore_autogenerated + +package api + +// ParseMode controls how Telegram interprets formatting in message text. +type ParseMode string + +const ( + ParseModeMarkdown ParseMode = "Markdown" // legacy + ParseModeMarkdownV2 ParseMode = "MarkdownV2" + ParseModeHTML ParseMode = "HTML" +) + +// ChatType is the type of a Telegram chat. +type ChatType string + +const ( + ChatTypePrivate ChatType = "private" + ChatTypeGroup ChatType = "group" + ChatTypeSupergroup ChatType = "supergroup" + ChatTypeChannel ChatType = "channel" +) + +// UpdateType identifies an Update payload variant. Used by allowed_updates +// in getUpdates / setWebhook. +type UpdateType string + +const ( + UpdateMessage UpdateType = "message" + UpdateEditedMessage UpdateType = "edited_message" + UpdateChannelPost UpdateType = "channel_post" + UpdateEditedChannelPost UpdateType = "edited_channel_post" + UpdateCallbackQuery UpdateType = "callback_query" + UpdateInlineQuery UpdateType = "inline_query" +) + +// MessageEntityType is the kind of an entity (mention, hashtag, command, ...). +type MessageEntityType string + +const ( + EntityMention MessageEntityType = "mention" + EntityHashtag MessageEntityType = "hashtag" + EntityCashtag MessageEntityType = "cashtag" + EntityBotCommand MessageEntityType = "bot_command" + EntityURL MessageEntityType = "url" + EntityEmail MessageEntityType = "email" + EntityPhoneNumber MessageEntityType = "phone_number" + EntityBold MessageEntityType = "bold" + EntityItalic MessageEntityType = "italic" + EntityUnderline MessageEntityType = "underline" + EntityStrike MessageEntityType = "strikethrough" + EntitySpoiler MessageEntityType = "spoiler" + EntityCode MessageEntityType = "code" + EntityPre MessageEntityType = "pre" + EntityTextLink MessageEntityType = "text_link" + EntityTextMention MessageEntityType = "text_mention" + EntityCustomEmoji MessageEntityType = "custom_emoji" +) diff --git a/cmd/genapi/extra_test.go b/cmd/genapi/extra_test.go new file mode 100644 index 0000000..af788f7 --- /dev/null +++ b/cmd/genapi/extra_test.go @@ -0,0 +1,645 @@ +package main + +import ( + "testing" + + "github.com/lukaszraczylo/go-telegram/internal/spec" + "github.com/stretchr/testify/require" +) + +// --------------------------------------------------------------------------- +// goType — all branches +// --------------------------------------------------------------------------- + +func TestGoType_Primitive(t *testing.T) { + cases := []struct { + name string + optional bool + want string + }{ + {"bool", false, "bool"}, + {"bool", true, "*bool"}, + {"int64", false, "int64"}, + {"int64", true, "*int64"}, + {"float64", false, "float64"}, + {"float64", true, "*float64"}, + {"string", false, "string"}, + {"string", true, "string"}, // string is not pointer-wrapped + } + for _, c := range cases { + tr := spec.TypeRef{Kind: spec.KindPrimitive, Name: c.name} + got := goType(tr, c.optional) + require.Equal(t, c.want, got, "goType(%q, optional=%v)", c.name, c.optional) + } +} + +func TestGoType_Named_Required(t *testing.T) { + tr := spec.TypeRef{Kind: spec.KindNamed, Name: "Message"} + require.Equal(t, "Message", goType(tr, false)) + require.Equal(t, "*Message", goType(tr, true)) +} + +func TestGoType_Named_InputFile(t *testing.T) { + tr := spec.TypeRef{Kind: spec.KindNamed, Name: "InputFile"} + // InputFile is always pointer even when required. + require.Equal(t, "*InputFile", goType(tr, false)) + require.Equal(t, "*InputFile", goType(tr, true)) +} + +func TestGoType_Named_UnionInterface(t *testing.T) { + // ChatMember is a known discriminated union — no * even when optional. + tr := spec.TypeRef{Kind: spec.KindNamed, Name: "ChatMember"} + require.Equal(t, "ChatMember", goType(tr, false)) + require.Equal(t, "ChatMember", goType(tr, true)) +} + +func TestGoType_Array_NilElem(t *testing.T) { + tr := spec.TypeRef{Kind: spec.KindArray} + require.Equal(t, "[]any", goType(tr, false)) +} + +func TestGoType_Array_WithElem(t *testing.T) { + elem := spec.TypeRef{Kind: spec.KindNamed, Name: "Update"} + tr := spec.TypeRef{Kind: spec.KindArray, ElemType: &elem} + require.Equal(t, "[]Update", goType(tr, false)) +} + +func TestGoType_OneOf_ChatID(t *testing.T) { + tr := spec.TypeRef{Kind: spec.KindOneOf, Variants: []string{"int64", "string"}} + require.Equal(t, "ChatID", goType(tr, false)) + require.Equal(t, "*ChatID", goType(tr, true)) +} + +func TestGoType_OneOf_InputFile(t *testing.T) { + tr := spec.TypeRef{Kind: spec.KindOneOf, Variants: []string{"InputFile", "string"}} + require.Equal(t, "*InputFile", goType(tr, false)) +} + +func TestGoType_OneOf_SealedInterface(t *testing.T) { + tr := spec.TypeRef{Kind: spec.KindOneOf, Variants: []string{"A", "B"}} + require.Equal(t, "any", goType(tr, false)) +} + +func TestGoType_Unknown(t *testing.T) { + tr := spec.TypeRef{Kind: spec.Kind(99)} + require.Equal(t, "any", goType(tr, false)) +} + +// --------------------------------------------------------------------------- +// returnGoType — all branches +// --------------------------------------------------------------------------- + +func TestReturnGoType_Primitive(t *testing.T) { + tr := spec.TypeRef{Kind: spec.KindPrimitive, Name: "bool"} + require.Equal(t, "bool", returnGoType(tr)) +} + +func TestReturnGoType_Named(t *testing.T) { + tr := spec.TypeRef{Kind: spec.KindNamed, Name: "Message"} + require.Equal(t, "*Message", returnGoType(tr)) +} + +func TestReturnGoType_Array_NilElem(t *testing.T) { + tr := spec.TypeRef{Kind: spec.KindArray} + require.Equal(t, "[]any", returnGoType(tr)) +} + +func TestReturnGoType_Array_WithElem(t *testing.T) { + elem := spec.TypeRef{Kind: spec.KindNamed, Name: "Update"} + tr := spec.TypeRef{Kind: spec.KindArray, ElemType: &elem} + require.Equal(t, "[]Update", returnGoType(tr)) +} + +func TestReturnGoType_OneOf_ChatID(t *testing.T) { + tr := spec.TypeRef{Kind: spec.KindOneOf, Variants: []string{"int64", "string"}} + require.Equal(t, "ChatID", returnGoType(tr)) +} + +func TestReturnGoType_OneOf_Other(t *testing.T) { + tr := spec.TypeRef{Kind: spec.KindOneOf, Variants: []string{"A", "B"}} + require.Equal(t, "any", returnGoType(tr)) +} + +func TestReturnGoType_Unknown(t *testing.T) { + tr := spec.TypeRef{Kind: spec.Kind(99)} + require.Equal(t, "any", returnGoType(tr)) +} + +// --------------------------------------------------------------------------- +// returnGoElem — all branches +// --------------------------------------------------------------------------- + +func TestReturnGoElem_Primitive(t *testing.T) { + require.Equal(t, "int64", returnGoElem(spec.TypeRef{Kind: spec.KindPrimitive, Name: "int64"})) +} + +func TestReturnGoElem_Named(t *testing.T) { + require.Equal(t, "Message", returnGoElem(spec.TypeRef{Kind: spec.KindNamed, Name: "Message"})) +} + +func TestReturnGoElem_Array_NilElem(t *testing.T) { + require.Equal(t, "any", returnGoElem(spec.TypeRef{Kind: spec.KindArray})) +} + +func TestReturnGoElem_Array_WithElem(t *testing.T) { + elem := spec.TypeRef{Kind: spec.KindNamed, Name: "PhotoSize"} + tr := spec.TypeRef{Kind: spec.KindArray, ElemType: &elem} + require.Equal(t, "[]PhotoSize", returnGoElem(tr)) +} + +func TestReturnGoElem_Unknown(t *testing.T) { + require.Equal(t, "any", returnGoElem(spec.TypeRef{Kind: spec.Kind(99)})) +} + +// --------------------------------------------------------------------------- +// multipartFieldEntry — all branches +// --------------------------------------------------------------------------- + +func makeField(name, jname, typName string, kind spec.Kind, required bool) spec.Field { + return spec.Field{ + Name: name, + JSONName: jname, + Type: spec.TypeRef{Kind: kind, Name: typName}, + Required: required, + } +} + +func makeFieldVariants(name, jname string, kind spec.Kind, variants []string, required bool) spec.Field { + return spec.Field{ + Name: name, + JSONName: jname, + Type: spec.TypeRef{Kind: kind, Variants: variants}, + Required: required, + } +} + +func TestMultipartFieldEntry_Int64Required(t *testing.T) { + f := makeField("ChatID", "chat_id", "int64", spec.KindPrimitive, true) + got := multipartFieldEntry(f) + require.Contains(t, got, `FormatInt`) + require.NotContains(t, got, "if p.") +} + +func TestMultipartFieldEntry_Int64Optional(t *testing.T) { + f := makeField("MessageThreadID", "message_thread_id", "int64", spec.KindPrimitive, false) + got := multipartFieldEntry(f) + require.Contains(t, got, `FormatInt`) + require.Contains(t, got, "if p.") +} + +func TestMultipartFieldEntry_StringRequired(t *testing.T) { + f := makeField("Text", "text", "string", spec.KindPrimitive, true) + got := multipartFieldEntry(f) + require.Contains(t, got, `out["text"]`) + require.NotContains(t, got, "if p.Text") +} + +func TestMultipartFieldEntry_StringOptional(t *testing.T) { + f := makeField("ParseMode", "parse_mode", "string", spec.KindPrimitive, false) + got := multipartFieldEntry(f) + require.Contains(t, got, `if p.ParseMode`) +} + +func TestMultipartFieldEntry_BoolRequired(t *testing.T) { + f := makeField("DisableNotification", "disable_notification", "bool", spec.KindPrimitive, true) + got := multipartFieldEntry(f) + require.Contains(t, got, `FormatBool`) + require.NotContains(t, got, "if p.") +} + +func TestMultipartFieldEntry_BoolOptional(t *testing.T) { + f := makeField("Protected", "protect_content", "bool", spec.KindPrimitive, false) + got := multipartFieldEntry(f) + require.Contains(t, got, `FormatBool`) + require.Contains(t, got, "if p.") +} + +func TestMultipartFieldEntry_Float64Required(t *testing.T) { + f := makeField("Latitude", "latitude", "float64", spec.KindPrimitive, true) + got := multipartFieldEntry(f) + require.Contains(t, got, `FormatFloat`) + require.NotContains(t, got, "if p.") +} + +func TestMultipartFieldEntry_Float64Optional(t *testing.T) { + f := makeField("Longitude", "longitude", "float64", spec.KindPrimitive, false) + got := multipartFieldEntry(f) + require.Contains(t, got, `FormatFloat`) + require.Contains(t, got, "if p.") +} + +func TestMultipartFieldEntry_OneOf_ChatIDRequired(t *testing.T) { + f := makeFieldVariants("ChatID", "chat_id", spec.KindOneOf, []string{"int64", "string"}, true) + got := multipartFieldEntry(f) + require.Contains(t, got, `.String()`) + require.NotContains(t, got, "IsZero") +} + +func TestMultipartFieldEntry_OneOf_ChatIDOptional(t *testing.T) { + f := makeFieldVariants("ChatID", "chat_id", spec.KindOneOf, []string{"int64", "string"}, false) + got := multipartFieldEntry(f) + require.Contains(t, got, `IsZero`) +} + +func TestMultipartFieldEntry_OneOf_InputFileOrString(t *testing.T) { + f := makeFieldVariants("Photo", "photo", spec.KindOneOf, []string{"InputFile", "string"}, false) + got := multipartFieldEntry(f) + require.Contains(t, got, `PathOrID`) +} + +func TestMultipartFieldEntry_OneOf_SealedRequired(t *testing.T) { + f := makeFieldVariants("Markup", "reply_markup", spec.KindOneOf, []string{"A", "B"}, true) + got := multipartFieldEntry(f) + require.Contains(t, got, `json.Marshal`) +} + +func TestMultipartFieldEntry_OneOf_SealedOptional(t *testing.T) { + f := makeFieldVariants("Markup", "reply_markup", spec.KindOneOf, []string{"A", "B"}, false) + got := multipartFieldEntry(f) + require.Contains(t, got, `json.Marshal`) + require.Contains(t, got, "if p.Markup") +} + +func TestMultipartFieldEntry_Named_Required(t *testing.T) { + f := makeField("Entities", "entities", "MessageEntity", spec.KindNamed, true) + got := multipartFieldEntry(f) + require.Contains(t, got, `json.Marshal`) + require.NotContains(t, got, "if p.") +} + +func TestMultipartFieldEntry_Named_Optional(t *testing.T) { + f := makeField("Entities", "entities", "MessageEntity", spec.KindNamed, false) + got := multipartFieldEntry(f) + require.Contains(t, got, `json.Marshal`) + require.Contains(t, got, "if p.") +} + +// --------------------------------------------------------------------------- +// unionTypeFor — all branches +// --------------------------------------------------------------------------- + +func TestUnionTypeFor_DirectNamed(t *testing.T) { + tr := spec.TypeRef{Kind: spec.KindNamed, Name: "ChatMember"} + name, ok := unionTypeFor(tr) + require.True(t, ok) + require.Equal(t, "ChatMember", name) +} + +func TestUnionTypeFor_Array(t *testing.T) { + elem := spec.TypeRef{Kind: spec.KindNamed, Name: "ChatMember"} + tr := spec.TypeRef{Kind: spec.KindArray, ElemType: &elem} + name, ok := unionTypeFor(tr) + require.True(t, ok) + require.Equal(t, "ChatMember", name) +} + +func TestUnionTypeFor_ArrayNilElem(t *testing.T) { + tr := spec.TypeRef{Kind: spec.KindArray} + _, ok := unionTypeFor(tr) + require.False(t, ok) +} + +func TestUnionTypeFor_NotUnion(t *testing.T) { + tr := spec.TypeRef{Kind: spec.KindNamed, Name: "Message"} + _, ok := unionTypeFor(tr) + require.False(t, ok) +} + +func TestUnionTypeFor_Unknown(t *testing.T) { + tr := spec.TypeRef{Kind: spec.Kind(99)} + _, ok := unionTypeFor(tr) + require.False(t, ok) +} + +// --------------------------------------------------------------------------- +// unionNameByVariants +// --------------------------------------------------------------------------- + +func TestUnionNameByVariants_ChatMember(t *testing.T) { + // Use the actual variants from knownDiscriminators["ChatMember"]. + variants := []string{ + "ChatMemberOwner", "ChatMemberAdministrator", "ChatMemberMember", + "ChatMemberRestricted", "ChatMemberLeft", "ChatMemberBanned", + } + name := unionNameByVariants(variants) + require.Equal(t, "ChatMember", name) +} + +func TestUnionNameByVariants_Unknown(t *testing.T) { + name := unionNameByVariants([]string{"X", "Y", "Z"}) + require.Equal(t, "", name) +} + +// --------------------------------------------------------------------------- +// hasUnionElem +// --------------------------------------------------------------------------- + +func TestHasUnionElem_NonArray(t *testing.T) { + tr := spec.TypeRef{Kind: spec.KindNamed, Name: "ChatMember"} + require.False(t, hasUnionElem(tr)) +} + +func TestHasUnionElem_ArrayNilElem(t *testing.T) { + tr := spec.TypeRef{Kind: spec.KindArray} + require.False(t, hasUnionElem(tr)) +} + +func TestHasUnionElem_ArrayUnionElem(t *testing.T) { + elem := spec.TypeRef{Kind: spec.KindNamed, Name: "ChatMember"} + tr := spec.TypeRef{Kind: spec.KindArray, ElemType: &elem} + require.True(t, hasUnionElem(tr)) +} + +func TestHasUnionElem_ArrayNonUnionElem(t *testing.T) { + elem := spec.TypeRef{Kind: spec.KindNamed, Name: "Message"} + tr := spec.TypeRef{Kind: spec.KindArray, ElemType: &elem} + require.False(t, hasUnionElem(tr)) +} + +// --------------------------------------------------------------------------- +// unionFieldsOf +// --------------------------------------------------------------------------- + +func TestUnionFieldsOf_WithUnionField(t *testing.T) { + td := spec.TypeDecl{ + Name: "ChatMemberUpdated", + Fields: []spec.Field{ + {Name: "NewChatMember", JSONName: "new_chat_member", Type: spec.TypeRef{Kind: spec.KindNamed, Name: "ChatMember"}}, + {Name: "OldChatMember", JSONName: "old_chat_member", Type: spec.TypeRef{Kind: spec.KindNamed, Name: "ChatMember"}}, + {Name: "Date", JSONName: "date", Type: spec.TypeRef{Kind: spec.KindPrimitive, Name: "int64"}}, + }, + } + uf := unionFieldsOf(td) + require.Len(t, uf, 2) + require.Equal(t, "ChatMember", uf[0].UnionName) +} + +// --------------------------------------------------------------------------- +// splitLines — edge cases +// --------------------------------------------------------------------------- + +func TestSplitLines_Empty(t *testing.T) { + require.Empty(t, splitLines("")) +} + +func TestSplitLines_NoNewline(t *testing.T) { + got := splitLines("hello world") + require.Equal(t, []string{"hello world"}, got) +} + +func TestSplitLines_TrailingNewline(t *testing.T) { + got := splitLines("line1\nline2\n") + require.Equal(t, []string{"line1", "line2"}, got) +} + +func TestSplitLines_MultiLine(t *testing.T) { + got := splitLines("a\nb\nc") + require.Equal(t, []string{"a", "b", "c"}, got) +} + +// --------------------------------------------------------------------------- +// docComment +// --------------------------------------------------------------------------- + +func TestDocComment_Empty(t *testing.T) { + require.Equal(t, "", docComment("")) +} + +func TestDocComment_SingleLine(t *testing.T) { + got := docComment("Hello world.") + require.Equal(t, "// Hello world.\n", got) +} + +func TestDocComment_MultiLine(t *testing.T) { + got := docComment("Line 1\nLine 2") + require.Contains(t, got, "// Line 1\n") + require.Contains(t, got, "// Line 2\n") +} + +// --------------------------------------------------------------------------- +// title +// --------------------------------------------------------------------------- + +func TestTitle_Empty(t *testing.T) { + require.Equal(t, "", title("")) +} + +func TestTitle_Lowercase(t *testing.T) { + require.Equal(t, "SendMessage", title("sendMessage")) +} + +func TestTitle_AlreadyUpper(t *testing.T) { + require.Equal(t, "GetMe", title("GetMe")) +} + +// --------------------------------------------------------------------------- +// mentionsInputFileTr +// --------------------------------------------------------------------------- + +func TestMentionsInputFileTr_Named(t *testing.T) { + tr := spec.TypeRef{Kind: spec.KindNamed, Name: "InputFile"} + require.True(t, mentionsInputFileTr(tr)) +} + +func TestMentionsInputFileTr_NotInputFile(t *testing.T) { + tr := spec.TypeRef{Kind: spec.KindNamed, Name: "Message"} + require.False(t, mentionsInputFileTr(tr)) +} + +func TestMentionsInputFileTr_Array(t *testing.T) { + elem := spec.TypeRef{Kind: spec.KindNamed, Name: "InputFile"} + tr := spec.TypeRef{Kind: spec.KindArray, ElemType: &elem} + require.True(t, mentionsInputFileTr(tr)) +} + +func TestMentionsInputFileTr_ArrayNilElem(t *testing.T) { + tr := spec.TypeRef{Kind: spec.KindArray} + require.False(t, mentionsInputFileTr(tr)) +} + +func TestMentionsInputFileTr_OneOf_WithInputFile(t *testing.T) { + tr := spec.TypeRef{Kind: spec.KindOneOf, Variants: []string{"InputFile", "string"}} + require.True(t, mentionsInputFileTr(tr)) +} + +func TestMentionsInputFileTr_OneOf_WithoutInputFile(t *testing.T) { + tr := spec.TypeRef{Kind: spec.KindOneOf, Variants: []string{"A", "B"}} + require.False(t, mentionsInputFileTr(tr)) +} + +// --------------------------------------------------------------------------- +// loadAPI — error paths +// --------------------------------------------------------------------------- + +func TestLoadAPI_MissingFile(t *testing.T) { + _, err := loadAPI("/nonexistent/path/api.json") + require.Error(t, err) +} + +// --------------------------------------------------------------------------- +// runtimeTypes filter in emitTypes +// --------------------------------------------------------------------------- + +func TestRuntimeTypes_NeverEmitted(t *testing.T) { + for name := range runtimeTypes { + require.True(t, runtimeTypes[name], "runtimeType %q should be true", name) + } + require.True(t, runtimeTypes["InputFile"]) + require.True(t, runtimeTypes["ChatID"]) + require.True(t, runtimeTypes["MessageOrBool"]) + require.True(t, runtimeTypes["ResponseParameters"]) +} + +// --------------------------------------------------------------------------- +// sentinelForField — all branches +// --------------------------------------------------------------------------- + +func TestSentinelForField(t *testing.T) { + unionTypes := map[string]bool{"ChatMember": true} + cases := []struct { + name string + field spec.Field + contains string + }{ + { + name: "int64 primitive", + field: makeField("Count", "count", "int64", spec.KindPrimitive, true), + contains: "42", + }, + { + name: "string primitive", + field: makeField("Text", "text", "string", spec.KindPrimitive, true), + contains: "test_value", + }, + { + name: "bool primitive", + field: makeField("Flag", "flag", "bool", spec.KindPrimitive, true), + contains: "true", + }, + { + name: "float64 primitive", + field: makeField("Lat", "lat", "float64", spec.KindPrimitive, true), + contains: "1.0", + }, + { + name: "named ChatID", + field: makeField("ChatID", "chat_id", "ChatID", spec.KindNamed, true), + contains: "ChatIDFromInt", + }, + { + name: "named InputFile", + field: makeField("Photo", "photo", "InputFile", spec.KindNamed, true), + contains: "InputFile", + }, + { + name: "named union (nil-able)", + field: makeField("Member", "member", "ChatMember", spec.KindNamed, true), + contains: "nil", + }, + { + name: "named required struct", + field: makeField("Chat", "chat", "Chat", spec.KindNamed, true), + contains: "Chat{}", + }, + { + name: "named optional struct", + field: makeField("Chat", "chat", "Chat", spec.KindNamed, false), + contains: "&Chat{}", + }, + { + name: "array", + field: spec.Field{Name: "Items", JSONName: "items", Type: spec.TypeRef{Kind: spec.KindArray}}, + contains: "nil", + }, + { + name: "oneOf ChatID variants", + field: makeFieldVariants("ChatID", "chat_id", spec.KindOneOf, []string{"int64", "string"}, true), + contains: "ChatIDFromInt", + }, + { + name: "oneOf InputFile variants", + field: makeFieldVariants("Photo", "photo", spec.KindOneOf, []string{"InputFile", "string"}, true), + contains: "InputFile", + }, + { + name: "oneOf sealed", + field: makeFieldVariants("Markup", "markup", spec.KindOneOf, []string{"A", "B"}, true), + contains: "nil", + }, + { + name: "unknown kind", + field: spec.Field{Name: "X", JSONName: "x", Type: spec.TypeRef{Kind: spec.Kind(99)}}, + contains: "nil", + }, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + got := sentinelForField(c.field, unionTypes) + require.Contains(t, got, c.contains, "sentinelForField for %q", c.name) + }) + } +} + +// --------------------------------------------------------------------------- +// successBody — all branches +// --------------------------------------------------------------------------- + +func TestSuccessBody(t *testing.T) { + cases := []struct { + name string + tr spec.TypeRef + want string + }{ + {"bool", spec.TypeRef{Kind: spec.KindPrimitive, Name: "bool"}, "true"}, + {"int64", spec.TypeRef{Kind: spec.KindPrimitive, Name: "int64"}, "0"}, + {"float64", spec.TypeRef{Kind: spec.KindPrimitive, Name: "float64"}, "0"}, + {"string", spec.TypeRef{Kind: spec.KindPrimitive, Name: "string"}, `""`}, + {"MessageOrBool", spec.TypeRef{Kind: spec.KindNamed, Name: "MessageOrBool"}, "true"}, + {"named", spec.TypeRef{Kind: spec.KindNamed, Name: "Message"}, "{}"}, + {"array", spec.TypeRef{Kind: spec.KindArray}, "[]"}, + {"oneOf", spec.TypeRef{Kind: spec.KindOneOf, Variants: []string{"A", "B"}}, "null"}, + {"unknown", spec.TypeRef{Kind: spec.Kind(99)}, "null"}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + got := successBody(c.tr) + require.Equal(t, c.want, got) + }) + } +} + +// --------------------------------------------------------------------------- +// unionTypeFor — KindOneOf branch (variant-set match) +// --------------------------------------------------------------------------- + +func TestUnionTypeFor_OneOfVariants(t *testing.T) { + // These variant *type names* match the ChatMember discriminator. + tr := spec.TypeRef{ + Kind: spec.KindOneOf, + Variants: []string{ + "ChatMemberOwner", "ChatMemberAdministrator", "ChatMemberMember", + "ChatMemberRestricted", "ChatMemberLeft", "ChatMemberBanned", + }, + } + name, ok := unionTypeFor(tr) + require.True(t, ok) + require.Equal(t, "ChatMember", name) +} + +func TestUnionTypeFor_OneOfNoMatch(t *testing.T) { + tr := spec.TypeRef{Kind: spec.KindOneOf, Variants: []string{"Foo", "Bar"}} + _, ok := unionTypeFor(tr) + require.False(t, ok) +} + +// --------------------------------------------------------------------------- +// funcs() returns a non-nil FuncMap with expected keys +// --------------------------------------------------------------------------- + +func TestFuncs_HasExpectedKeys(t *testing.T) { + fm := funcs() + require.NotNil(t, fm) + for _, key := range []string{"goType", "docComment", "returnGoType", "unionFields"} { + require.NotNil(t, fm[key], "funcs() missing key %q", key) + } +} diff --git a/cmd/genapi/main.go b/cmd/genapi/main.go new file mode 100644 index 0000000..a4c5d31 --- /dev/null +++ b/cmd/genapi/main.go @@ -0,0 +1,49 @@ +// Command genapi reads internal/spec/api.json and emits api/*.gen.go. +// +// Usage: +// +// genapi -input (default: internal/spec/api.json) +// genapi -outdir (default: api) +package main + +import ( + "flag" + "fmt" + "os" +) + +func main() { + input := flag.String("input", "internal/spec/api.json", "IR JSON path") + outdir := flag.String("outdir", "api", "output directory") + flag.Parse() + + if err := run(*input, *outdir); err != nil { + fmt.Fprintln(os.Stderr, "genapi:", err) + os.Exit(1) + } +} + +// run is filled in by P2.T8/T9/T10. +func run(input, outdir string) error { + api, err := loadAPI(input) + if err != nil { + return fmt.Errorf("load api: %w", err) + } + if err := os.MkdirAll(outdir, 0o750); err != nil { + return err + } + e := newEmitter(api, outdir) + if err := e.emitTypes(); err != nil { + return err + } + if err := e.emitMethods(); err != nil { + return err + } + if err := e.emitEnums(); err != nil { + return err + } + if err := e.emitTests(); err != nil { + return err + } + return nil +} diff --git a/cmd/genapi/methods.tmpl b/cmd/genapi/methods.tmpl new file mode 100644 index 0000000..c0fa2f9 --- /dev/null +++ b/cmd/genapi/methods.tmpl @@ -0,0 +1,58 @@ +// Code generated by cmd/genapi. DO NOT EDIT. + +//go:build !ignore_autogenerated + +package api + +import ( + "context" + "github.com/goccy/go-json" + "strconv" + + "github.com/lukaszraczylo/go-telegram/client" +) + +var _ = strconv.Itoa // keep import for multipart helpers +var _ = json.Marshal // keep import for complex multipart fields + +{{range .Methods}} +// {{title .Name}}Params is the parameter set for {{title .Name}}. +// +{{docComment .Doc -}} +type {{title .Name}}Params struct { +{{range .Params}}{{docComment .Doc}} {{goField .}} +{{end}}} +{{if .HasFiles}} +// HasFile reports whether a multipart upload is required. +func (p *{{title .Name}}Params) HasFile() bool { +{{range .Params}}{{if isFileField .}}{{fileCheck .}}{{end}}{{end}} return false +} + +// MultipartFields returns the non-file fields used in the multipart body. +func (p *{{title .Name}}Params) MultipartFields() map[string]string { + out := map[string]string{} +{{range .Params}}{{if not (isFileField .)}}{{multipartFieldEntry .}}{{end}}{{end}} return out +} + +// MultipartFiles returns the file parts. +func (p *{{title .Name}}Params) MultipartFiles() []client.MultipartFile { + var files []client.MultipartFile +{{range .Params}}{{if isFileField .}}{{multipartFileEntry .}}{{end}}{{end}} return files +} +{{end}} + +// {{title .Name}} calls the {{.Name}} Telegram Bot API method. +// +{{docComment .Doc -}} +func {{title .Name}}(ctx context.Context, b *client.Bot, p *{{title .Name}}Params) ({{returnGoType .Returns}}, error) { +{{if isSealedUnionReturn .Returns -}} + raw, err := client.CallRaw[*{{title .Name}}Params](ctx, b, "{{.Name}}", p) + if err != nil { + return nil, err + } + return Unmarshal{{.Returns.Name}}(raw) +{{else -}} + return client.Call[*{{title .Name}}Params, {{returnGoType .Returns}}](ctx, b, "{{.Name}}", p) +{{end -}} +} +{{end}} diff --git a/cmd/genapi/tests.tmpl b/cmd/genapi/tests.tmpl new file mode 100644 index 0000000..1327e90 --- /dev/null +++ b/cmd/genapi/tests.tmpl @@ -0,0 +1,220 @@ +// Code generated by cmd/genapi. DO NOT EDIT. + +//go:build !ignore_autogenerated + +package api + +import ( + "bytes" + "context" + "errors" + "io" + "net/http" + "strings" + "testing" + + "github.com/lukaszraczylo/go-telegram/client" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" +) + +// genTestMockDoer is a testify-mock HTTPDoer used by generated tests only. +type genTestMockDoer struct{ mock.Mock } + +func (m *genTestMockDoer) Do(r *http.Request) (*http.Response, error) { + args := m.Called(r) + if v := args.Get(0); v != nil { + return v.(*http.Response), args.Error(1) + } + return nil, args.Error(1) +} + +func genTestResp(status int, body string) *http.Response { + return &http.Response{ + StatusCode: status, + Body: io.NopCloser(bytes.NewBufferString(body)), + Header: http.Header{"Content-Type": []string{"application/json"}}, + } +} + +{{range .Methods}}{{$m := .}}{{$mName := title .Name}}{{$mWire := .Name}} +func Test_{{$mName}}_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/{{$mWire}}") + })).Return(genTestResp(200, {{successResp $m}}), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + {{- if .Params}} + params := &{{$mName}}Params{ + {{- range .Params}}{{if .Required}} + {{.Name}}: {{sentinelValue .}},{{end}} + {{- end}} + } + _, err := {{$mName}}(context.Background(), bot, params) + {{- else}} + _, err := {{$mName}}(context.Background(), bot, &{{$mName}}Params{}) + {{- end}} + require.NoError(t, err) +} + +func Test_{{$mName}}_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + {{- if .Params}} + params := &{{$mName}}Params{ + {{- range .Params}}{{if .Required}} + {{.Name}}: {{sentinelValue .}},{{end}} + {{- end}} + } + _, err := {{$mName}}(context.Background(), bot, params) + {{- else}} + _, err := {{$mName}}(context.Background(), bot, &{{$mName}}Params{}) + {{- end}} + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_{{$mName}}_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + {{- if .Params}} + params := &{{$mName}}Params{ + {{- range .Params}}{{if .Required}} + {{.Name}}: {{sentinelValue .}},{{end}} + {{- end}} + } + _, err := {{$mName}}(context.Background(), bot, params) + {{- else}} + _, err := {{$mName}}(context.Background(), bot, &{{$mName}}Params{}) + {{- end}} + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_{{$mName}}_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + {{- if .Params}} + params := &{{$mName}}Params{ + {{- range .Params}}{{if .Required}} + {{.Name}}: {{sentinelValue .}},{{end}} + {{- end}} + } + _, err := {{$mName}}(context.Background(), bot, params) + {{- else}} + _, err := {{$mName}}(context.Background(), bot, &{{$mName}}Params{}) + {{- end}} + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_{{$mName}}_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + {{- if .Params}} + params := &{{$mName}}Params{ + {{- range .Params}}{{if .Required}} + {{.Name}}: {{sentinelValue .}},{{end}} + {{- end}} + } + _, err := {{$mName}}(ctx, bot, params) + {{- else}} + _, err := {{$mName}}(ctx, bot, &{{$mName}}Params{}) + {{- end}} + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_{{$mName}}_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_{{$mName}}_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := {{$mName}}(context.Background(), bot, &{{$mName}}Params{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_{{$mName}}_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_{{$mName}}_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + {{- if .Params}} + params := &{{$mName}}Params{ + {{- range .Params}}{{if .Required}} + {{.Name}}: {{sentinelValue .}},{{end}} + {{- end}} + } + _, err := {{$mName}}(context.Background(), bot, params) + {{- else}} + _, err := {{$mName}}(context.Background(), bot, &{{$mName}}Params{}) + {{- end}} + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_{{$mName}}_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_{{$mName}}_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + {{- if .Params}} + params := &{{$mName}}Params{ + {{- range .Params}}{{if .Required}} + {{.Name}}: {{sentinelValue .}},{{end}} + {{- end}} + } + _, err := {{$mName}}(context.Background(), bot, params) + {{- else}} + _, err := {{$mName}}(context.Background(), bot, &{{$mName}}Params{}) + {{- end}} + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +{{end}} diff --git a/cmd/genapi/types.tmpl b/cmd/genapi/types.tmpl new file mode 100644 index 0000000..c44ae74 --- /dev/null +++ b/cmd/genapi/types.tmpl @@ -0,0 +1,126 @@ +// Code generated by cmd/genapi. DO NOT EDIT. + +//go:build !ignore_autogenerated + +// Package api contains the Telegram Bot API object types and method +// wrappers, generated from the live documentation by cmd/genapi. +package api + +import ( + "github.com/goccy/go-json" + "fmt" + "io" +) + +var _ = io.Discard // keep import even if no fields use io +var _ = json.Marshal // keep import for UnmarshalXxx helpers +var _ = fmt.Errorf // keep import for UnmarshalXxx helpers + +{{range .Types}} +{{- $td := . -}} +{{if .OneOf}} +// {{.Name}} is a union type. The following concrete variants implement +// it: +{{range .OneOf}}// - {{.}} +{{end}}// +{{docComment .Doc -}} +type {{.Name}} interface{ is{{.Name}}() } + +{{range .OneOf}} +// is{{$td.Name}} is the marker method that makes {{.}} implement {{$td.Name}}. +func (*{{.}}) is{{$td.Name}}() {} +{{end}} +{{if hasDiscriminator .Name}} +// Unmarshal{{.Name}} decodes a {{.Name}} from JSON by inspecting the +// "{{discriminatorField .Name}}" field and dispatching to the correct concrete type. +func Unmarshal{{.Name}}(data []byte) ({{.Name}}, error) { + var probe struct { + V string `json:"{{discriminatorField .Name}}"` + } + if err := json.Unmarshal(data, &probe); err != nil { + return nil, err + } + var v {{.Name}} + switch probe.V { +{{range $val, $typ := discriminatorMap .Name}} case {{printf "%q" $val}}: + v = &{{$typ}}{} +{{end}} default: + return nil, fmt.Errorf("{{.Name}}: unknown {{discriminatorField .Name}} %q", probe.V) + } + if err := json.Unmarshal(data, v); err != nil { + return nil, err + } + return v, nil +} +{{end}} +{{if isMaybeInaccessibleMessage .Name}} +// UnmarshalMaybeInaccessibleMessage decodes a JSON object into the correct +// MaybeInaccessibleMessage variant. Telegram uses the date field as a +// discriminator: date == 0 indicates InaccessibleMessage; any other value +// indicates a real Message. +func UnmarshalMaybeInaccessibleMessage(data []byte) (MaybeInaccessibleMessage, error) { + var probe struct { + Date int64 `json:"date"` + } + if err := json.Unmarshal(data, &probe); err != nil { + return nil, fmt.Errorf("MaybeInaccessibleMessage: %w", err) + } + if probe.Date == 0 { + v := &InaccessibleMessage{} + if err := json.Unmarshal(data, v); err != nil { + return nil, fmt.Errorf("InaccessibleMessage: %w", err) + } + return v, nil + } + v := &Message{} + if err := json.Unmarshal(data, v); err != nil { + return nil, fmt.Errorf("Message: %w", err) + } + return v, nil +} +{{end}} +{{else}} +{{docComment .Doc -}} +type {{.Name}} struct { +{{range .Fields}}{{docComment .Doc}}{{goField .}} +{{end}}} +{{$unionFields := unionFields .}}{{if $unionFields}} +// UnmarshalJSON decodes {{.Name}} by dispatching union-typed fields +// ({{range $i, $u := $unionFields}}{{if $i}}, {{end}}{{$u.Field.Name}}{{end}}) through their concrete UnmarshalXxx helpers. +func (m *{{.Name}}) UnmarshalJSON(data []byte) error { + type Alias {{.Name}} + aux := &struct { + {{range $unionFields}}{{.Field.Name}} json.RawMessage `json:"{{.Field.JSONName}},omitempty"` + {{end}}*Alias + }{Alias: (*Alias)(m)} + if err := json.Unmarshal(data, aux); err != nil { + return err + } + {{range $unionFields}}{{$f := .Field}}{{$u := .UnionName}} + if len(aux.{{$f.Name}}) > 0 && string(aux.{{$f.Name}}) != "null" { + {{if isArrayUnion $f.Type}}var raws []json.RawMessage + if err := json.Unmarshal(aux.{{$f.Name}}, &raws); err != nil { + return fmt.Errorf("decoding {{$f.JSONName}}: %w", err) + } + decoded := make([]{{$u}}, 0, len(raws)) + for i, r := range raws { + v, err := Unmarshal{{$u}}(r) + if err != nil { + return fmt.Errorf("decoding {{$f.JSONName}}[%d]: %w", i, err) + } + decoded = append(decoded, v) + } + m.{{$f.Name}} = decoded + {{else}}v, err := Unmarshal{{$u}}(aux.{{$f.Name}}) + if err != nil { + return fmt.Errorf("decoding {{$f.JSONName}}: %w", err) + } + m.{{$f.Name}} = v + {{end}} + } + {{end}} + return nil +} +{{end}} +{{end}} +{{end}} diff --git a/cmd/scrape/extra_test.go b/cmd/scrape/extra_test.go new file mode 100644 index 0000000..756a8b9 --- /dev/null +++ b/cmd/scrape/extra_test.go @@ -0,0 +1,211 @@ +package main + +import ( + "testing" + + "github.com/lukaszraczylo/go-telegram/internal/spec" + "github.com/stretchr/testify/require" +) + +// --------------------------------------------------------------------------- +// parseTypeRef — edge cases +// --------------------------------------------------------------------------- + +func TestParseTypeRef_Empty(t *testing.T) { + // Empty string → named with empty name (fallback). + got := parseTypeRef("") + require.Equal(t, spec.KindNamed, got.Kind) + require.Equal(t, "", got.Name) +} + +func TestParseTypeRef_Whitespace(t *testing.T) { + got := parseTypeRef(" Integer ") + require.Equal(t, spec.KindPrimitive, got.Kind) + require.Equal(t, "int64", got.Name) +} + +func TestParseTypeRef_True(t *testing.T) { + got := parseTypeRef("True") + require.Equal(t, spec.KindPrimitive, got.Kind) + require.Equal(t, "bool", got.Name) +} + +func TestParseTypeRef_False(t *testing.T) { + got := parseTypeRef("False") + require.Equal(t, spec.KindPrimitive, got.Kind) + require.Equal(t, "bool", got.Name) +} + +func TestParseTypeRef_FloatNumber(t *testing.T) { + got := parseTypeRef("Float number") + require.Equal(t, spec.KindPrimitive, got.Kind) + require.Equal(t, "float64", got.Name) +} + +func TestParseTypeRef_Int(t *testing.T) { + got := parseTypeRef("Int") + require.Equal(t, spec.KindPrimitive, got.Kind) + require.Equal(t, "int64", got.Name) +} + +func TestParseTypeRef_Bool(t *testing.T) { + got := parseTypeRef("Bool") + require.Equal(t, spec.KindPrimitive, got.Kind) + require.Equal(t, "bool", got.Name) +} + +func TestParseTypeRef_CommaAndUnion(t *testing.T) { + // "Foo, Bar and Baz" → oneOf{Foo, Bar, Baz} + got := parseTypeRef("InputMediaPhoto, InputMediaVideo and InputMediaDocument") + require.Equal(t, spec.KindOneOf, got.Kind) + require.Len(t, got.Variants, 3) + require.Contains(t, got.Variants, "InputMediaPhoto") + require.Contains(t, got.Variants, "InputMediaVideo") + require.Contains(t, got.Variants, "InputMediaDocument") +} + +func TestParseTypeRef_ArrayOfNothing(t *testing.T) { + // "Array of " with trailing space — TrimSpace removes the trailing space + // leaving "Array of" which does NOT match the "Array of " prefix, so it + // falls through to primitiveOrNamed and returns KindNamed (not KindArray). + got := parseTypeRef("Array of ") + require.Equal(t, spec.KindNamed, got.Kind) +} + +// --------------------------------------------------------------------------- +// splitCommaAnd +// --------------------------------------------------------------------------- + +func TestSplitCommaAnd_ThreeVariants(t *testing.T) { + got := splitCommaAnd("A, B and C") + require.Equal(t, []string{"A", "B", "C"}, got) +} + +func TestSplitCommaAnd_FourVariants(t *testing.T) { + got := splitCommaAnd("A, B, C and D") + require.Equal(t, []string{"A", "B", "C", "D"}, got) +} + +func TestSplitCommaAnd_ExtraSpaces(t *testing.T) { + got := splitCommaAnd(" Foo , Bar and Baz ") + require.Len(t, got, 3) +} + +// --------------------------------------------------------------------------- +// goName — edge cases +// --------------------------------------------------------------------------- + +func TestGoName_Empty(t *testing.T) { + require.Equal(t, "", goName("")) +} + +func TestGoName_SingleWord(t *testing.T) { + require.Equal(t, "Photo", goName("photo")) +} + +func TestGoName_JSON(t *testing.T) { + require.Equal(t, "JSON", goName("json")) +} + +func TestGoName_HTML(t *testing.T) { + require.Equal(t, "HTML", goName("html")) +} + +func TestGoName_HTTPS(t *testing.T) { + require.Equal(t, "HTTPS", goName("https")) +} + +func TestGoName_AlreadyUpperSegment(t *testing.T) { + // Segment that starts with uppercase letter should be passed through. + require.Equal(t, "MediaGroupID", goName("media_group_id")) +} + +// --------------------------------------------------------------------------- +// extractReturn — additional patterns +// --------------------------------------------------------------------------- + +func TestExtractReturn_ArrayPattern(t *testing.T) { + desc := "Returns an Array of Update objects." + got := extractReturn(desc) + require.Equal(t, spec.KindArray, got.Kind) + require.Equal(t, "Update", got.ElemType.Name) +} + +func TestExtractReturn_BoolPattern(t *testing.T) { + desc := "Returns True on success." + got := extractReturn(desc) + require.Equal(t, spec.KindPrimitive, got.Kind) + require.Equal(t, "bool", got.Name) +} + +func TestExtractReturn_OnSuccessTrueIsReturned(t *testing.T) { + desc := "On success, true is returned." + got := extractReturn(desc) + require.Equal(t, spec.KindPrimitive, got.Kind) + require.Equal(t, "bool", got.Name) +} + +func TestExtractReturn_NamedObject(t *testing.T) { + desc := "On success, returns a Message object." + got := extractReturn(desc) + require.Equal(t, spec.KindNamed, got.Kind) + require.Equal(t, "Message", got.Name) +} + +func TestExtractReturn_MessageOrBool(t *testing.T) { + desc := "On success, the edited Message is returned, otherwise True is returned." + got := extractReturn(desc) + require.Equal(t, spec.KindNamed, got.Kind) + require.Equal(t, "MessageOrBool", got.Name) +} + +func TestExtractReturn_InFormOf(t *testing.T) { + desc := "The answer is provided in form of a ChatInviteLink object." + got := extractReturn(desc) + require.Equal(t, spec.KindNamed, got.Kind) + require.Equal(t, "ChatInviteLink", got.Name) +} + +func TestExtractReturn_Fallback(t *testing.T) { + // No recognized pattern → bool fallback. + got := extractReturn("This method does something interesting.") + require.Equal(t, spec.KindPrimitive, got.Kind) + require.Equal(t, "bool", got.Name) +} + +func TestExtractReturn_MultipleReturnsFirstWins(t *testing.T) { + // Doc with multiple "Returns" phrases — first matching pattern should win. + // The indefinite-article pattern ("Returns a X object") appears earlier in + // the priority list than "Returns True", so it matches "Returns a Message" + // before the bool pattern can fire. + desc := "Returns True on success. You can also Returns a Message object later." + got := extractReturn(desc) + // The indefinite-article pattern fires first → returns Message (KindNamed). + require.Equal(t, spec.KindNamed, got.Kind) + require.Equal(t, "Message", got.Name) +} + +// --------------------------------------------------------------------------- +// extractVersion +// --------------------------------------------------------------------------- + +func TestExtractVersion_InTitle(t *testing.T) { + sections := []section{ + {Title: "Bot API 7.3", Description: ""}, + } + require.Equal(t, "7.3", extractVersion(sections)) +} + +func TestExtractVersion_InDescription(t *testing.T) { + sections := []section{ + {Title: "April 2024", Description: "Released Bot API 7.2."}, + } + require.Equal(t, "7.2", extractVersion(sections)) +} + +func TestExtractVersion_NotFound(t *testing.T) { + sections := []section{ + {Title: "Introduction", Description: "Welcome to the API."}, + } + require.Equal(t, "", extractVersion(sections)) +} diff --git a/cmd/scrape/main.go b/cmd/scrape/main.go new file mode 100644 index 0000000..90d7eaa --- /dev/null +++ b/cmd/scrape/main.go @@ -0,0 +1,77 @@ +// Command scrape parses the Telegram Bot API HTML page into the IR +// (internal/spec.API) and writes it to internal/spec/api.json. +// +// Usage: +// +// scrape -input (read HTML from local file) +// scrape -url (fetch HTML from URL; default: live docs) +// scrape -output (output path; default: internal/spec/api.json) +package main + +import ( + "errors" + "flag" + "fmt" + "io" + "net/http" + "os" + "time" + + "github.com/lukaszraczylo/go-telegram/internal/spec" +) + +const defaultURL = "https://core.telegram.org/bots/api" + +func main() { + input := flag.String("input", "", "local HTML file (overrides -url)") + url := flag.String("url", defaultURL, "URL to fetch HTML from") + output := flag.String("output", "internal/spec/api.json", "output path") + overridesPath := flag.String("overrides", "internal/spec/overrides.json", "path to overrides JSON") + flag.Parse() + + if err := run(*input, *url, *output, *overridesPath); err != nil { + fmt.Fprintln(os.Stderr, "scrape:", err) + os.Exit(1) + } +} + +func run(input, url, output, overridesPath string) error { + htmlBytes, err := readHTML(input, url) + if err != nil { + return fmt.Errorf("read html: %w", err) + } + + api, err := scrape(htmlBytes) + if err != nil { + return fmt.Errorf("scrape: %w", err) + } + + overrides, err := spec.LoadOverrides(overridesPath) + if err != nil { + return fmt.Errorf("load overrides: %w", err) + } + overrides.Apply(api) + + return writeJSON(output, api) +} + +func readHTML(input, url string) ([]byte, error) { + if input != "" { + return os.ReadFile(input) + } + c := &http.Client{Timeout: 30 * time.Second} + req, err := http.NewRequest(http.MethodGet, url, nil) + if err != nil { + return nil, err + } + req.Header.Set("User-Agent", "go-telegram codegen scraper") + resp, err := c.Do(req) + if err != nil { + return nil, err + } + defer func() { _ = resp.Body.Close() }() + if resp.StatusCode != http.StatusOK { + return nil, errors.New(resp.Status) + } + return io.ReadAll(resp.Body) +} diff --git a/cmd/scrape/method.go b/cmd/scrape/method.go new file mode 100644 index 0000000..8d16e38 --- /dev/null +++ b/cmd/scrape/method.go @@ -0,0 +1,149 @@ +package main + +import ( + "regexp" + "strings" + + "github.com/lukaszraczylo/go-telegram/internal/spec" +) + +// extractReturn pulls the return type from a method's description prose. +// +// Patterns we handle (in priority order): +// +// "Returns an Array of X" / "On success, an Array of X is returned" → array of named X +// "an array of X of the sent messages is returned" → array of named X +// "the edited X is returned, otherwise True is returned" → XOrBool +// "Returns ... as a X object" / "Returns ... as X object" → named X +// "Returns ... as String on success" → string +// "On success, returns a X object" / "Returns a X object" → named X (indefinite article) +// "On success, an? X is returned" / "On success, the X is returned" → named X +// "Returns True" / "On success, true is returned" → bool +// "Returns the verb-ed X" → named X +// "On success, X is returned" → named X +// "Returns X on success" (no article) → named X +// "in form of a X" → named X +// fallback: bool +func extractReturn(desc string) spec.TypeRef { + // Normalise; strip *bold* markers because Telegram uses italics. + d := strings.ReplaceAll(desc, "*", "") + + patterns := []struct { + re *regexp.Regexp + fn func([]string) spec.TypeRef + }{ + // Array patterns first — most specific. + {regexp.MustCompile(`Returns an? [Aa]rray of ([A-Z][A-Za-z0-9]+)`), func(m []string) spec.TypeRef { + elem := primitiveOrNamed(m[1]) + return spec.TypeRef{Kind: spec.KindArray, ElemType: &elem} + }}, + {regexp.MustCompile(`On success(?:,)?\s+(?:an?\s+)?[Aa]rray of ([A-Z][A-Za-z0-9]+)(?:\s+objects?)?\s+(?:is|are|that\s+\S+\s+\S+\s+)?(?:is |are )?returned`), func(m []string) spec.TypeRef { + elem := primitiveOrNamed(m[1]) + return spec.TypeRef{Kind: spec.KindArray, ElemType: &elem} + }}, + // "an array of X of the sent messages is returned" (ForwardMessages/CopyMessages shape). + {regexp.MustCompile(`(?:[Oo]n success[,.]?\s+)?an? array of ([A-Z][A-Za-z0-9]+)(?:\s+of [^.]+?)?\s+(?:objects\s+)?(?:is|are) returned`), func(m []string) spec.TypeRef { + elem := primitiveOrNamed(m[1]) + return spec.TypeRef{Kind: spec.KindArray, ElemType: &elem} + }}, + // "Message or True" conditional return → XOrBool sentinel. + {regexp.MustCompile(`the (?:edited|sent|stopped)?\s*([A-Z][A-Za-z0-9]+)\s+is returned, otherwise (?:True|true) is returned`), func(m []string) spec.TypeRef { + return spec.TypeRef{Kind: spec.KindNamed, Name: m[1] + "OrBool"} + }}, + // "Returns ... as a X object" / "Returns ... as X object" (with or without article). + {regexp.MustCompile(`[Rr]eturns? (?:.+? )?as (?:an? )?([A-Z][A-Za-z0-9]+) object`), func(m []string) spec.TypeRef { + return primitiveOrNamed(m[1]) + }}, + // "Returns ... as String on success" / "Returns ... as X on success" (named type after "as"). + {regexp.MustCompile(`[Rr]eturns? (?:.+? )?as ([A-Z][A-Za-z0-9]+) on success`), func(m []string) spec.TypeRef { + return primitiveOrNamed(m[1]) + }}, + // Indefinite article: "On success, returns a X object" / "Returns a X object". + {regexp.MustCompile(`(?:[Oo]n success[,.]?\s+)?[Rr]eturns? an? ([A-Z][A-Za-z0-9]+)(?:\s+object)?`), func(m []string) spec.TypeRef { + return primitiveOrNamed(m[1]) + }}, + // "On success, an? X is returned" / "On success, the stopped X is returned". + {regexp.MustCompile(`On success,\s+(?:an?|the)?\s*(?:[a-z]+\s+)?([A-Z][A-Za-z0-9]+)(?:\s+object)?\s+is returned`), func(m []string) spec.TypeRef { + return primitiveOrNamed(m[1]) + }}, + // Explicit True — must come before the broad "Returns X" pattern. + {regexp.MustCompile(`Returns True`), func(m []string) spec.TypeRef { + return spec.TypeRef{Kind: spec.KindPrimitive, Name: "bool"} + }}, + {regexp.MustCompile(`(?i)on success, true is returned`), func(m []string) spec.TypeRef { + return spec.TypeRef{Kind: spec.KindPrimitive, Name: "bool"} + }}, + // "Returns the verb-ed X" — accepts any verb prefix (uploaded, revoked, …). + {regexp.MustCompile(`Returns (?:the|an?)\s+(?:[a-z]+ )?([A-Z][A-Za-z0-9]+)`), func(m []string) spec.TypeRef { + return primitiveOrNamed(m[1]) + }}, + // "On success, X is returned" (no article). + {regexp.MustCompile(`On success(?:,)?\s+(?:the\s+)?(?:newly\s+)?(?:edited\s+|sent\s+|created\s+|updated\s+)?([A-Z][A-Za-z0-9]+)\s+is returned`), func(m []string) spec.TypeRef { + return primitiveOrNamed(m[1]) + }}, + // "Returns X on success" (no article, e.g. "Returns OwnedGifts on success"). + {regexp.MustCompile(`[Rr]eturns ([A-Z][A-Za-z0-9]+) on success`), func(m []string) spec.TypeRef { + return primitiveOrNamed(m[1]) + }}, + // "in form of a X". + {regexp.MustCompile(`in (?:the )?form of (?:a )?([A-Z][A-Za-z0-9]+)`), func(m []string) spec.TypeRef { + return primitiveOrNamed(m[1]) + }}, + } + for _, p := range patterns { + if m := p.re.FindStringSubmatch(d); m != nil { + return p.fn(m) + } + } + // Fallback: bool. Better than panic; method-by-method tests would + // catch any regression. + return spec.TypeRef{Kind: spec.KindPrimitive, Name: "bool"} +} + +// hasFilesParams returns true if any param mentions InputFile (the +// scraper convention triggering multipart/form-data). +func hasFilesParams(params []spec.Field) bool { + for _, p := range params { + if mentionsInputFile(p.Type) { + return true + } + } + return false +} + +func mentionsInputFile(tr spec.TypeRef) bool { + switch tr.Kind { + case spec.KindNamed: + return tr.Name == "InputFile" || strings.HasPrefix(tr.Name, "InputMedia") || strings.HasPrefix(tr.Name, "InputPaidMedia") + case spec.KindArray: + if tr.ElemType != nil { + return mentionsInputFile(*tr.ElemType) + } + case spec.KindOneOf: + for _, v := range tr.Variants { + if v == "InputFile" || strings.HasPrefix(v, "InputMedia") || strings.HasPrefix(v, "InputPaidMedia") { + return true + } + } + } + return false +} + +// extractVersion finds the API version string in a "Bot API X.Y[.Z]" heading. +var versionRE = regexp.MustCompile(`Bot API (\d+\.\d+(?:\.\d+)?)`) + +// extractVersion finds the API version string. The live docs page emits +// the version as "Bot API X.Y" inside a paragraph below +// a date heading; the small fixture uses an h4 "Bot API X.Y" instead. +// Both shapes are handled here by also scanning section descriptions. +func extractVersion(sections []section) string { + for _, s := range sections { + if m := versionRE.FindStringSubmatch(s.Title); m != nil { + return m[1] + } + if m := versionRE.FindStringSubmatch(s.Description); m != nil { + return m[1] + } + } + return "" +} diff --git a/cmd/scrape/method_test.go b/cmd/scrape/method_test.go new file mode 100644 index 0000000..d8997ae --- /dev/null +++ b/cmd/scrape/method_test.go @@ -0,0 +1,76 @@ +package main + +import ( + "testing" + + "github.com/stretchr/testify/require" + + "github.com/lukaszraczylo/go-telegram/internal/spec" +) + +func TestExtractReturn(t *testing.T) { + cases := []struct { + in string + want spec.TypeRef + }{ + {"Returns basic information about the bot in form of a User object.", spec.TypeRef{Kind: spec.KindNamed, Name: "User"}}, + {"On success, the sent Message is returned.", spec.TypeRef{Kind: spec.KindNamed, Name: "Message"}}, + {"Returns an Array of Update objects.", spec.TypeRef{Kind: spec.KindArray, ElemType: &spec.TypeRef{Kind: spec.KindNamed, Name: "Update"}}}, + {"Returns True on success.", spec.TypeRef{Kind: spec.KindPrimitive, Name: "bool"}}, + {"On success, True is returned.", spec.TypeRef{Kind: spec.KindPrimitive, Name: "bool"}}, + // Issue 5: "Message or True" conditional return → MessageOrBool sentinel. + {"On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned.", spec.TypeRef{Kind: spec.KindNamed, Name: "MessageOrBool"}}, + // Issue 1: new phrasings. + {"On success, returns a WebhookInfo object.", spec.TypeRef{Kind: spec.KindNamed, Name: "WebhookInfo"}}, + {"Returns a UserProfilePhotos object.", spec.TypeRef{Kind: spec.KindNamed, Name: "UserProfilePhotos"}}, + {"Returns the uploaded File.", spec.TypeRef{Kind: spec.KindNamed, Name: "File"}}, + {"On success, the stopped Poll is returned.", spec.TypeRef{Kind: spec.KindNamed, Name: "Poll"}}, + {"On success, an Array of MessageId is returned.", spec.TypeRef{Kind: spec.KindArray, ElemType: &spec.TypeRef{Kind: spec.KindNamed, Name: "MessageId"}}}, + {"On success, an array of Message objects that were sent is returned.", spec.TypeRef{Kind: spec.KindArray, ElemType: &spec.TypeRef{Kind: spec.KindNamed, Name: "Message"}}}, + // ForwardMessages/CopyMessages shape: "an array of X of the sent messages is returned". + {"On success, an array of MessageId of the sent messages is returned.", spec.TypeRef{Kind: spec.KindArray, ElemType: &spec.TypeRef{Kind: spec.KindNamed, Name: "MessageId"}}}, + // "Returns X on success" (no article) — OwnedGifts, StarAmount, Story, MenuButton, etc. + {"Returns the gifts received and owned by a managed business account. Returns OwnedGifts on success.", spec.TypeRef{Kind: spec.KindNamed, Name: "OwnedGifts"}}, + {"Returns StarAmount on success.", spec.TypeRef{Kind: spec.KindNamed, Name: "StarAmount"}}, + {"Posts a story on behalf of a managed business account. Returns Story on success.", spec.TypeRef{Kind: spec.KindNamed, Name: "Story"}}, + {"Returns MenuButton on success.", spec.TypeRef{Kind: spec.KindNamed, Name: "MenuButton"}}, + // "Returns ... as X object" (no article before type) — ChatInviteLink variants. + {"Returns the new invite link as ChatInviteLink object.", spec.TypeRef{Kind: spec.KindNamed, Name: "ChatInviteLink"}}, + {"Returns the revoked invite link as ChatInviteLink object.", spec.TypeRef{Kind: spec.KindNamed, Name: "ChatInviteLink"}}, + // "Returns ... as a X object" (with article) — createForumTopic. + {"Returns information about the created topic as a ForumTopic object.", spec.TypeRef{Kind: spec.KindNamed, Name: "ForumTopic"}}, + // "Returns ... as String on success" — exportChatInviteLink / createInvoiceLink. + {"Returns the new invite link as String on success.", spec.TypeRef{Kind: spec.KindPrimitive, Name: "string"}}, + {"Returns the created invoice link as String on success.", spec.TypeRef{Kind: spec.KindPrimitive, Name: "string"}}, + // "Returns Int on success" — getChatMemberCount. + {"Returns Int on success.", spec.TypeRef{Kind: spec.KindPrimitive, Name: "int64"}}, + } + for _, c := range cases { + require.Equal(t, c.want, extractReturn(c.in), c.in) + } +} + +func TestHasFilesParams(t *testing.T) { + require.True(t, hasFilesParams([]spec.Field{ + {Type: spec.TypeRef{Kind: spec.KindNamed, Name: "InputFile"}}, + })) + require.True(t, hasFilesParams([]spec.Field{ + {Type: spec.TypeRef{Kind: spec.KindOneOf, Variants: []string{"InputFile", "string"}}}, + })) + require.False(t, hasFilesParams([]spec.Field{ + {Type: spec.TypeRef{Kind: spec.KindPrimitive, Name: "string"}}, + })) + // Issue 2: Array of InputMedia* union triggers HasFiles. + require.True(t, hasFilesParams([]spec.Field{ + {Type: spec.TypeRef{Kind: spec.KindArray, ElemType: &spec.TypeRef{Kind: spec.KindOneOf, Variants: []string{"InputMediaPhoto", "InputMediaVideo"}}}}, + })) +} + +func TestExtractVersion(t *testing.T) { + sections := []section{{Title: "Recent changes"}, {Title: "Bot API 7.10"}, {Title: "Available types"}} + require.Equal(t, "7.10", extractVersion(sections)) + + // Issue 4: 3-part version must not be truncated. + sections3 := []section{{Description: "Bot API 8.0.1"}} + require.Equal(t, "8.0.1", extractVersion(sections3)) +} diff --git a/cmd/scrape/scrape.go b/cmd/scrape/scrape.go new file mode 100644 index 0000000..8c30bf8 --- /dev/null +++ b/cmd/scrape/scrape.go @@ -0,0 +1,84 @@ +package main + +import ( + "bytes" + "fmt" + "github.com/goccy/go-json" + "os" + + "golang.org/x/net/html" + + "github.com/lukaszraczylo/go-telegram/internal/spec" +) + +// scrape (the package-level implementation overriding the stub in main.go; +// remove the stub from main.go in this task) parses the docs HTML into IR. +func scrape(htmlBytes []byte) (*spec.API, error) { + doc, err := html.Parse(bytes.NewReader(htmlBytes)) + if err != nil { + return nil, fmt.Errorf("html parse: %w", err) + } + sections := walk(doc) + api := &spec.API{Version: extractVersion(sections)} + for _, s := range sections { + switch { + case isMethodTitle(s.Title): + api.Methods = append(api.Methods, methodFromSection(s)) + case isTypeTitle(s.Title): + api.Types = append(api.Types, typeFromSection(s)) + } + } + return api, nil +} + +func typeFromSection(s section) spec.TypeDecl { + td := spec.TypeDecl{Name: s.Title, Doc: s.Description} + if len(s.Tables) > 0 { + td.Fields = parseFieldsTable(s.Tables[0]) + } else if len(s.Lists) > 0 { + // Union: extract variant names from
  • ...
  • . + td.OneOf = extractListLinks(s.Lists[0]) + } + return td +} + +func methodFromSection(s section) spec.MethodDecl { + md := spec.MethodDecl{Name: s.Title, Doc: s.Description, Returns: extractReturn(s.Description)} + if len(s.Tables) > 0 { + md.Params = parseParamsTable(s.Tables[0]) + } + md.HasFiles = hasFilesParams(md.Params) + return md +} + +// extractListLinks pulls anchor texts out of a
      : each
    • X
    • +// contributes "X" to the result. Used for union variant lists. +func extractListLinks(ul *html.Node) []string { + var names []string + var visit func(*html.Node) + visit = func(n *html.Node) { + if n.Type == html.ElementNode && n.Data == "a" { + names = append(names, textOf(n)) + return + } + for c := n.FirstChild; c != nil; c = c.NextSibling { + visit(c) + } + } + visit(ul) + return names +} + +// writeJSON marshals the IR with stable, human-readable formatting and +// writes it to path. Marshalling is deterministic: types and methods +// preserve scrape order; struct fields use IR-defined order. +func writeJSON(path string, api *spec.API) error { + var buf bytes.Buffer + enc := json.NewEncoder(&buf) + enc.SetIndent("", " ") + enc.SetEscapeHTML(false) + if err := enc.Encode(api); err != nil { + return err + } + return os.WriteFile(path, buf.Bytes(), 0o644) +} diff --git a/cmd/scrape/scrape_test.go b/cmd/scrape/scrape_test.go new file mode 100644 index 0000000..1becb94 --- /dev/null +++ b/cmd/scrape/scrape_test.go @@ -0,0 +1,36 @@ +package main + +import ( + "bytes" + "encoding/json" + "flag" + "os" + "testing" + + "github.com/stretchr/testify/require" +) + +var update = flag.Bool("update", false, "update golden files") + +func TestScrape_Golden_SmallFixture(t *testing.T) { + htmlBytes, err := os.ReadFile("../../testdata/html/small_fixture.html") + require.NoError(t, err) + + api, err := scrape(htmlBytes) + require.NoError(t, err) + + var buf bytes.Buffer + enc := json.NewEncoder(&buf) + enc.SetIndent("", " ") + enc.SetEscapeHTML(false) + require.NoError(t, enc.Encode(api)) + + goldenPath := "../../testdata/golden/api_small_fixture.json" + if *update { + require.NoError(t, os.WriteFile(goldenPath, buf.Bytes(), 0o644)) + return + } + expected, err := os.ReadFile(goldenPath) + require.NoError(t, err, "missing golden; run `go test -update ./cmd/scrape/...` to create") + require.Equal(t, string(expected), buf.String()) +} diff --git a/cmd/scrape/table.go b/cmd/scrape/table.go new file mode 100644 index 0000000..624aaaa --- /dev/null +++ b/cmd/scrape/table.go @@ -0,0 +1,224 @@ +package main + +import ( + "strings" + + "golang.org/x/net/html" + + "github.com/lukaszraczylo/go-telegram/internal/spec" +) + +// parseFieldsTable walks a for an object-type definition. +// Columns: Field, Type, Description (optional column orders are not +// supported; Telegram's docs use a stable layout). +// +// Optional fields are detected via the "Optional." prefix in the +// description text, which is the documented convention. +func parseFieldsTable(t *html.Node) []spec.Field { + rows := tableRows(t) + if len(rows) == 0 { + return nil + } + var fields []spec.Field + for _, row := range rows[1:] { // skip header + cells := rowCells(row) + if len(cells) < 3 { + continue + } + jname := strings.TrimSpace(textOf(cells[0])) + typeText := strings.TrimSpace(textOf(cells[1])) + desc := strings.TrimSpace(textOf(cells[2])) + + required := !strings.HasPrefix(desc, "Optional.") + fields = append(fields, spec.Field{ + Name: goName(jname), + JSONName: jname, + Type: parseTypeRef(typeText), + Required: required, + Doc: desc, + }) + } + return fields +} + +// parseParamsTable walks a
      for a method definition. +// Columns: Parameter, Type, Required, Description. +func parseParamsTable(t *html.Node) []spec.Field { + rows := tableRows(t) + if len(rows) == 0 { + return nil + } + var params []spec.Field + for _, row := range rows[1:] { + cells := rowCells(row) + if len(cells) < 4 { + continue + } + jname := strings.TrimSpace(textOf(cells[0])) + typeText := strings.TrimSpace(textOf(cells[1])) + req := strings.EqualFold(strings.TrimSpace(textOf(cells[2])), "Yes") + desc := strings.TrimSpace(textOf(cells[3])) + + params = append(params, spec.Field{ + Name: goName(jname), + JSONName: jname, + Type: parseTypeRef(typeText), + Required: req, + Doc: desc, + }) + } + return params +} + +// tableRows returns the children of a
      , skipping over +// any / wrappers. +func tableRows(t *html.Node) []*html.Node { + var rows []*html.Node + var visit func(*html.Node) + visit = func(n *html.Node) { + if n.Type == html.ElementNode && n.Data == "tr" { + rows = append(rows, n) + return + } + for c := n.FirstChild; c != nil; c = c.NextSibling { + visit(c) + } + } + visit(t) + return rows +} + +// rowCells returns the . +func rowCells(tr *html.Node) []*html.Node { + var cells []*html.Node + for c := tr.FirstChild; c != nil; c = c.NextSibling { + if c.Type == html.ElementNode && (c.Data == "td" || c.Data == "th") { + cells = append(cells, c) + } + } + return cells +} + +// goName converts a snake_case JSON identifier to PascalCase. +// Special-cases common acronyms used in the Telegram docs. +func goName(s string) string { + if s == "" { + return "" + } + parts := strings.Split(s, "_") + var b strings.Builder + for _, p := range parts { + if p == "" { + continue + } + switch p { + case "id": + b.WriteString("ID") + case "url": + b.WriteString("URL") + case "ip": + b.WriteString("IP") + case "https": + b.WriteString("HTTPS") + case "json": + b.WriteString("JSON") + case "html": + b.WriteString("HTML") + default: + if p[0] >= 'a' && p[0] <= 'z' { + b.WriteByte(p[0] - 'a' + 'A') + b.WriteString(p[1:]) + } else { + b.WriteString(p) + } + } + } + return b.String() +} + +// parseTypeRef decodes the type-cell text into a spec.TypeRef. +// +// Recognised shapes: +// +// "Integer" → primitive int64 +// "String" → primitive string +// "Boolean" / "True" → primitive bool +// "Float" / "Float number"→ primitive float64 +// "Array of X" → array of (parseTypeRef of X) +// "Array of Array of X" → array of array of X +// "Foo" → named Foo +// "Foo or Bar" → oneOf {Foo, Bar} +// "InputFile or String" → oneOf (caller may translate to InputFile) +// +// parseTypeRef decodes the type-cell text into a spec.TypeRef. +// +// Recognised shapes: +// +// "Integer" → primitive int64 +// "String" → primitive string +// "Boolean" / "True" → primitive bool +// "Float" / "Float number"→ primitive float64 +// "Array of X" → array of (parseTypeRef of X) +// "Array of Array of X" → array of array of X +// "Foo" → named Foo +// "Foo or Bar" → oneOf {Foo, Bar} +// "Foo, Bar and Baz" → oneOf {Foo, Bar, Baz} (Telegram's comma+and union form) +// "InputFile or String" → oneOf (caller may translate to InputFile) +func parseTypeRef(s string) spec.TypeRef { + s = strings.TrimSpace(s) + // Array prefix. + if rest, ok := strings.CutPrefix(s, "Array of "); ok { + elem := parseTypeRef(rest) + return spec.TypeRef{Kind: spec.KindArray, ElemType: &elem} + } + // Comma-and union ("X, Y, Z and W") — used by Telegram for ≥3-variant unions. + if strings.Contains(s, ", ") && strings.Contains(s, " and ") { + parts := splitCommaAnd(s) + variants := make([]string, 0, len(parts)) + for _, p := range parts { + variants = append(variants, primitiveOrNamed(strings.TrimSpace(p)).Name) + } + return spec.TypeRef{Kind: spec.KindOneOf, Variants: variants} + } + // "X or Y" union (the 2-variant form). + if strings.Contains(s, " or ") { + parts := strings.Split(s, " or ") + variants := make([]string, 0, len(parts)) + for _, p := range parts { + variants = append(variants, primitiveOrNamed(strings.TrimSpace(p)).Name) + } + return spec.TypeRef{Kind: spec.KindOneOf, Variants: variants} + } + return primitiveOrNamed(s) +} + +// splitCommaAnd splits "A, B, C and D" → ["A", "B", "C", "D"]. +func splitCommaAnd(s string) []string { + // Replace " and " with ", " then split on ", ". + s = strings.ReplaceAll(s, " and ", ", ") + parts := strings.Split(s, ", ") + out := make([]string, 0, len(parts)) + for _, p := range parts { + if p = strings.TrimSpace(p); p != "" { + out = append(out, p) + } + } + return out +} + +// primitiveOrNamed maps a single-word type cell to either a primitive +// or a named TypeRef. Unrecognised words are treated as named types. +func primitiveOrNamed(s string) spec.TypeRef { + switch s { + case "Integer", "Int": + return spec.TypeRef{Kind: spec.KindPrimitive, Name: "int64"} + case "String": + return spec.TypeRef{Kind: spec.KindPrimitive, Name: "string"} + case "Boolean", "Bool", "True", "False": + return spec.TypeRef{Kind: spec.KindPrimitive, Name: "bool"} + case "Float", "Float number": + return spec.TypeRef{Kind: spec.KindPrimitive, Name: "float64"} + default: + return spec.TypeRef{Kind: spec.KindNamed, Name: s} + } +} diff --git a/cmd/scrape/table_test.go b/cmd/scrape/table_test.go new file mode 100644 index 0000000..3c305fb --- /dev/null +++ b/cmd/scrape/table_test.go @@ -0,0 +1,92 @@ +package main + +import ( + "testing" + + "github.com/stretchr/testify/require" + + "github.com/lukaszraczylo/go-telegram/internal/spec" +) + +func TestGoName(t *testing.T) { + cases := []struct{ in, want string }{ + {"chat_id", "ChatID"}, + {"first_name", "FirstName"}, + {"is_bot", "IsBot"}, + {"url", "URL"}, + {"ip_address", "IPAddress"}, + {"language_code", "LanguageCode"}, + {"webhook_URL", "WebhookURL"}, // Issue 3: already-uppercase segment must not be corrupted. + } + for _, c := range cases { + require.Equal(t, c.want, goName(c.in), c.in) + } +} + +func TestParseTypeRef(t *testing.T) { + cases := []struct { + in string + want spec.TypeRef + }{ + {"Integer", spec.TypeRef{Kind: spec.KindPrimitive, Name: "int64"}}, + {"String", spec.TypeRef{Kind: spec.KindPrimitive, Name: "string"}}, + {"Boolean", spec.TypeRef{Kind: spec.KindPrimitive, Name: "bool"}}, + {"Float", spec.TypeRef{Kind: spec.KindPrimitive, Name: "float64"}}, + {"Message", spec.TypeRef{Kind: spec.KindNamed, Name: "Message"}}, + {"Array of Update", spec.TypeRef{Kind: spec.KindArray, ElemType: &spec.TypeRef{Kind: spec.KindNamed, Name: "Update"}}}, + {"Array of Array of PhotoSize", spec.TypeRef{Kind: spec.KindArray, ElemType: &spec.TypeRef{Kind: spec.KindArray, ElemType: &spec.TypeRef{Kind: spec.KindNamed, Name: "PhotoSize"}}}}, + {"Integer or String", spec.TypeRef{Kind: spec.KindOneOf, Variants: []string{"int64", "string"}}}, + {"InputFile or String", spec.TypeRef{Kind: spec.KindOneOf, Variants: []string{"InputFile", "string"}}}, + } + for _, c := range cases { + require.Equal(t, c.want, parseTypeRef(c.in), c.in) + } +} + +func TestParseFieldsTable_FromFixture(t *testing.T) { + doc := parse(t, "../../testdata/html/small_fixture.html") + sections := walk(doc) + var user *section + for i := range sections { + if sections[i].Title == "User" { + user = §ions[i] + break + } + } + require.NotNil(t, user) + require.Len(t, user.Tables, 1) + + fields := parseFieldsTable(user.Tables[0]) + require.Len(t, fields, 4) + require.Equal(t, "ID", fields[0].Name) + require.Equal(t, "id", fields[0].JSONName) + require.Equal(t, spec.KindPrimitive, fields[0].Type.Kind) + require.True(t, fields[0].Required) + + require.Equal(t, "LastName", fields[3].Name) + require.False(t, fields[3].Required) // "Optional." prefix +} + +func TestParseParamsTable_FromFixture(t *testing.T) { + doc := parse(t, "../../testdata/html/small_fixture.html") + sections := walk(doc) + var sm *section + for i := range sections { + if sections[i].Title == "sendMessage" { + sm = §ions[i] + break + } + } + require.NotNil(t, sm) + require.Len(t, sm.Tables, 1) + + params := parseParamsTable(sm.Tables[0]) + require.Len(t, params, 3) + require.Equal(t, "ChatID", params[0].Name) + require.True(t, params[0].Required) + require.Equal(t, spec.KindOneOf, params[0].Type.Kind) + require.Equal(t, []string{"int64", "string"}, params[0].Type.Variants) + + require.Equal(t, "ParseMode", params[2].Name) + require.False(t, params[2].Required) // "Optional" +} diff --git a/cmd/scrape/walker.go b/cmd/scrape/walker.go new file mode 100644 index 0000000..18f72a9 --- /dev/null +++ b/cmd/scrape/walker.go @@ -0,0 +1,137 @@ +package main + +import ( + "strings" + + "golang.org/x/net/html" +) + +// section is an h4-anchored block of the docs page. Title is the +// heading text (e.g. "User" or "sendMessage"). Description is the +// concatenation of immediately-following

      paragraphs (until the +// next h4 / h3 / table / list). Tables and Lists hold raw nodes for +// later parsing by the table/oneof extractors. +type section struct { + Title string + Description string + Tables []*html.Node //

      (or ) children of a
      nodes + Lists []*html.Node //
        nodes (used for oneof variant lists) +} + +// walk parses the page and returns sections in document order. +// Sections whose title contains a space (e.g. "Bot API 7.10") are +// included; later passes ignore them or treat them specially. +func walk(doc *html.Node) []section { + var ( + sections []section + current *section + ) + + var visit func(n *html.Node) + visit = func(n *html.Node) { + if n.Type == html.ElementNode { + switch n.Data { + case "h4": + if current != nil { + sections = append(sections, *current) + } + current = §ion{Title: textOf(n)} + // Don't recurse into the heading; we already have its text. + return + case "h3": + // h3 (e.g. "Available methods") delimits a section; + // flush the current h4 section but do not start a new one. + if current != nil { + sections = append(sections, *current) + current = nil + } + return + case "p": + if current != nil { + if current.Description != "" { + current.Description += "\n" + } + current.Description += strings.TrimSpace(textOf(n)) + } + return + case "table": + if current != nil { + current.Tables = append(current.Tables, n) + } + return + case "ul": + if current != nil { + current.Lists = append(current.Lists, n) + } + return + } + } + for c := n.FirstChild; c != nil; c = c.NextSibling { + visit(c) + } + } + visit(doc) + if current != nil { + sections = append(sections, *current) + } + return sections +} + +// textOf returns the concatenated text content of n and descendants, +// with adjacent whitespace collapsed to single spaces. +func textOf(n *html.Node) string { + var sb strings.Builder + var w func(*html.Node) + w = func(n *html.Node) { + if n.Type == html.TextNode { + sb.WriteString(n.Data) + return + } + for c := n.FirstChild; c != nil; c = c.NextSibling { + w(c) + } + } + w(n) + return collapseWS(sb.String()) +} + +func collapseWS(s string) string { + var b strings.Builder + prevSpace := false + for _, r := range s { + if r == ' ' || r == '\t' || r == '\n' || r == '\r' { + if !prevSpace { + b.WriteByte(' ') + } + prevSpace = true + continue + } + prevSpace = false + b.WriteRune(r) + } + return strings.TrimSpace(b.String()) +} + +// isMethodTitle returns true for headings that look like method names +// (camelCase starting with a lowercase letter; e.g. "sendMessage"). +func isMethodTitle(s string) bool { + if s == "" { + return false + } + r := s[0] + return r >= 'a' && r <= 'z' +} + +// isTypeTitle returns true for headings that look like type names +// (PascalCase; e.g. "Message"). Allows a leading-uppercase only; +// excludes spaces (which would denote a header like "Bot API 7.10"). +func isTypeTitle(s string) bool { + if s == "" { + return false + } + r := s[0] + if r < 'A' || r > 'Z' { + return false + } + return !strings.Contains(s, " ") +} diff --git a/cmd/scrape/walker_test.go b/cmd/scrape/walker_test.go new file mode 100644 index 0000000..c079403 --- /dev/null +++ b/cmd/scrape/walker_test.go @@ -0,0 +1,69 @@ +package main + +import ( + "os" + "strings" + "testing" + + "github.com/stretchr/testify/require" + "golang.org/x/net/html" +) + +func parse(t *testing.T, path string) *html.Node { + t.Helper() + f, err := os.Open(path) + require.NoError(t, err) + defer f.Close() + doc, err := html.Parse(f) + require.NoError(t, err) + return doc +} + +func TestWalk_FixtureSections(t *testing.T) { + doc := parse(t, "../../testdata/html/small_fixture.html") + sections := walk(doc) + + titles := make([]string, 0, len(sections)) + for _, s := range sections { + titles = append(titles, s.Title) + } + + require.Contains(t, titles, "User") + require.Contains(t, titles, "ChatMember") + require.Contains(t, titles, "getMe") + require.Contains(t, titles, "sendMessage") + require.Contains(t, titles, "sendDocument") + require.Contains(t, titles, "getUpdates") + require.Contains(t, titles, "Bot API 7.10") +} + +func TestIsMethodTitle(t *testing.T) { + require.True(t, isMethodTitle("sendMessage")) + require.True(t, isMethodTitle("getMe")) + require.False(t, isMethodTitle("Message")) + require.False(t, isMethodTitle("")) + require.False(t, isMethodTitle("Bot API 7.10")) +} + +func TestIsTypeTitle(t *testing.T) { + require.True(t, isTypeTitle("Message")) + require.True(t, isTypeTitle("ChatMember")) + require.False(t, isTypeTitle("sendMessage")) + require.False(t, isTypeTitle("Bot API 7.10")) + require.False(t, isTypeTitle("")) +} + +func TestSection_DescriptionAndTables(t *testing.T) { + doc := parse(t, "../../testdata/html/small_fixture.html") + sections := walk(doc) + var sm *section + for i, s := range sections { + if s.Title == "sendMessage" { + sm = §ions[i] + break + } + } + require.NotNil(t, sm) + require.True(t, strings.Contains(sm.Description, "Use this method to send text messages")) + require.Len(t, sm.Tables, 1) +} diff --git a/dispatch/context.go b/dispatch/context.go new file mode 100644 index 0000000..e5b6f4c --- /dev/null +++ b/dispatch/context.go @@ -0,0 +1,40 @@ +// Package dispatch provides a typed router for Telegram updates. It +// consumes any transport.Updater and dispatches updates to handlers +// registered by command, regex, or update-payload kind. +package dispatch + +import ( + "context" + + "github.com/lukaszraczylo/go-telegram/api" + "github.com/lukaszraczylo/go-telegram/client" +) + +// Context bundles the per-update state every handler receives. +// +// Ctx is the request context propagated from Router.Run; cancelling the +// run cancels every handler. +// +// Bot is the API client. Handlers reply by calling api.SendMessage(c.Ctx, +// c.Bot, ...) etc. +// +// Update is the raw update; payload-typed handlers also receive a +// narrowed pointer to one of its sub-fields. +// +// Values is a per-update bag matchers populate. Conventional keys: +// +// "command": string, the matched bot command (e.g. "/start") +// "command_args": string, everything after the command +// "regex_match": []string, regex sub-matches when OnText matches +type Context struct { + Ctx context.Context + Bot *client.Bot + Update *api.Update + Values map[string]any +} + +// NewContext constructs a Context. Used by Router internally; exposed for +// custom test harnesses. +func NewContext(ctx context.Context, b *client.Bot, u *api.Update) *Context { + return &Context{Ctx: ctx, Bot: b, Update: u, Values: map[string]any{}} +} diff --git a/dispatch/conversation/conversation_test.go b/dispatch/conversation/conversation_test.go new file mode 100644 index 0000000..6a429a7 --- /dev/null +++ b/dispatch/conversation/conversation_test.go @@ -0,0 +1,494 @@ +package conversation_test + +import ( + "context" + "strings" + "sync" + "sync/atomic" + "testing" + + "github.com/lukaszraczylo/go-telegram/api" + "github.com/lukaszraczylo/go-telegram/client" + "github.com/lukaszraczylo/go-telegram/dispatch" + "github.com/lukaszraczylo/go-telegram/dispatch/conversation" + "github.com/stretchr/testify/require" +) + +// ---- helpers --------------------------------------------------------------- + +func msgUpd(userID, chatID int64, text string) api.Update { + return api.Update{ + UpdateID: 1, + Message: &api.Message{ + MessageID: 1, + From: &api.User{ID: userID}, + Chat: api.Chat{ID: chatID}, + Text: text, + }, + } +} + +func makeCtx(u *api.Update) *dispatch.Context { + return dispatch.NewContext(context.Background(), client.New("t"), u) +} + +// anyMsg matches any update that has a Message. +var anyMsg = func(u *api.Update) bool { return u.Message != nil } + +// hasPrefix returns a filter matching updates whose Message.Text has prefix p. +func hasPrefix(p string) dispatch.Filter[*api.Update] { + return func(u *api.Update) bool { + return u.Message != nil && strings.HasPrefix(u.Message.Text, p) + } +} + +// fakeUpdater feeds a fixed set of updates then closes (mirrors router_test.go). +type fakeUpdater struct{ ch chan api.Update } + +func newFake(ups ...api.Update) *fakeUpdater { + ch := make(chan api.Update, len(ups)) + for _, u := range ups { + ch <- u + } + close(ch) + return &fakeUpdater{ch: ch} +} + +func (f *fakeUpdater) Updates() <-chan api.Update { return f.ch } +func (f *fakeUpdater) Run(ctx context.Context) error { <-ctx.Done(); return ctx.Err() } +func (f *fakeUpdater) Stop(ctx context.Context) error { return nil } + +// ---- Storage tests --------------------------------------------------------- + +func TestStorage_ErrKeyNotFound(t *testing.T) { + s := conversation.NewMemoryStorage() + _, err := s.Get(context.Background(), "missing") + require.ErrorIs(t, err, conversation.ErrKeyNotFound) +} + +func TestStorage_SetAndGet(t *testing.T) { + ctx := context.Background() + s := conversation.NewMemoryStorage() + require.NoError(t, s.Set(ctx, "k", "state_a")) + v, err := s.Get(ctx, "k") + require.NoError(t, err) + require.Equal(t, conversation.State("state_a"), v) +} + +func TestStorage_Delete(t *testing.T) { + ctx := context.Background() + s := conversation.NewMemoryStorage() + require.NoError(t, s.Set(ctx, "k", "state_a")) + require.NoError(t, s.Delete(ctx, "k")) + _, err := s.Get(ctx, "k") + require.ErrorIs(t, err, conversation.ErrKeyNotFound) +} + +func TestStorage_DeleteNonExistentIsNoop(t *testing.T) { + require.NoError(t, conversation.NewMemoryStorage().Delete(context.Background(), "gone")) +} + +// ---- Key strategy tests ---------------------------------------------------- + +func TestKeyByUser_Variants(t *testing.T) { + t.Run("message", func(t *testing.T) { + u := msgUpd(42, 100, "hi") + require.Equal(t, "u:42", conversation.KeyByUser(&u)) + }) + t.Run("edited_message", func(t *testing.T) { + u := api.Update{EditedMessage: &api.Message{From: &api.User{ID: 7}, Chat: api.Chat{ID: 1}}} + require.Equal(t, "u:7", conversation.KeyByUser(&u)) + }) + t.Run("callback_query", func(t *testing.T) { + u := api.Update{CallbackQuery: &api.CallbackQuery{From: api.User{ID: 99}}} + require.Equal(t, "u:99", conversation.KeyByUser(&u)) + }) + t.Run("inline_query", func(t *testing.T) { + u := api.Update{InlineQuery: &api.InlineQuery{From: api.User{ID: 5}}} + require.Equal(t, "u:5", conversation.KeyByUser(&u)) + }) + t.Run("empty", func(t *testing.T) { + require.Equal(t, "", conversation.KeyByUser(&api.Update{})) + }) +} + +func TestKeyByChat_Variants(t *testing.T) { + t.Run("message", func(t *testing.T) { + u := msgUpd(1, 200, "") + require.Equal(t, "c:200", conversation.KeyByChat(&u)) + }) + t.Run("inline_has_no_chat", func(t *testing.T) { + u := api.Update{InlineQuery: &api.InlineQuery{From: api.User{ID: 5}}} + require.Equal(t, "", conversation.KeyByChat(&u)) + }) +} + +func TestKeyByUserAndChat(t *testing.T) { + u := msgUpd(42, 100, "") + require.Equal(t, "uc:100:42", conversation.KeyByUserAndChat(&u)) +} + +// ---- Handler / state machine tests ----------------------------------------- + +func buildConv() *conversation.Conversation { + return &conversation.Conversation{ + EntryPoints: []conversation.Step{{ + Filter: hasPrefix("/start"), + Handler: func(c *dispatch.Context, u *api.Update) error { + return conversation.Next("await_name") + }, + }}, + States: map[conversation.State][]conversation.Step{ + "await_name": {{ + Filter: anyMsg, + Handler: func(c *dispatch.Context, u *api.Update) error { return conversation.Next("await_age") }, + }}, + "await_age": {{ + Filter: anyMsg, + Handler: func(c *dispatch.Context, u *api.Update) error { return conversation.End() }, + }}, + }, + Exits: []conversation.Step{{ + Filter: hasPrefix("/cancel"), + Handler: func(c *dispatch.Context, u *api.Update) error { return conversation.End() }, + }}, + } +} + +func TestConversation_FullFlow(t *testing.T) { + conv := buildConv() + + var downstream int + noop := dispatch.Handler[*api.Update](func(_ *dispatch.Context, _ *api.Update) error { + downstream++ + return nil + }) + mw := conv.Dispatch(noop) + + key := "uc:1:42" + + // 1. /start → enters, state = await_name + u1 := msgUpd(42, 1, "/start") + require.NoError(t, mw(makeCtx(&u1), &u1)) + v, err := conv.Storage.Get(context.Background(), key) + require.NoError(t, err) + require.Equal(t, conversation.State("await_name"), v) + require.Equal(t, 0, downstream, "entry claimed update") + + // 2. name → state = await_age + u2 := msgUpd(42, 1, "Alice") + require.NoError(t, mw(makeCtx(&u2), &u2)) + v, err = conv.Storage.Get(context.Background(), key) + require.NoError(t, err) + require.Equal(t, conversation.State("await_age"), v) + + // 3. age → End, key deleted + u3 := msgUpd(42, 1, "30") + require.NoError(t, mw(makeCtx(&u3), &u3)) + _, err = conv.Storage.Get(context.Background(), key) + require.ErrorIs(t, err, conversation.ErrKeyNotFound) +} + +func TestConversation_ExitsCancelMidFlow(t *testing.T) { + conv := buildConv() + noop := dispatch.Handler[*api.Update](func(_ *dispatch.Context, _ *api.Update) error { return nil }) + mw := conv.Dispatch(noop) + + // Start conversation. + u1 := msgUpd(42, 1, "/start") + require.NoError(t, mw(makeCtx(&u1), &u1)) + _, err := conv.Storage.Get(context.Background(), "uc:1:42") + require.NoError(t, err) + + // Cancel mid-flow. + u2 := msgUpd(42, 1, "/cancel") + require.NoError(t, mw(makeCtx(&u2), &u2)) + _, err = conv.Storage.Get(context.Background(), "uc:1:42") + require.ErrorIs(t, err, conversation.ErrKeyNotFound, "exit should clear state") +} + +func TestConversation_FallbackFiresWhenNoStateStepMatches(t *testing.T) { + fallbackHit := false + conv := &conversation.Conversation{ + EntryPoints: []conversation.Step{{ + Filter: hasPrefix("/start"), + Handler: func(c *dispatch.Context, u *api.Update) error { return conversation.Next("waiting") }, + }}, + States: map[conversation.State][]conversation.Step{ + // No steps for "waiting" that match a callback query. + "waiting": {}, + }, + Fallbacks: []conversation.Step{{ + Filter: anyMsg, + Handler: func(c *dispatch.Context, u *api.Update) error { + fallbackHit = true + return nil + }, + }}, + } + + noop := dispatch.Handler[*api.Update](func(_ *dispatch.Context, _ *api.Update) error { return nil }) + mw := conv.Dispatch(noop) + + u1 := msgUpd(42, 1, "/start") + require.NoError(t, mw(makeCtx(&u1), &u1)) + + u2 := msgUpd(42, 1, "unexpected text") + require.NoError(t, mw(makeCtx(&u2), &u2)) + require.True(t, fallbackHit, "fallback should have fired") +} + +func TestConversation_NoActiveConv_PassesToDownstream(t *testing.T) { + conv := buildConv() + downstreamHit := false + downstream := dispatch.Handler[*api.Update](func(_ *dispatch.Context, _ *api.Update) error { + downstreamHit = true + return nil + }) + mw := conv.Dispatch(downstream) + + // Random message that doesn't match /start + u := msgUpd(42, 1, "hello") + require.NoError(t, mw(makeCtx(&u), &u)) + require.True(t, downstreamHit, "unmatched update should reach downstream") +} + +func TestConversation_EmptyKey_PassesThrough(t *testing.T) { + // InlineQuery has no chatID → KeyByUserAndChat returns "" → pass through. + conv := buildConv() + downstreamHit := false + downstream := dispatch.Handler[*api.Update](func(_ *dispatch.Context, _ *api.Update) error { + downstreamHit = true + return nil + }) + mw := conv.Dispatch(downstream) + + u := api.Update{InlineQuery: &api.InlineQuery{From: api.User{ID: 5}}} + require.NoError(t, mw(makeCtx(&u), &u)) + require.True(t, downstreamHit) +} + +func TestConversation_AllowReEntry(t *testing.T) { + conv := buildConv() + conv.AllowReEntry = true + + noop := dispatch.Handler[*api.Update](func(_ *dispatch.Context, _ *api.Update) error { return nil }) + mw := conv.Dispatch(noop) + + // Start. + u1 := msgUpd(42, 1, "/start") + require.NoError(t, mw(makeCtx(&u1), &u1)) + v, _ := conv.Storage.Get(context.Background(), "uc:1:42") + require.Equal(t, conversation.State("await_name"), v) + + // Advance once. + u2 := msgUpd(42, 1, "Alice") + require.NoError(t, mw(makeCtx(&u2), &u2)) + v, _ = conv.Storage.Get(context.Background(), "uc:1:42") + require.Equal(t, conversation.State("await_age"), v) + + // Re-enter with /start — should restart to await_name even though mid-flow. + u3 := msgUpd(42, 1, "/start") + require.NoError(t, mw(makeCtx(&u3), &u3)) + v, _ = conv.Storage.Get(context.Background(), "uc:1:42") + require.Equal(t, conversation.State("await_name"), v, "AllowReEntry should restart") +} + +func TestConversation_NoReEntry_EntryIgnoredWhenActive(t *testing.T) { + conv := buildConv() + conv.AllowReEntry = false + + noop := dispatch.Handler[*api.Update](func(_ *dispatch.Context, _ *api.Update) error { return nil }) + mw := conv.Dispatch(noop) + + // Start. + u1 := msgUpd(42, 1, "/start") + require.NoError(t, mw(makeCtx(&u1), &u1)) + + // Advance to await_age. + u2 := msgUpd(42, 1, "Alice") + require.NoError(t, mw(makeCtx(&u2), &u2)) + v, _ := conv.Storage.Get(context.Background(), "uc:1:42") + require.Equal(t, conversation.State("await_age"), v) + + // /start again — should NOT restart; state should stay await_age since + // /start matches the state step filter (anyMsg) and advances. + // Actually /start is handled by "await_age" anyMsg step → End(). + u3 := msgUpd(42, 1, "/start") + require.NoError(t, mw(makeCtx(&u3), &u3)) + // State ended (End() called by await_age step). + _, err := conv.Storage.Get(context.Background(), "uc:1:42") + require.ErrorIs(t, err, conversation.ErrKeyNotFound, "state step should have consumed /start when AllowReEntry=false") +} + +func TestConversation_StayInState_NilReturn(t *testing.T) { + // Handler returning nil keeps state unchanged. + stored := false + conv := &conversation.Conversation{ + EntryPoints: []conversation.Step{{ + Filter: hasPrefix("/start"), + Handler: func(c *dispatch.Context, u *api.Update) error { + return conversation.Next("waiting") + }, + }}, + States: map[conversation.State][]conversation.Step{ + "waiting": {{ + Filter: anyMsg, + Handler: func(c *dispatch.Context, u *api.Update) error { + stored = true + return nil // stay in current state + }, + }}, + }, + } + + noop := dispatch.Handler[*api.Update](func(_ *dispatch.Context, _ *api.Update) error { return nil }) + mw := conv.Dispatch(noop) + + u1 := msgUpd(42, 1, "/start") + require.NoError(t, mw(makeCtx(&u1), &u1)) + + u2 := msgUpd(42, 1, "something") + require.NoError(t, mw(makeCtx(&u2), &u2)) + require.True(t, stored) + v, _ := conv.Storage.Get(context.Background(), "uc:1:42") + require.Equal(t, conversation.State("waiting"), v, "nil return should leave state unchanged") +} + +func TestConversation_ActiveNoMatch_Swallows(t *testing.T) { + // Active conversation with no matching state step and no fallback: + // update is swallowed (not passed downstream). + conv := &conversation.Conversation{ + EntryPoints: []conversation.Step{{ + Filter: hasPrefix("/start"), + Handler: func(c *dispatch.Context, u *api.Update) error { return conversation.Next("waiting") }, + }}, + States: map[conversation.State][]conversation.Step{ + "waiting": {{ + // Only matches /done specifically. + Filter: hasPrefix("/done"), + Handler: func(c *dispatch.Context, u *api.Update) error { return conversation.End() }, + }}, + }, + } + + downstreamHit := false + downstream := dispatch.Handler[*api.Update](func(_ *dispatch.Context, _ *api.Update) error { + downstreamHit = true + return nil + }) + mw := conv.Dispatch(downstream) + + u1 := msgUpd(42, 1, "/start") + require.NoError(t, mw(makeCtx(&u1), &u1)) + + // Random text doesn't match /done and there's no fallback → swallowed. + u2 := msgUpd(42, 1, "random") + require.NoError(t, mw(makeCtx(&u2), &u2)) + require.False(t, downstreamHit, "active conv with no matching step should swallow") +} + +// ---- Via Router.Run -------------------------------------------------------- + +func TestConversation_ViaRouter(t *testing.T) { + var steps atomic.Int32 + conv := &conversation.Conversation{ + EntryPoints: []conversation.Step{{ + Filter: hasPrefix("/start"), + Handler: func(c *dispatch.Context, u *api.Update) error { + steps.Add(1) + return conversation.Next("await_name") + }, + }}, + States: map[conversation.State][]conversation.Step{ + "await_name": {{ + Filter: anyMsg, + Handler: func(c *dispatch.Context, u *api.Update) error { + steps.Add(1) + return conversation.Next("await_age") + }, + }}, + "await_age": {{ + Filter: anyMsg, + Handler: func(c *dispatch.Context, u *api.Update) error { + steps.Add(1) + return conversation.End() + }, + }}, + }, + } + + router := dispatch.New(client.New("t"), dispatch.WithMaxConcurrency(0)) // serial + router.Use(conv.Dispatch) + + ups := []api.Update{ + msgUpd(42, 1, "/start"), + msgUpd(42, 1, "Alice"), + msgUpd(42, 1, "30"), + } + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + errCh := make(chan error, 1) + go func() { errCh <- router.Run(ctx, newFake(ups...)) }() + + // Wait for updater channel to drain (Run returns when closed). + err := <-errCh + if err != nil && err != context.Canceled { + t.Fatalf("Run error: %v", err) + } + + require.Equal(t, int32(3), steps.Load(), "all three steps should have fired") +} + +// ---- Concurrent storage safety --------------------------------------------- + +func TestConversation_ConcurrentStorageAccess(t *testing.T) { + // 15 goroutines each running a full /start → name → age flow against the + // same shared storage but DIFFERENT keys (one per goroutine). Validates + // no data races. + const numUsers = 15 + + conv := buildConv() + noop := dispatch.Handler[*api.Update](func(_ *dispatch.Context, _ *api.Update) error { return nil }) + mw := conv.Dispatch(noop) + + var wg sync.WaitGroup + wg.Add(numUsers) + for i := 0; i < numUsers; i++ { + go func(uid int64) { + defer wg.Done() + u1 := msgUpd(uid, uid, "/start") + _ = mw(makeCtx(&u1), &u1) + u2 := msgUpd(uid, uid, "Alice") + _ = mw(makeCtx(&u2), &u2) + u3 := msgUpd(uid, uid, "30") + _ = mw(makeCtx(&u3), &u3) + }(int64(i + 1)) + } + wg.Wait() + // Race detector catches bugs; no assertion needed beyond clean finish. +} + +func TestConversation_ConcurrentSameKey(t *testing.T) { + // 12 goroutines hammer the same key concurrently. Storage must not panic + // or corrupt state. Race detector validates lock discipline. + const goroutines = 12 + s := conversation.NewMemoryStorage() + ctx := context.Background() + + var wg sync.WaitGroup + wg.Add(goroutines) + for i := 0; i < goroutines; i++ { + go func(i int) { + defer wg.Done() + _ = s.Set(ctx, "shared", conversation.State("step")) + _, _ = s.Get(ctx, "shared") + if i%4 == 0 { + _ = s.Delete(ctx, "shared") + } + }(i) + } + wg.Wait() +} diff --git a/dispatch/conversation/handler.go b/dispatch/conversation/handler.go new file mode 100644 index 0000000..831467d --- /dev/null +++ b/dispatch/conversation/handler.go @@ -0,0 +1,176 @@ +package conversation + +import ( + "context" + "errors" + + "github.com/lukaszraczylo/go-telegram/api" + "github.com/lukaszraczylo/go-telegram/dispatch" +) + +// stateTransition is a sentinel error type carrying a state transition +// or end signal. Conversation handlers return one of these (via Next or +// End helpers below) to drive the state machine. +type stateTransition struct { + next State + end bool +} + +func (e *stateTransition) Error() string { + if e.end { + return "conversation: end" + } + return "conversation: → " + string(e.next) +} + +// Next signals the conversation should advance to the given state. +// Conversation handlers return Next("state_name") to transition. +func Next(s State) error { + return &stateTransition{next: s} +} + +// End signals the conversation has finished and state should be cleared. +// Conversation handlers return End() to terminate. +func End() error { + return &stateTransition{end: true} +} + +// Handler defines a step in the conversation. Receives the dispatch context +// and the raw update. Returns: +// - nil to stay in the current state +// - Next("state") to transition to a different state +// - End() to end the conversation +// - any other non-nil error to surface to the dispatcher (state unchanged) +type Handler func(ctx *dispatch.Context, u *api.Update) error + +// Step pairs a filter with a handler for one conversation step. +type Step struct { + Filter dispatch.Filter[*api.Update] + Handler Handler +} + +// Conversation is a stateful handler with entry, per-state, exit and +// fallback steps. A conversation is keyed by KeyStrategy (default +// KeyByUserAndChat) and persisted by Storage (default in-memory). +type Conversation struct { + // EntryPoints starts a new conversation when a matching filter fires + // and no conversation is already active for the key. + EntryPoints []Step + + // States maps each state to the steps that handle it. + States map[State][]Step + + // Exits, if any match, end the active conversation early. Useful for + // /cancel-style commands. + Exits []Step + + // Fallbacks run when no state step matches the current update. + Fallbacks []Step + + // Storage persists conversation state. Defaults to NewMemoryStorage. + Storage Storage + + // KeyStrategy derives the persistence key. Defaults to KeyByUserAndChat. + KeyStrategy KeyStrategy + + // AllowReEntry, when true, lets entry-point steps fire even while a + // conversation is already active for the key (effectively restarting it). + AllowReEntry bool +} + +// Dispatch is a global middleware-shaped Handler that consumes updates +// and routes them through the conversation graph. Register via +// router.Use(conv.Dispatch). +// +// If the conversation claims an update, downstream handlers are skipped. +// If the conversation does not claim it, downstream handlers run as normal. +func (c *Conversation) Dispatch(next dispatch.Handler[*api.Update]) dispatch.Handler[*api.Update] { + if c.Storage == nil { + c.Storage = NewMemoryStorage() + } + if c.KeyStrategy == nil { + c.KeyStrategy = KeyByUserAndChat + } + return func(dctx *dispatch.Context, u *api.Update) error { + key := c.KeyStrategy(u) + if key == "" { + return next(dctx, u) + } + + ctx := dctx.Ctx + current, err := c.Storage.Get(ctx, key) + if err != nil && !errors.Is(err, ErrKeyNotFound) { + return err + } + active := !errors.Is(err, ErrKeyNotFound) + + // Try exits first (always allowed if conversation is active). + if active { + for _, step := range c.Exits { + if step.Filter(u) { + if err := c.runStep(ctx, dctx, u, key, step.Handler); err != nil { + return err + } + return nil + } + } + } + + // Try entry points (only if no active conversation, or AllowReEntry). + if !active || c.AllowReEntry { + for _, step := range c.EntryPoints { + if step.Filter(u) { + if err := c.runStep(ctx, dctx, u, key, step.Handler); err != nil { + return err + } + return nil + } + } + } + + if !active { + return next(dctx, u) + } + + // Active conversation: try state steps. + for _, step := range c.States[current] { + if step.Filter(u) { + if err := c.runStep(ctx, dctx, u, key, step.Handler); err != nil { + return err + } + return nil + } + } + + // Fallbacks if no state step matched. + for _, step := range c.Fallbacks { + if step.Filter(u) { + if err := c.runStep(ctx, dctx, u, key, step.Handler); err != nil { + return err + } + return nil + } + } + + // Active conversation but no step matched and no fallback: swallow the + // update (do NOT pass to downstream handlers, since the user is + // mid-conversation and an unrelated handler would surprise them). + return nil + } +} + +// runStep invokes the handler and applies its return-value state transition. +func (c *Conversation) runStep(ctx context.Context, dctx *dispatch.Context, u *api.Update, key string, h Handler) error { + err := h(dctx, u) + if err == nil { + return nil + } + var trans *stateTransition + if errors.As(err, &trans) { + if trans.end { + return c.Storage.Delete(ctx, key) + } + return c.Storage.Set(ctx, key, trans.next) + } + return err +} diff --git a/dispatch/conversation/in_memory.go b/dispatch/conversation/in_memory.go new file mode 100644 index 0000000..eaf1125 --- /dev/null +++ b/dispatch/conversation/in_memory.go @@ -0,0 +1,43 @@ +package conversation + +import ( + "context" + "sync" +) + +// MemoryStorage is the default in-process Storage. It is safe for +// concurrent use. Conversation state is lost on process restart; use +// a custom Storage backed by a database for persistent flows. +type MemoryStorage struct { + mu sync.RWMutex + state map[string]State +} + +// NewMemoryStorage constructs an empty in-memory storage. +func NewMemoryStorage() *MemoryStorage { + return &MemoryStorage{state: map[string]State{}} +} + +func (s *MemoryStorage) Get(_ context.Context, key string) (State, error) { + s.mu.RLock() + defer s.mu.RUnlock() + v, ok := s.state[key] + if !ok { + return "", ErrKeyNotFound + } + return v, nil +} + +func (s *MemoryStorage) Set(_ context.Context, key string, state State) error { + s.mu.Lock() + defer s.mu.Unlock() + s.state[key] = state + return nil +} + +func (s *MemoryStorage) Delete(_ context.Context, key string) error { + s.mu.Lock() + defer s.mu.Unlock() + delete(s.state, key) + return nil +} diff --git a/dispatch/conversation/in_memory_test.go b/dispatch/conversation/in_memory_test.go new file mode 100644 index 0000000..e04a151 --- /dev/null +++ b/dispatch/conversation/in_memory_test.go @@ -0,0 +1,87 @@ +package conversation + +import ( + "context" + "sync" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestMemoryStorage_GetSetDelete(t *testing.T) { + ctx := context.Background() + s := NewMemoryStorage() + + // Get on empty key returns ErrKeyNotFound. + _, err := s.Get(ctx, "k1") + require.ErrorIs(t, err, ErrKeyNotFound) + + // Set then Get returns the stored state. + require.NoError(t, s.Set(ctx, "k1", "step_a")) + v, err := s.Get(ctx, "k1") + require.NoError(t, err) + require.Equal(t, State("step_a"), v) + + // Overwrite works. + require.NoError(t, s.Set(ctx, "k1", "step_b")) + v, err = s.Get(ctx, "k1") + require.NoError(t, err) + require.Equal(t, State("step_b"), v) + + // Delete removes the key. + require.NoError(t, s.Delete(ctx, "k1")) + _, err = s.Get(ctx, "k1") + require.ErrorIs(t, err, ErrKeyNotFound) + + // Delete of non-existent key is a no-op (no error). + require.NoError(t, s.Delete(ctx, "nonexistent")) +} + +func TestMemoryStorage_MultipleKeys(t *testing.T) { + ctx := context.Background() + s := NewMemoryStorage() + + require.NoError(t, s.Set(ctx, "a", "stateA")) + require.NoError(t, s.Set(ctx, "b", "stateB")) + + va, err := s.Get(ctx, "a") + require.NoError(t, err) + require.Equal(t, State("stateA"), va) + + vb, err := s.Get(ctx, "b") + require.NoError(t, err) + require.Equal(t, State("stateB"), vb) + + // Delete one key; the other remains. + require.NoError(t, s.Delete(ctx, "a")) + _, err = s.Get(ctx, "a") + require.ErrorIs(t, err, ErrKeyNotFound) + + vb, err = s.Get(ctx, "b") + require.NoError(t, err) + require.Equal(t, State("stateB"), vb) +} + +func TestMemoryStorage_Concurrent(t *testing.T) { + // 20 goroutines hammering the same key concurrently — no data race. + ctx := context.Background() + s := NewMemoryStorage() + + const goroutines = 20 + var wg sync.WaitGroup + wg.Add(goroutines) + + for i := 0; i < goroutines; i++ { + go func(i int) { + defer wg.Done() + key := "shared" + _ = s.Set(ctx, key, State("step")) + _, _ = s.Get(ctx, key) + if i%3 == 0 { + _ = s.Delete(ctx, key) + } + }(i) + } + wg.Wait() + // No assertion needed — race detector catches the bug if present. +} diff --git a/dispatch/conversation/key.go b/dispatch/conversation/key.go new file mode 100644 index 0000000..8c20e0e --- /dev/null +++ b/dispatch/conversation/key.go @@ -0,0 +1,79 @@ +package conversation + +import ( + "fmt" + + "github.com/lukaszraczylo/go-telegram/api" +) + +// KeyStrategy derives a persistence key from an update. Strategies +// determine how conversation scope works — per-user, per-chat, or +// per-user-and-chat. Implementations must return a stable string for +// the same logical scope across updates. +// +// Returns the empty string if the update doesn't have enough context +// to derive a key (in which case the conversation handler skips it). +type KeyStrategy func(u *api.Update) string + +// KeyByUser derives a key from the sending user's ID. Useful for DM +// conversations and any flow that should follow the user across chats. +var KeyByUser KeyStrategy = func(u *api.Update) string { + if uid := userID(u); uid != 0 { + return fmt.Sprintf("u:%d", uid) + } + return "" +} + +// KeyByChat derives a key from the chat ID. Useful for group flows where +// any user in the chat can drive the conversation. +var KeyByChat KeyStrategy = func(u *api.Update) string { + if cid := chatID(u); cid != 0 { + return fmt.Sprintf("c:%d", cid) + } + return "" +} + +// KeyByUserAndChat derives a key from both user and chat IDs. The most +// common strategy: each user has their own conversation per chat. +var KeyByUserAndChat KeyStrategy = func(u *api.Update) string { + uid := userID(u) + cid := chatID(u) + if uid == 0 || cid == 0 { + return "" + } + return fmt.Sprintf("uc:%d:%d", cid, uid) +} + +// userID extracts the sending user's ID from any update payload. +func userID(u *api.Update) int64 { + switch { + case u.Message != nil && u.Message.From != nil: + return u.Message.From.ID + case u.EditedMessage != nil && u.EditedMessage.From != nil: + return u.EditedMessage.From.ID + case u.CallbackQuery != nil: + return u.CallbackQuery.From.ID + case u.InlineQuery != nil: + return u.InlineQuery.From.ID + } + return 0 +} + +// chatID extracts the relevant chat ID. +func chatID(u *api.Update) int64 { + switch { + case u.Message != nil: + return u.Message.Chat.ID + case u.EditedMessage != nil: + return u.EditedMessage.Chat.ID + case u.ChannelPost != nil: + return u.ChannelPost.Chat.ID + case u.EditedChannelPost != nil: + return u.EditedChannelPost.Chat.ID + case u.CallbackQuery != nil && u.CallbackQuery.Message != nil: + if msg, ok := u.CallbackQuery.Message.(*api.Message); ok { + return msg.Chat.ID + } + } + return 0 +} diff --git a/dispatch/conversation/key_test.go b/dispatch/conversation/key_test.go new file mode 100644 index 0000000..2e0ea00 --- /dev/null +++ b/dispatch/conversation/key_test.go @@ -0,0 +1,115 @@ +package conversation + +import ( + "testing" + + "github.com/lukaszraczylo/go-telegram/api" + "github.com/stretchr/testify/require" +) + +// helpers to build api.Update variants. + +func msgUpdate(userID, chatID int64) *api.Update { + return &api.Update{ + Message: &api.Message{ + From: &api.User{ID: userID}, + Chat: api.Chat{ID: chatID}, + }, + } +} + +func editedMsgUpdate(userID, chatID int64) *api.Update { + return &api.Update{ + EditedMessage: &api.Message{ + From: &api.User{ID: userID}, + Chat: api.Chat{ID: chatID}, + }, + } +} + +func callbackUpdate(userID, chatID int64) *api.Update { + return &api.Update{ + CallbackQuery: &api.CallbackQuery{ + From: api.User{ID: userID}, + Message: &api.Message{Chat: api.Chat{ID: chatID}}, + }, + } +} + +func inlineUpdate(userID int64) *api.Update { + return &api.Update{ + InlineQuery: &api.InlineQuery{ + From: api.User{ID: userID}, + }, + } +} + +func emptyUpdate() *api.Update { return &api.Update{} } + +func TestKeyByUser(t *testing.T) { + t.Run("message update", func(t *testing.T) { + require.Equal(t, "u:42", KeyByUser(msgUpdate(42, 100))) + }) + t.Run("edited message", func(t *testing.T) { + require.Equal(t, "u:7", KeyByUser(editedMsgUpdate(7, 100))) + }) + t.Run("callback query", func(t *testing.T) { + require.Equal(t, "u:99", KeyByUser(callbackUpdate(99, 100))) + }) + t.Run("inline query", func(t *testing.T) { + require.Equal(t, "u:5", KeyByUser(inlineUpdate(5))) + }) + t.Run("empty update returns empty string", func(t *testing.T) { + require.Equal(t, "", KeyByUser(emptyUpdate())) + }) +} + +func TestKeyByChat(t *testing.T) { + t.Run("message update", func(t *testing.T) { + require.Equal(t, "c:100", KeyByChat(msgUpdate(42, 100))) + }) + t.Run("edited message", func(t *testing.T) { + require.Equal(t, "c:200", KeyByChat(editedMsgUpdate(7, 200))) + }) + t.Run("callback with accessible message", func(t *testing.T) { + require.Equal(t, "c:300", KeyByChat(callbackUpdate(99, 300))) + }) + t.Run("inline query has no chat → empty", func(t *testing.T) { + require.Equal(t, "", KeyByChat(inlineUpdate(5))) + }) + t.Run("empty update returns empty string", func(t *testing.T) { + require.Equal(t, "", KeyByChat(emptyUpdate())) + }) +} + +func TestKeyByUserAndChat(t *testing.T) { + t.Run("message update", func(t *testing.T) { + require.Equal(t, "uc:100:42", KeyByUserAndChat(msgUpdate(42, 100))) + }) + t.Run("edited message", func(t *testing.T) { + require.Equal(t, "uc:200:7", KeyByUserAndChat(editedMsgUpdate(7, 200))) + }) + t.Run("callback query", func(t *testing.T) { + require.Equal(t, "uc:300:99", KeyByUserAndChat(callbackUpdate(99, 300))) + }) + t.Run("inline query has no chat → empty", func(t *testing.T) { + require.Equal(t, "", KeyByUserAndChat(inlineUpdate(5))) + }) + t.Run("empty update returns empty string", func(t *testing.T) { + require.Equal(t, "", KeyByUserAndChat(emptyUpdate())) + }) +} + +func TestKeyByUserAndChat_CallbackInaccessibleMessage(t *testing.T) { + // CallbackQuery.Message is InaccessibleMessage (not *Message) — chatID returns 0. + u := &api.Update{ + CallbackQuery: &api.CallbackQuery{ + From: api.User{ID: 10}, + Message: &api.InaccessibleMessage{}, // implements MaybeInaccessibleMessage, not *api.Message + }, + } + // userID picks up From.ID=10 but chatID fails type assertion → 0 + require.Equal(t, "", KeyByUserAndChat(u), "no key when message inaccessible") + // KeyByUser still works since From is set. + require.Equal(t, "u:10", KeyByUser(u)) +} diff --git a/dispatch/conversation/state.go b/dispatch/conversation/state.go new file mode 100644 index 0000000..5b78396 --- /dev/null +++ b/dispatch/conversation/state.go @@ -0,0 +1,9 @@ +// Package conversation implements a stateful conversation handler for the +// go-telegram dispatch router. It provides a state-machine abstraction over +// multi-step Telegram bot interactions, with pluggable storage and flexible +// key strategies. +package conversation + +// State is a label identifying a node in the conversation graph. +// The empty string is the implicit "no active conversation" state. +type State string diff --git a/dispatch/conversation/storage.go b/dispatch/conversation/storage.go new file mode 100644 index 0000000..02fba5d --- /dev/null +++ b/dispatch/conversation/storage.go @@ -0,0 +1,20 @@ +package conversation + +import ( + "context" + "errors" +) + +// ErrKeyNotFound is returned by Storage.Get when no conversation is active +// for the given key. +var ErrKeyNotFound = errors.New("conversation: key not found") + +// Storage persists per-user (or per-chat, per-message — depending on the +// KeyStrategy in use) conversation state across update deliveries. +// +// Implementations must be safe for concurrent use. +type Storage interface { + Get(ctx context.Context, key string) (State, error) + Set(ctx context.Context, key string, state State) error + Delete(ctx context.Context, key string) error +} diff --git a/dispatch/filter.go b/dispatch/filter.go new file mode 100644 index 0000000..8d48de9 --- /dev/null +++ b/dispatch/filter.go @@ -0,0 +1,70 @@ +package dispatch + +// Filter is a predicate over a typed payload (e.g. *api.Message). Filters +// compose via And/Or/Not for multi-condition matching. +// +// Example: +// +// f := message.HasPhoto().And(message.InChat(-100123456789)) +type Filter[T any] func(payload T) bool + +// And returns a Filter that matches iff f and every one of others matches. +func (f Filter[T]) And(others ...Filter[T]) Filter[T] { + return func(payload T) bool { + if !f(payload) { + return false + } + for _, o := range others { + if !o(payload) { + return false + } + } + return true + } +} + +// Or returns a Filter that matches iff f matches OR any of others matches. +func (f Filter[T]) Or(others ...Filter[T]) Filter[T] { + return func(payload T) bool { + if f(payload) { + return true + } + for _, o := range others { + if o(payload) { + return true + } + } + return false + } +} + +// Not returns a Filter that inverts f. +func (f Filter[T]) Not() Filter[T] { + return func(payload T) bool { return !f(payload) } +} + +// All combines filters with AND. Returns a Filter that matches when all match. +// Returns a filter that always matches when filters is empty. +func All[T any](filters ...Filter[T]) Filter[T] { + return func(payload T) bool { + for _, f := range filters { + if !f(payload) { + return false + } + } + return true + } +} + +// Any combines filters with OR. Returns a Filter that matches when at least +// one matches. Returns a filter that never matches when filters is empty. +func Any[T any](filters ...Filter[T]) Filter[T] { + return func(payload T) bool { + for _, f := range filters { + if f(payload) { + return true + } + } + return false + } +} diff --git a/dispatch/filter_test.go b/dispatch/filter_test.go new file mode 100644 index 0000000..48bd26a --- /dev/null +++ b/dispatch/filter_test.go @@ -0,0 +1,87 @@ +package dispatch + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +func alwaysTrue[T any]() Filter[T] { return func(_ T) bool { return true } } +func alwaysFalse[T any]() Filter[T] { return func(_ T) bool { return false } } + +func TestFilter_And(t *testing.T) { + t.Run("all true", func(t *testing.T) { + f := alwaysTrue[int]().And(alwaysTrue[int](), alwaysTrue[int]()) + require.True(t, f(0)) + }) + t.Run("first false", func(t *testing.T) { + f := alwaysFalse[int]().And(alwaysTrue[int]()) + require.False(t, f(0)) + }) + t.Run("other false", func(t *testing.T) { + f := alwaysTrue[int]().And(alwaysFalse[int]()) + require.False(t, f(0)) + }) + t.Run("no others — acts as identity", func(t *testing.T) { + require.True(t, alwaysTrue[int]().And()(0)) + require.False(t, alwaysFalse[int]().And()(0)) + }) +} + +func TestFilter_Or(t *testing.T) { + t.Run("first true", func(t *testing.T) { + f := alwaysTrue[int]().Or(alwaysFalse[int]()) + require.True(t, f(0)) + }) + t.Run("other true", func(t *testing.T) { + f := alwaysFalse[int]().Or(alwaysTrue[int]()) + require.True(t, f(0)) + }) + t.Run("all false", func(t *testing.T) { + f := alwaysFalse[int]().Or(alwaysFalse[int]()) + require.False(t, f(0)) + }) + t.Run("no others", func(t *testing.T) { + require.True(t, alwaysTrue[int]().Or()(0)) + require.False(t, alwaysFalse[int]().Or()(0)) + }) +} + +func TestFilter_Not(t *testing.T) { + require.False(t, alwaysTrue[int]().Not()(0)) + require.True(t, alwaysFalse[int]().Not()(0)) +} + +func TestAll(t *testing.T) { + t.Run("all true", func(t *testing.T) { + require.True(t, All(alwaysTrue[int](), alwaysTrue[int]())(0)) + }) + t.Run("one false", func(t *testing.T) { + require.False(t, All(alwaysTrue[int](), alwaysFalse[int]())(0)) + }) + t.Run("empty — always true", func(t *testing.T) { + require.True(t, All[int]()(0)) + }) +} + +func TestAny(t *testing.T) { + t.Run("one true", func(t *testing.T) { + require.True(t, Any(alwaysFalse[int](), alwaysTrue[int]())(0)) + }) + t.Run("all false", func(t *testing.T) { + require.False(t, Any(alwaysFalse[int](), alwaysFalse[int]())(0)) + }) + t.Run("empty — always false", func(t *testing.T) { + require.False(t, Any[int]()(0)) + }) +} + +func TestFilter_Composition(t *testing.T) { + // (true AND false) OR true == true + f := alwaysTrue[int]().And(alwaysFalse[int]()).Or(alwaysTrue[int]()) + require.True(t, f(0)) + + // NOT (true OR false) == false + g := alwaysTrue[int]().Or(alwaysFalse[int]()).Not() + require.False(t, g(0)) +} diff --git a/dispatch/filters/callback/callback.go b/dispatch/filters/callback/callback.go new file mode 100644 index 0000000..ee1e1c5 --- /dev/null +++ b/dispatch/filters/callback/callback.go @@ -0,0 +1,43 @@ +// Package callback provides Filter helpers for *api.CallbackQuery payloads. +package callback + +import ( + "regexp" + "strings" + + "github.com/lukaszraczylo/go-telegram/api" + "github.com/lukaszraczylo/go-telegram/dispatch" +) + +// Data returns a Filter that matches callback queries whose Data matches +// pattern (regex). Panics at registration time on an invalid pattern. +func Data(pattern string) dispatch.Filter[*api.CallbackQuery] { + re := regexp.MustCompile(pattern) + return func(q *api.CallbackQuery) bool { + return q != nil && re.MatchString(q.Data) + } +} + +// DataEquals returns a Filter that matches callback queries whose Data equals +// s exactly. +func DataEquals(s string) dispatch.Filter[*api.CallbackQuery] { + return func(q *api.CallbackQuery) bool { + return q != nil && q.Data == s + } +} + +// DataPrefix returns a Filter that matches callback queries whose Data starts +// with prefix. +func DataPrefix(prefix string) dispatch.Filter[*api.CallbackQuery] { + return func(q *api.CallbackQuery) bool { + return q != nil && strings.HasPrefix(q.Data, prefix) + } +} + +// FromUser returns a Filter that matches callback queries whose From.ID equals +// userID. +func FromUser(userID int64) dispatch.Filter[*api.CallbackQuery] { + return func(q *api.CallbackQuery) bool { + return q != nil && q.From.ID == userID + } +} diff --git a/dispatch/filters/callback/callback_test.go b/dispatch/filters/callback/callback_test.go new file mode 100644 index 0000000..2f1f8af --- /dev/null +++ b/dispatch/filters/callback/callback_test.go @@ -0,0 +1,56 @@ +package callback_test + +import ( + "testing" + + "github.com/lukaszraczylo/go-telegram/api" + cbfilter "github.com/lukaszraczylo/go-telegram/dispatch/filters/callback" + "github.com/stretchr/testify/require" +) + +func cq(data string, userID int64) *api.CallbackQuery { + return &api.CallbackQuery{ + ID: "q", + From: api.User{ID: userID}, + Data: data, + } +} + +func TestData(t *testing.T) { + f := cbfilter.Data(`^like:\d+$`) + require.True(t, f(cq("like:42", 1))) + require.False(t, f(cq("dislike:42", 1))) + require.False(t, f(nil)) +} + +func TestData_PanicsOnBadPattern(t *testing.T) { + require.Panics(t, func() { cbfilter.Data(`[bad`) }) +} + +func TestDataEquals(t *testing.T) { + f := cbfilter.DataEquals("yes") + require.True(t, f(cq("yes", 1))) + require.False(t, f(cq("yes please", 1))) + require.False(t, f(nil)) +} + +func TestDataPrefix(t *testing.T) { + f := cbfilter.DataPrefix("vote:") + require.True(t, f(cq("vote:up", 1))) + require.False(t, f(cq("novote:up", 1))) + require.False(t, f(nil)) +} + +func TestFromUser(t *testing.T) { + f := cbfilter.FromUser(7) + require.True(t, f(cq("data", 7))) + require.False(t, f(cq("data", 8))) + require.False(t, f(nil)) +} + +func TestComposedCallbackFilters(t *testing.T) { + f := cbfilter.DataPrefix("vote:").And(cbfilter.FromUser(7)) + require.True(t, f(cq("vote:up", 7))) + require.False(t, f(cq("vote:up", 8))) + require.False(t, f(cq("other", 7))) +} diff --git a/dispatch/filters/chatjoinrequest/chatjoinrequest.go b/dispatch/filters/chatjoinrequest/chatjoinrequest.go new file mode 100644 index 0000000..fc5b408 --- /dev/null +++ b/dispatch/filters/chatjoinrequest/chatjoinrequest.go @@ -0,0 +1,23 @@ +// Package chatjoinrequest provides Filter helpers for *api.ChatJoinRequest payloads. +package chatjoinrequest + +import ( + "github.com/lukaszraczylo/go-telegram/api" + "github.com/lukaszraczylo/go-telegram/dispatch" +) + +// FromUser returns a Filter that matches join requests where the requesting +// user's ID equals uid. +func FromUser(uid int64) dispatch.Filter[*api.ChatJoinRequest] { + return func(r *api.ChatJoinRequest) bool { + return r != nil && r.From.ID == uid + } +} + +// InChat returns a Filter that matches join requests directed at the chat +// with the given chat ID. +func InChat(cid int64) dispatch.Filter[*api.ChatJoinRequest] { + return func(r *api.ChatJoinRequest) bool { + return r != nil && r.Chat.ID == cid + } +} diff --git a/dispatch/filters/chatjoinrequest/chatjoinrequest_test.go b/dispatch/filters/chatjoinrequest/chatjoinrequest_test.go new file mode 100644 index 0000000..07654f3 --- /dev/null +++ b/dispatch/filters/chatjoinrequest/chatjoinrequest_test.go @@ -0,0 +1,37 @@ +package chatjoinrequest_test + +import ( + "testing" + + "github.com/lukaszraczylo/go-telegram/api" + cjrfilter "github.com/lukaszraczylo/go-telegram/dispatch/filters/chatjoinrequest" + "github.com/stretchr/testify/require" +) + +func joinRequest(fromID, chatID int64) *api.ChatJoinRequest { + return &api.ChatJoinRequest{ + Chat: api.Chat{ID: chatID}, + From: api.User{ID: fromID}, + } +} + +func TestFromUser_Matches(t *testing.T) { + f := cjrfilter.FromUser(10) + require.True(t, f(joinRequest(10, 100))) + require.False(t, f(joinRequest(99, 100))) + require.False(t, f(nil)) +} + +func TestInChat_Matches(t *testing.T) { + f := cjrfilter.InChat(100) + require.True(t, f(joinRequest(10, 100))) + require.False(t, f(joinRequest(10, 200))) + require.False(t, f(nil)) +} + +func TestComposedFilters(t *testing.T) { + f := cjrfilter.FromUser(10).And(cjrfilter.InChat(100)) + require.True(t, f(joinRequest(10, 100))) + require.False(t, f(joinRequest(10, 200))) + require.False(t, f(joinRequest(99, 100))) +} diff --git a/dispatch/filters/chatmember/chatmember.go b/dispatch/filters/chatmember/chatmember.go new file mode 100644 index 0000000..9e8ef25 --- /dev/null +++ b/dispatch/filters/chatmember/chatmember.go @@ -0,0 +1,41 @@ +// Package chatmember provides Filter helpers for *api.ChatMemberUpdated payloads. +package chatmember + +import ( + "github.com/lukaszraczylo/go-telegram/api" + "github.com/lukaszraczylo/go-telegram/dispatch" +) + +// NewStatus returns a Filter that matches updates where the new chat member +// status equals s (e.g. "member", "administrator", "kicked", "left"). +func NewStatus(s string) dispatch.Filter[*api.ChatMemberUpdated] { + return func(u *api.ChatMemberUpdated) bool { + if u == nil { + return false + } + switch m := u.NewChatMember.(type) { + case *api.ChatMemberOwner: + return m.Status == s + case *api.ChatMemberAdministrator: + return m.Status == s + case *api.ChatMemberMember: + return m.Status == s + case *api.ChatMemberRestricted: + return m.Status == s + case *api.ChatMemberLeft: + return m.Status == s + case *api.ChatMemberBanned: + return m.Status == s + default: + return false + } + } +} + +// FromUser returns a Filter that matches updates where the acting user +// (From.ID) equals uid. +func FromUser(uid int64) dispatch.Filter[*api.ChatMemberUpdated] { + return func(u *api.ChatMemberUpdated) bool { + return u != nil && u.From.ID == uid + } +} diff --git a/dispatch/filters/chatmember/chatmember_test.go b/dispatch/filters/chatmember/chatmember_test.go new file mode 100644 index 0000000..969d138 --- /dev/null +++ b/dispatch/filters/chatmember/chatmember_test.go @@ -0,0 +1,95 @@ +package chatmember_test + +import ( + "testing" + + "github.com/lukaszraczylo/go-telegram/api" + cmfilter "github.com/lukaszraczylo/go-telegram/dispatch/filters/chatmember" + "github.com/stretchr/testify/require" +) + +func memberUpdate(status string, fromID int64) *api.ChatMemberUpdated { + var newMember api.ChatMember + switch status { + case "member": + newMember = &api.ChatMemberMember{Status: status} + case "administrator": + newMember = &api.ChatMemberAdministrator{Status: status} + case "kicked": + newMember = &api.ChatMemberBanned{Status: status} + case "left": + newMember = &api.ChatMemberLeft{Status: status} + default: + newMember = &api.ChatMemberMember{Status: status} + } + return &api.ChatMemberUpdated{ + From: api.User{ID: fromID}, + NewChatMember: newMember, + } +} + +func TestNewStatus_Matches(t *testing.T) { + f := cmfilter.NewStatus("member") + require.True(t, f(memberUpdate("member", 1))) + require.False(t, f(memberUpdate("kicked", 1))) + require.False(t, f(nil)) +} + +func TestNewStatus_Administrator(t *testing.T) { + f := cmfilter.NewStatus("administrator") + require.True(t, f(memberUpdate("administrator", 1))) + require.False(t, f(memberUpdate("member", 1))) +} + +func TestNewStatus_Kicked(t *testing.T) { + f := cmfilter.NewStatus("kicked") + require.True(t, f(memberUpdate("kicked", 1))) + require.False(t, f(memberUpdate("left", 1))) +} + +func TestNewStatus_Left(t *testing.T) { + f := cmfilter.NewStatus("left") + require.True(t, f(memberUpdate("left", 1))) + require.False(t, f(memberUpdate("member", 1))) +} + +func TestFromUser_Matches(t *testing.T) { + f := cmfilter.FromUser(42) + require.True(t, f(memberUpdate("member", 42))) + require.False(t, f(memberUpdate("member", 99))) + require.False(t, f(nil)) +} + +func TestComposedFilters(t *testing.T) { + f := cmfilter.NewStatus("member").And(cmfilter.FromUser(7)) + require.True(t, f(memberUpdate("member", 7))) + require.False(t, f(memberUpdate("member", 8))) + require.False(t, f(memberUpdate("kicked", 7))) +} + +func TestNewStatus_Owner(t *testing.T) { + u := &api.ChatMemberUpdated{ + From: api.User{ID: 1}, + NewChatMember: &api.ChatMemberOwner{Status: "creator"}, + } + require.True(t, cmfilter.NewStatus("creator")(u)) + require.False(t, cmfilter.NewStatus("member")(u)) +} + +func TestNewStatus_Restricted(t *testing.T) { + u := &api.ChatMemberUpdated{ + From: api.User{ID: 1}, + NewChatMember: &api.ChatMemberRestricted{Status: "restricted"}, + } + require.True(t, cmfilter.NewStatus("restricted")(u)) + require.False(t, cmfilter.NewStatus("member")(u)) +} + +func TestNewStatus_UnknownType(t *testing.T) { + // nil NewChatMember → default branch → false + u := &api.ChatMemberUpdated{ + From: api.User{ID: 1}, + NewChatMember: nil, + } + require.False(t, cmfilter.NewStatus("member")(u)) +} diff --git a/dispatch/filters/inline/inline.go b/dispatch/filters/inline/inline.go new file mode 100644 index 0000000..74806fd --- /dev/null +++ b/dispatch/filters/inline/inline.go @@ -0,0 +1,35 @@ +// Package inline provides Filter helpers for *api.InlineQuery payloads. +package inline + +import ( + "regexp" + "strings" + + "github.com/lukaszraczylo/go-telegram/api" + "github.com/lukaszraczylo/go-telegram/dispatch" +) + +// Query returns a Filter that matches inline queries whose Query field matches +// pattern (regex). Panics at registration time on an invalid pattern. +func Query(pattern string) dispatch.Filter[*api.InlineQuery] { + re := regexp.MustCompile(pattern) + return func(q *api.InlineQuery) bool { + return q != nil && re.MatchString(q.Query) + } +} + +// QueryEquals returns a Filter that matches inline queries whose Query equals +// s exactly. +func QueryEquals(s string) dispatch.Filter[*api.InlineQuery] { + return func(q *api.InlineQuery) bool { + return q != nil && q.Query == s + } +} + +// QueryPrefix returns a Filter that matches inline queries whose Query starts +// with prefix. +func QueryPrefix(prefix string) dispatch.Filter[*api.InlineQuery] { + return func(q *api.InlineQuery) bool { + return q != nil && strings.HasPrefix(q.Query, prefix) + } +} diff --git a/dispatch/filters/inline/inline_test.go b/dispatch/filters/inline/inline_test.go new file mode 100644 index 0000000..a1d0233 --- /dev/null +++ b/dispatch/filters/inline/inline_test.go @@ -0,0 +1,45 @@ +package inline_test + +import ( + "testing" + + "github.com/lukaszraczylo/go-telegram/api" + ilfilter "github.com/lukaszraczylo/go-telegram/dispatch/filters/inline" + "github.com/stretchr/testify/require" +) + +func iq(query string) *api.InlineQuery { + return &api.InlineQuery{ID: "i", From: api.User{ID: 1}, Query: query} +} + +func TestQuery(t *testing.T) { + f := ilfilter.Query(`^find`) + require.True(t, f(iq("find me"))) + require.False(t, f(iq("search me"))) + require.False(t, f(nil)) +} + +func TestQuery_PanicsOnBadPattern(t *testing.T) { + require.Panics(t, func() { ilfilter.Query(`[bad`) }) +} + +func TestQueryEquals(t *testing.T) { + f := ilfilter.QueryEquals("exact") + require.True(t, f(iq("exact"))) + require.False(t, f(iq("exact match"))) + require.False(t, f(nil)) +} + +func TestQueryPrefix(t *testing.T) { + f := ilfilter.QueryPrefix("@user") + require.True(t, f(iq("@username"))) + require.False(t, f(iq("no prefix"))) + require.False(t, f(nil)) +} + +func TestComposedInlineFilters(t *testing.T) { + f := ilfilter.QueryPrefix("find").Or(ilfilter.QueryEquals("help")) + require.True(t, f(iq("find me"))) + require.True(t, f(iq("help"))) + require.False(t, f(iq("other"))) +} diff --git a/dispatch/filters/message/message.go b/dispatch/filters/message/message.go new file mode 100644 index 0000000..7bcbe9f --- /dev/null +++ b/dispatch/filters/message/message.go @@ -0,0 +1,142 @@ +// Package message provides Filter helpers for *api.Message payloads. +package message + +import ( + "regexp" + "strings" + + "github.com/lukaszraczylo/go-telegram/api" + "github.com/lukaszraczylo/go-telegram/dispatch" +) + +// Text returns a Filter that matches messages whose Text matches pattern (regex). +// Panics at registration time on an invalid pattern. +func Text(pattern string) dispatch.Filter[*api.Message] { + re := regexp.MustCompile(pattern) + return func(m *api.Message) bool { + return m != nil && re.MatchString(m.Text) + } +} + +// TextEquals returns a Filter that matches messages whose Text equals s exactly. +func TextEquals(s string) dispatch.Filter[*api.Message] { + return func(m *api.Message) bool { + return m != nil && m.Text == s + } +} + +// TextPrefix returns a Filter that matches messages whose Text starts with prefix. +func TextPrefix(prefix string) dispatch.Filter[*api.Message] { + return func(m *api.Message) bool { + return m != nil && strings.HasPrefix(m.Text, prefix) + } +} + +// TextContains returns a Filter that matches messages whose Text contains sub. +func TextContains(sub string) dispatch.Filter[*api.Message] { + return func(m *api.Message) bool { + return m != nil && strings.Contains(m.Text, sub) + } +} + +// Command returns a Filter that matches messages whose first entity is a +// bot_command equal to "/" (with or without "@BotName" suffix). +func Command(name string) dispatch.Filter[*api.Message] { + want := "/" + strings.TrimPrefix(name, "/") + return func(m *api.Message) bool { + if m == nil || len(m.Entities) == 0 || m.Text == "" { + return false + } + first := m.Entities[0] + if first.Type != string(api.EntityBotCommand) || first.Offset != 0 { + return false + } + end := int(first.Length) + runes := []rune(m.Text) + if end > len(runes) { + return false + } + cmd := string(runes[:end]) + if i := strings.Index(cmd, "@"); i >= 0 { + cmd = cmd[:i] + } + return cmd == want + } +} + +// AnyCommand returns a Filter that matches any message starting with a +// bot_command entity at offset 0. +func AnyCommand() dispatch.Filter[*api.Message] { + return func(m *api.Message) bool { + if m == nil || len(m.Entities) == 0 { + return false + } + first := m.Entities[0] + return first.Type == string(api.EntityBotCommand) && first.Offset == 0 + } +} + +// IsReply returns a Filter that matches messages that have ReplyToMessage set. +func IsReply() dispatch.Filter[*api.Message] { + return func(m *api.Message) bool { + return m != nil && m.ReplyToMessage != nil + } +} + +// IsForward returns a Filter that matches messages that have ForwardOrigin set. +func IsForward() dispatch.Filter[*api.Message] { + return func(m *api.Message) bool { + return m != nil && m.ForwardOrigin != nil + } +} + +// HasPhoto returns a Filter that matches messages with a Photo attachment. +func HasPhoto() dispatch.Filter[*api.Message] { + return func(m *api.Message) bool { + return m != nil && len(m.Photo) > 0 + } +} + +// HasDocument returns a Filter that matches messages with a Document attachment. +func HasDocument() dispatch.Filter[*api.Message] { + return func(m *api.Message) bool { + return m != nil && m.Document != nil + } +} + +// HasEntity returns a Filter that matches messages whose Entities contain at +// least one entity of type t (e.g. string(api.EntityBotCommand)). +func HasEntity(t string) dispatch.Filter[*api.Message] { + return func(m *api.Message) bool { + if m == nil { + return false + } + for _, e := range m.Entities { + if e.Type == t { + return true + } + } + return false + } +} + +// ChatType returns a Filter that matches messages whose Chat.Type equals t. +func ChatType(t api.ChatType) dispatch.Filter[*api.Message] { + return func(m *api.Message) bool { + return m != nil && m.Chat.Type == string(t) + } +} + +// FromUser returns a Filter that matches messages whose From.ID equals userID. +func FromUser(userID int64) dispatch.Filter[*api.Message] { + return func(m *api.Message) bool { + return m != nil && m.From != nil && m.From.ID == userID + } +} + +// InChat returns a Filter that matches messages whose Chat.ID equals chatID. +func InChat(chatID int64) dispatch.Filter[*api.Message] { + return func(m *api.Message) bool { + return m != nil && m.Chat.ID == chatID + } +} diff --git a/dispatch/filters/message/message_test.go b/dispatch/filters/message/message_test.go new file mode 100644 index 0000000..13470e0 --- /dev/null +++ b/dispatch/filters/message/message_test.go @@ -0,0 +1,188 @@ +package message_test + +import ( + "testing" + + "github.com/lukaszraczylo/go-telegram/api" + msgfilter "github.com/lukaszraczylo/go-telegram/dispatch/filters/message" + "github.com/stretchr/testify/require" +) + +func msg(text string) *api.Message { + return &api.Message{ + MessageID: 1, + Chat: api.Chat{ID: 1, Type: string(api.ChatTypePrivate)}, + Text: text, + } +} + +func cmdMsg(cmd string) *api.Message { + text := cmd + return &api.Message{ + MessageID: 1, + Chat: api.Chat{ID: 1, Type: string(api.ChatTypePrivate)}, + Text: text, + Entities: []api.MessageEntity{ + {Type: string(api.EntityBotCommand), Offset: 0, Length: int64(len([]rune(text)))}, + }, + } +} + +func TestText(t *testing.T) { + f := msgfilter.Text(`^hello`) + require.True(t, f(msg("hello world"))) + require.False(t, f(msg("world hello"))) + require.False(t, f(nil)) +} + +func TestText_PanicsOnBadPattern(t *testing.T) { + require.Panics(t, func() { msgfilter.Text(`[invalid`) }) +} + +func TestTextEquals(t *testing.T) { + f := msgfilter.TextEquals("hi") + require.True(t, f(msg("hi"))) + require.False(t, f(msg("hi there"))) + require.False(t, f(nil)) +} + +func TestTextPrefix(t *testing.T) { + f := msgfilter.TextPrefix("/start") + require.True(t, f(msg("/start now"))) + require.False(t, f(msg("no prefix"))) + require.False(t, f(nil)) +} + +func TestTextContains(t *testing.T) { + f := msgfilter.TextContains("bot") + require.True(t, f(msg("my bot is cool"))) + require.False(t, f(msg("nothing here"))) + require.False(t, f(nil)) +} + +func TestCommand(t *testing.T) { + t.Run("matches exact command", func(t *testing.T) { + f := msgfilter.Command("/start") + require.True(t, f(cmdMsg("/start"))) + }) + t.Run("matches without leading slash", func(t *testing.T) { + f := msgfilter.Command("start") + require.True(t, f(cmdMsg("/start"))) + }) + t.Run("strips BotName suffix", func(t *testing.T) { + m := &api.Message{ + Text: "/start@MyBot", + Entities: []api.MessageEntity{{Type: string(api.EntityBotCommand), Offset: 0, Length: 12}}, + } + f := msgfilter.Command("/start") + require.True(t, f(m)) + }) + t.Run("no match different command", func(t *testing.T) { + f := msgfilter.Command("/stop") + require.False(t, f(cmdMsg("/start"))) + }) + t.Run("nil message", func(t *testing.T) { + require.False(t, msgfilter.Command("/start")(nil)) + }) + t.Run("no entities", func(t *testing.T) { + require.False(t, msgfilter.Command("/start")(msg("/start"))) + }) +} + +func TestAnyCommand(t *testing.T) { + f := msgfilter.AnyCommand() + require.True(t, f(cmdMsg("/anything"))) + require.False(t, f(msg("plain text"))) + require.False(t, f(nil)) +} + +func TestIsReply(t *testing.T) { + f := msgfilter.IsReply() + m := msg("reply") + m.ReplyToMessage = &api.Message{MessageID: 2} + require.True(t, f(m)) + require.False(t, f(msg("no reply"))) + require.False(t, f(nil)) +} + +func TestIsForward(t *testing.T) { + // ForwardOrigin is a MessageOrigin interface; set via a concrete type. + f := msgfilter.IsForward() + m := msg("fwd") + m.ForwardOrigin = &api.MessageOriginUser{Type: "user"} + require.True(t, f(m)) + require.False(t, f(msg("no fwd"))) + require.False(t, f(nil)) +} + +func TestHasPhoto(t *testing.T) { + f := msgfilter.HasPhoto() + m := msg("") + m.Photo = []api.PhotoSize{{FileID: "x", Width: 100, Height: 100}} + require.True(t, f(m)) + require.False(t, f(msg("no photo"))) + require.False(t, f(nil)) +} + +func TestHasDocument(t *testing.T) { + f := msgfilter.HasDocument() + m := msg("") + m.Document = &api.Document{FileID: "doc1"} + require.True(t, f(m)) + require.False(t, f(msg("no doc"))) + require.False(t, f(nil)) +} + +func TestHasEntity(t *testing.T) { + f := msgfilter.HasEntity(string(api.EntityURL)) + m := msg("check https://example.com") + m.Entities = []api.MessageEntity{{Type: string(api.EntityURL), Offset: 6, Length: 19}} + require.True(t, f(m)) + require.False(t, f(msg("plain"))) + require.False(t, f(nil)) +} + +func TestChatType(t *testing.T) { + f := msgfilter.ChatType(api.ChatTypePrivate) + private := msg("hi") + require.True(t, f(private)) + + group := msg("hi") + group.Chat.Type = string(api.ChatTypeGroup) + require.False(t, f(group)) + require.False(t, f(nil)) +} + +func TestFromUser(t *testing.T) { + f := msgfilter.FromUser(42) + m := msg("hi") + m.From = &api.User{ID: 42} + require.True(t, f(m)) + + m2 := msg("hi") + m2.From = &api.User{ID: 99} + require.False(t, f(m2)) + + require.False(t, f(msg("no from"))) + require.False(t, f(nil)) +} + +func TestInChat(t *testing.T) { + f := msgfilter.InChat(1) + require.True(t, f(msg("hi"))) + m2 := msg("hi") + m2.Chat.ID = 2 + require.False(t, f(m2)) + require.False(t, f(nil)) +} + +func TestComposedMessageFilters(t *testing.T) { + // private chat AND contains "hello" + f := msgfilter.ChatType(api.ChatTypePrivate).And(msgfilter.TextContains("hello")) + m := msg("say hello") + require.True(t, f(m)) + + m2 := msg("say hello") + m2.Chat.Type = string(api.ChatTypeGroup) + require.False(t, f(m2)) +} diff --git a/dispatch/filters/precheckoutquery/precheckoutquery.go b/dispatch/filters/precheckoutquery/precheckoutquery.go new file mode 100644 index 0000000..6515715 --- /dev/null +++ b/dispatch/filters/precheckoutquery/precheckoutquery.go @@ -0,0 +1,23 @@ +// Package precheckoutquery provides Filter helpers for *api.PreCheckoutQuery payloads. +package precheckoutquery + +import ( + "github.com/lukaszraczylo/go-telegram/api" + "github.com/lukaszraczylo/go-telegram/dispatch" +) + +// Currency returns a Filter that matches pre-checkout queries with the given +// ISO 4217 currency code (e.g. "USD", "EUR", "XTR"). +func Currency(c string) dispatch.Filter[*api.PreCheckoutQuery] { + return func(q *api.PreCheckoutQuery) bool { + return q != nil && q.Currency == c + } +} + +// FromUser returns a Filter that matches pre-checkout queries sent by the +// user with the given ID. +func FromUser(uid int64) dispatch.Filter[*api.PreCheckoutQuery] { + return func(q *api.PreCheckoutQuery) bool { + return q != nil && q.From.ID == uid + } +} diff --git a/dispatch/filters/precheckoutquery/precheckoutquery_test.go b/dispatch/filters/precheckoutquery/precheckoutquery_test.go new file mode 100644 index 0000000..fef9d28 --- /dev/null +++ b/dispatch/filters/precheckoutquery/precheckoutquery_test.go @@ -0,0 +1,38 @@ +package precheckoutquery_test + +import ( + "testing" + + "github.com/lukaszraczylo/go-telegram/api" + pcqfilter "github.com/lukaszraczylo/go-telegram/dispatch/filters/precheckoutquery" + "github.com/stretchr/testify/require" +) + +func pcq(currency string, fromID int64) *api.PreCheckoutQuery { + return &api.PreCheckoutQuery{ + ID: "q", + Currency: currency, + From: api.User{ID: fromID}, + } +} + +func TestCurrency_Matches(t *testing.T) { + f := pcqfilter.Currency("USD") + require.True(t, f(pcq("USD", 1))) + require.False(t, f(pcq("EUR", 1))) + require.False(t, f(nil)) +} + +func TestFromUser_Matches(t *testing.T) { + f := pcqfilter.FromUser(5) + require.True(t, f(pcq("USD", 5))) + require.False(t, f(pcq("USD", 9))) + require.False(t, f(nil)) +} + +func TestComposedFilters(t *testing.T) { + f := pcqfilter.Currency("XTR").And(pcqfilter.FromUser(42)) + require.True(t, f(pcq("XTR", 42))) + require.False(t, f(pcq("XTR", 99))) + require.False(t, f(pcq("USD", 42))) +} diff --git a/dispatch/groups.go b/dispatch/groups.go new file mode 100644 index 0000000..968b05b --- /dev/null +++ b/dispatch/groups.go @@ -0,0 +1,186 @@ +package dispatch + +import ( + "errors" + "regexp" + "sort" + + "github.com/lukaszraczylo/go-telegram/api" +) + +// ErrEndGroups stops dispatch from running any further handlers in any +// group for this update when returned by a handler. Use it to indicate +// the update has been definitively handled. +// +// errors.Is(err, ErrEndGroups) is the canonical check, though dispatch +// itself recognises it by exact identity. +var ErrEndGroups = errors.New("dispatch: end groups") + +// ErrContinueGroups signals that this group's handler should be treated +// as not-matching when returned by a handler: dispatch moves on to the +// next handler in the same group, then to subsequent groups. +// +// Without ErrContinueGroups, a non-error return from a matched handler +// stops dispatch (default first-match-wins semantics). +var ErrContinueGroups = errors.New("dispatch: continue groups") + +// RouterScope registers handlers into a specific priority group on its parent +// Router. Group 0 runs first, then group 1, etc. Within a group, handlers run +// in registration order; the first non-skipped match terminates dispatch +// unless the handler returns ErrContinueGroups. +type RouterScope struct { + router *Router + group int +} + +// Group returns a RouterScope that registers handlers in the given group. +// Group 0 (the default) runs first, then group 1, etc. Within a group, +// handlers run in registration order; the first non-skipped match +// terminates dispatch unless the handler returns ErrContinueGroups. +func (r *Router) Group(group int) *RouterScope { + return &RouterScope{router: r, group: group} +} + +// OnCommand registers a command handler in this group. +func (s *RouterScope) OnCommand(cmd string, h Handler[*api.Message]) { + s.router.groupCommands = append(s.router.groupCommands, groupCommandRoute{ + cmd: cmd, group: s.group, handler: h, + }) +} + +// OnText registers a regex text handler in this group. +// Panics at registration time if pattern is not a valid regular expression. +func (s *RouterScope) OnText(pattern string, h Handler[*api.Message]) { + s.router.groupTexts = append(s.router.groupTexts, groupTextRoute{ + re: regexp.MustCompile(pattern), group: s.group, handler: h, + }) +} + +// OnMessageFilter registers a filter-based message handler in this group. +func (s *RouterScope) OnMessageFilter(f Filter[*api.Message], h Handler[*api.Message]) { + s.router.groupMessageFilters = append(s.router.groupMessageFilters, groupMessageFilterRoute{ + filter: f, group: s.group, handler: h, + }) +} + +// group-aware route types + +type groupCommandRoute struct { + cmd string + group int + handler Handler[*api.Message] +} + +type groupTextRoute struct { + re *regexp.Regexp + group int + handler Handler[*api.Message] +} + +type groupMessageFilterRoute struct { + filter Filter[*api.Message] + group int + handler Handler[*api.Message] +} + +// dispatchGroups runs message handlers registered via RouterScope.Group(). +// It collects all matching groups, sorts by group number, and applies +// first-match-wins semantics within each group. Handlers may return +// ErrContinueGroups (skip to next handler/group) or ErrEndGroups (stop all groups). +// A non-sentinel error stops dispatch and is returned to the caller. +func (r *Router) dispatchGroups(c *Context, m *api.Message) error { + // Collect group numbers present. + groupSet := map[int]struct{}{} + for _, gr := range r.groupCommands { + groupSet[gr.group] = struct{}{} + } + for _, gr := range r.groupTexts { + groupSet[gr.group] = struct{}{} + } + for _, gr := range r.groupMessageFilters { + groupSet[gr.group] = struct{}{} + } + if len(groupSet) == 0 { + return nil + } + + groups := make([]int, 0, len(groupSet)) + for g := range groupSet { + groups = append(groups, g) + } + sort.Ints(groups) + + for _, g := range groups { + matched, err := r.runGroupHandlers(c, m, g) + if err != nil { + if errors.Is(err, ErrEndGroups) { + return nil + } + return err + } + if matched { + // First-match-wins: stop further groups. + return nil + } + // No match or ErrContinueGroups from all handlers: try next group. + } + return nil +} + +// runGroupHandlers runs all handlers in group g against m, in registration +// order. Returns (true, nil) when a handler matched (returned nil). Returns +// (false, nil) when all handlers returned ErrContinueGroups. Returns +// (false, err) for ErrEndGroups or any non-sentinel error. +func (r *Router) runGroupHandlers(c *Context, m *api.Message, g int) (matched bool, err error) { + // Commands. + if cmd, args, ok := extractCommand(m); ok { + for _, route := range r.groupCommands { + if route.group != g || route.cmd != cmd { + continue + } + c.Values["command"] = cmd + c.Values["command_args"] = args + if err := route.handler(c, m); err != nil { + if errors.Is(err, ErrContinueGroups) { + continue + } + return false, err + } + return true, nil + } + } + // Text regex. + if m.Text != "" { + for _, route := range r.groupTexts { + if route.group != g { + continue + } + subs := route.re.FindStringSubmatch(m.Text) + if subs == nil { + continue + } + c.Values["regex_match"] = subs + if err := route.handler(c, m); err != nil { + if errors.Is(err, ErrContinueGroups) { + continue + } + return false, err + } + return true, nil + } + } + // Filter-based. + for _, route := range r.groupMessageFilters { + if route.group != g || !route.filter(m) { + continue + } + if err := route.handler(c, m); err != nil { + if errors.Is(err, ErrContinueGroups) { + continue + } + return false, err + } + return true, nil + } + return false, nil +} diff --git a/dispatch/groups_test.go b/dispatch/groups_test.go new file mode 100644 index 0000000..a0c7ca8 --- /dev/null +++ b/dispatch/groups_test.go @@ -0,0 +1,209 @@ +package dispatch + +import ( + "context" + "sync/atomic" + "testing" + "time" + + "github.com/lukaszraczylo/go-telegram/api" + "github.com/lukaszraczylo/go-telegram/client" + "github.com/stretchr/testify/require" +) + +// msgUpdate builds a simple private message update. +func msgUpdate(id int64, text string) api.Update { + return api.Update{ + UpdateID: id, + Message: &api.Message{ + MessageID: id, + Chat: api.Chat{ID: 1, Type: string(api.ChatTypePrivate)}, + Text: text, + }, + } +} + +// cmdUpdate builds a command message update. +func cmdUpdate(id int64, cmd string) api.Update { + return api.Update{ + UpdateID: id, + Message: &api.Message{ + MessageID: id, + Chat: api.Chat{ID: 1, Type: string(api.ChatTypePrivate)}, + Text: cmd, + Entities: []api.MessageEntity{ + {Type: string(api.EntityBotCommand), Offset: 0, Length: int64(len(cmd))}, + }, + }, + } +} + +// runSingle fires one update through the router and waits for it to complete. +func runSingle(t *testing.T, r *Router, up api.Update) { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond) + defer cancel() + _ = r.Run(ctx, newFake(up)) +} + +// TestGroup_Order verifies group 0 fires before group 1. +func TestGroup_Order(t *testing.T) { + r := New(client.New("t")) + var order []int + + r.Group(0).OnText(`.*`, func(c *Context, m *api.Message) error { + order = append(order, 0) + return ErrContinueGroups // let group 1 also run + }) + r.Group(1).OnText(`.*`, func(c *Context, m *api.Message) error { + order = append(order, 1) + return nil + }) + + runSingle(t, r, msgUpdate(1, "hello")) + require.Equal(t, []int{0, 1}, order) +} + +// TestGroup_FirstMatchWins verifies group 0 match stops group 1 by default. +func TestGroup_FirstMatchWins(t *testing.T) { + r := New(client.New("t")) + var fired []int + + r.Group(0).OnText(`.*`, func(c *Context, m *api.Message) error { + fired = append(fired, 0) + return nil // matched — group 1 must NOT run + }) + r.Group(1).OnText(`.*`, func(c *Context, m *api.Message) error { + fired = append(fired, 1) + return nil + }) + + runSingle(t, r, msgUpdate(1, "hello")) + require.Equal(t, []int{0}, fired) +} + +// TestGroup_ErrContinueGroups lets group 1 run when group 0 returns ErrContinueGroups. +func TestGroup_ErrContinueGroups(t *testing.T) { + r := New(client.New("t")) + g1Hit := make(chan struct{}, 1) + + r.Group(0).OnText(`.*`, func(c *Context, m *api.Message) error { + return ErrContinueGroups + }) + r.Group(1).OnText(`.*`, func(c *Context, m *api.Message) error { + g1Hit <- struct{}{} + return nil + }) + + ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond) + defer cancel() + go func() { _ = r.Run(ctx, newFake(msgUpdate(1, "ping"))) }() + + select { + case <-g1Hit: + case <-ctx.Done(): + t.Fatal("group 1 handler never fired") + } +} + +// TestGroup_ErrEndGroups stops all further groups. +func TestGroup_ErrEndGroups(t *testing.T) { + r := New(client.New("t")) + var fired []int + + r.Group(0).OnText(`.*`, func(c *Context, m *api.Message) error { + fired = append(fired, 0) + return ErrEndGroups + }) + r.Group(1).OnText(`.*`, func(c *Context, m *api.Message) error { + fired = append(fired, 1) + return nil + }) + + runSingle(t, r, msgUpdate(1, "hello")) + require.Equal(t, []int{0}, fired) +} + +// TestGroup_NonSentinelError propagates error and stops further groups. +func TestGroup_NonSentinelError(t *testing.T) { + r := New(client.New("t"), WithMaxConcurrency(0)) + var fired []int + + r.Group(0).OnText(`.*`, func(c *Context, m *api.Message) error { + fired = append(fired, 0) + return context.DeadlineExceeded // non-sentinel real error + }) + r.Group(1).OnText(`.*`, func(c *Context, m *api.Message) error { + fired = append(fired, 1) + return nil + }) + + runSingle(t, r, msgUpdate(1, "hello")) + // group 1 must not fire + require.Equal(t, []int{0}, fired) +} + +// TestGroup_Command verifies OnCommand in a group works. +func TestGroup_Command(t *testing.T) { + r := New(client.New("t")) + hit := make(chan string, 1) + + r.Group(0).OnCommand("/start", func(c *Context, m *api.Message) error { + hit <- "g0-start" + return nil + }) + r.Group(1).OnCommand("/start", func(c *Context, m *api.Message) error { + hit <- "g1-start" + return nil + }) + + ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond) + defer cancel() + go func() { _ = r.Run(ctx, newFake(cmdUpdate(1, "/start"))) }() + + got := <-hit + require.Equal(t, "g0-start", got) +} + +// TestGroup_MessageFilter verifies OnMessageFilter in a group works. +func TestGroup_MessageFilter(t *testing.T) { + r := New(client.New("t")) + hit := make(chan bool, 1) + + r.Group(0).OnMessageFilter( + Filter[*api.Message](func(m *api.Message) bool { return m != nil && m.Text == "ok" }), + func(c *Context, m *api.Message) error { + hit <- true + return nil + }, + ) + + ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond) + defer cancel() + go func() { _ = r.Run(ctx, newFake(msgUpdate(1, "ok"))) }() + + require.True(t, <-hit) +} + +// TestGroup_ErrContinueGroups_WithCommand verifies ErrContinueGroups works for commands across groups. +func TestGroup_ErrContinueGroups_WithCommand(t *testing.T) { + r := New(client.New("t")) + var count atomic.Int32 + + r.Group(0).OnCommand("/ping", func(c *Context, m *api.Message) error { + count.Add(1) + return ErrContinueGroups + }) + r.Group(1).OnCommand("/ping", func(c *Context, m *api.Message) error { + count.Add(10) + return nil + }) + + ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond) + defer cancel() + go func() { _ = r.Run(ctx, newFake(cmdUpdate(1, "/ping"))) }() + time.Sleep(100 * time.Millisecond) + cancel() + + require.Equal(t, int32(11), count.Load()) +} diff --git a/dispatch/handler.go b/dispatch/handler.go new file mode 100644 index 0000000..67aae5e --- /dev/null +++ b/dispatch/handler.go @@ -0,0 +1,21 @@ +package dispatch + +// Handler is a generic handler over update payload type T. T is typically +// *api.Message, *api.CallbackQuery, *api.InlineQuery, or *api.Update for +// global middleware. +type Handler[T any] func(ctx *Context, payload T) error + +// Middleware wraps a Handler[T] with cross-cutting behaviour (logging, +// recovery, auth). Middleware composition is left-to-right: Use(a,b,c) +// runs as a(b(c(handler))). +type Middleware[T any] func(Handler[T]) Handler[T] + +// Chain composes a slice of middleware into a single Middleware[T]. +func Chain[T any](mws ...Middleware[T]) Middleware[T] { + return func(h Handler[T]) Handler[T] { + for i := len(mws) - 1; i >= 0; i-- { + h = mws[i](h) + } + return h + } +} diff --git a/dispatch/middleware.go b/dispatch/middleware.go new file mode 100644 index 0000000..0fb6eb5 --- /dev/null +++ b/dispatch/middleware.go @@ -0,0 +1,27 @@ +package dispatch + +import ( + "fmt" + "runtime/debug" + + "github.com/lukaszraczylo/go-telegram/api" +) + +// Recovery returns middleware that recovers from panics in downstream +// handlers, converting them into a returned error and logging via the +// bot's configured logger. Registered automatically by NewRouter. +func Recovery() Middleware[*api.Update] { + return func(next Handler[*api.Update]) Handler[*api.Update] { + return func(c *Context, u *api.Update) (err error) { + defer func() { + if r := recover(); r != nil { + err = fmt.Errorf("panic in handler: %v\n%s", r, debug.Stack()) + if c.Bot != nil { + c.Bot.Logger().Error("dispatch recovered panic", "err", err) + } + } + }() + return next(c, u) + } + } +} diff --git a/dispatch/named.go b/dispatch/named.go new file mode 100644 index 0000000..6d8c633 --- /dev/null +++ b/dispatch/named.go @@ -0,0 +1,101 @@ +package dispatch + +import ( + "fmt" + "sync" +) + +// NamedHandlers manages handlers by string name, allowing runtime +// registration, replacement, and removal. This complements the Router's +// registration methods: each registration via Named*() also gets a name +// for later lookup. +// +// Use case: a plugin system that loads/unloads command handlers without +// restarting the bot. +type NamedHandlers[T any] struct { + mu sync.RWMutex + handlers map[string]Handler[T] + order []string // preserves registration order +} + +// NewNamedHandlers returns a new, empty NamedHandlers[T]. +func NewNamedHandlers[T any]() *NamedHandlers[T] { + return &NamedHandlers[T]{handlers: map[string]Handler[T]{}} +} + +// Set registers or replaces the handler under name. If name is new, it is +// appended to the end of the registration order. +func (n *NamedHandlers[T]) Set(name string, h Handler[T]) { + n.mu.Lock() + defer n.mu.Unlock() + if _, exists := n.handlers[name]; !exists { + n.order = append(n.order, name) + } + n.handlers[name] = h +} + +// Remove unregisters the handler under name. Returns true if it existed. +func (n *NamedHandlers[T]) Remove(name string) bool { + n.mu.Lock() + defer n.mu.Unlock() + if _, ok := n.handlers[name]; !ok { + return false + } + delete(n.handlers, name) + for i, k := range n.order { + if k == name { + n.order = append(n.order[:i], n.order[i+1:]...) + break + } + } + return true +} + +// Has reports whether name is registered. +func (n *NamedHandlers[T]) Has(name string) bool { + n.mu.RLock() + defer n.mu.RUnlock() + _, ok := n.handlers[name] + return ok +} + +// Names returns the registered names in registration order. +func (n *NamedHandlers[T]) Names() []string { + n.mu.RLock() + defer n.mu.RUnlock() + out := make([]string, len(n.order)) + copy(out, n.order) + return out +} + +// Handler returns a single Handler[T] that runs each registered handler +// in registration order, first non-nil error stops the chain. Use this +// to wire NamedHandlers into a Router.OnXxx call: +// +// names := dispatch.NewNamedHandlers[*api.Message]() +// names.Set("logger", loggingHandler) +// names.Set("audit", auditHandler) +// router.OnCommand("/admin", names.Handler()) +// +// Subsequent Set/Remove calls take effect on the next dispatch. +func (n *NamedHandlers[T]) Handler() Handler[T] { + return func(c *Context, payload T) error { + n.mu.RLock() + names := make([]string, len(n.order)) + copy(names, n.order) + n.mu.RUnlock() + + for _, name := range names { + n.mu.RLock() + h, ok := n.handlers[name] + n.mu.RUnlock() + if !ok { + continue + } + if err := h(c, payload); err != nil { + return fmt.Errorf("named handler %q: %w", name, err) + } + } + return nil + } +} diff --git a/dispatch/named_test.go b/dispatch/named_test.go new file mode 100644 index 0000000..d05c904 --- /dev/null +++ b/dispatch/named_test.go @@ -0,0 +1,153 @@ +package dispatch + +import ( + "context" + "errors" + "fmt" + "sync" + "testing" + + "github.com/lukaszraczylo/go-telegram/api" + "github.com/stretchr/testify/require" +) + +// makeMsg returns a minimal *api.Message for use in handler tests. +func makeMsg() *api.Message { + return &api.Message{MessageID: 1, Chat: api.Chat{ID: 1, Type: "private"}} +} + +// makeCtx returns a minimal *Context (nil bot is fine for unit tests). +func makeCtx() *Context { + return NewContext(context.Background(), nil, &api.Update{}) +} + +func TestNamedHandlers_SetAndHas(t *testing.T) { + n := NewNamedHandlers[*api.Message]() + require.False(t, n.Has("a")) + n.Set("a", func(c *Context, m *api.Message) error { return nil }) + require.True(t, n.Has("a")) +} + +func TestNamedHandlers_Names_RegistrationOrder(t *testing.T) { + n := NewNamedHandlers[*api.Message]() + n.Set("first", func(c *Context, m *api.Message) error { return nil }) + n.Set("second", func(c *Context, m *api.Message) error { return nil }) + n.Set("third", func(c *Context, m *api.Message) error { return nil }) + require.Equal(t, []string{"first", "second", "third"}, n.Names()) +} + +func TestNamedHandlers_Remove(t *testing.T) { + n := NewNamedHandlers[*api.Message]() + n.Set("a", func(c *Context, m *api.Message) error { return nil }) + n.Set("b", func(c *Context, m *api.Message) error { return nil }) + + removed := n.Remove("a") + require.True(t, removed) + require.False(t, n.Has("a")) + require.Equal(t, []string{"b"}, n.Names()) + + // Remove non-existent returns false. + require.False(t, n.Remove("nonexistent")) +} + +func TestNamedHandlers_Replacement_SameOrderSlot(t *testing.T) { + n := NewNamedHandlers[*api.Message]() + n.Set("a", func(c *Context, m *api.Message) error { return nil }) + n.Set("b", func(c *Context, m *api.Message) error { return nil }) + + var called string + n.Set("a", func(c *Context, m *api.Message) error { + called = "replaced-a" + return nil + }) + + // Order must not change; "a" stays first. + require.Equal(t, []string{"a", "b"}, n.Names()) + + h := n.Handler() + _ = h(makeCtx(), makeMsg()) + require.Equal(t, "replaced-a", called) +} + +func TestNamedHandlers_Handler_RunsInOrder(t *testing.T) { + n := NewNamedHandlers[*api.Message]() + var calls []string + + n.Set("first", func(c *Context, m *api.Message) error { + calls = append(calls, "first") + return nil + }) + n.Set("second", func(c *Context, m *api.Message) error { + calls = append(calls, "second") + return nil + }) + + h := n.Handler() + require.NoError(t, h(makeCtx(), makeMsg())) + require.Equal(t, []string{"first", "second"}, calls) +} + +func TestNamedHandlers_Handler_ErrorWrappedAndStops(t *testing.T) { + n := NewNamedHandlers[*api.Message]() + sentinel := errors.New("boom") + + n.Set("ok", func(c *Context, m *api.Message) error { return nil }) + n.Set("fail", func(c *Context, m *api.Message) error { return sentinel }) + n.Set("never", func(c *Context, m *api.Message) error { + t.Fatal("should not be called after an error") + return nil + }) + + h := n.Handler() + err := h(makeCtx(), makeMsg()) + require.Error(t, err) + require.True(t, errors.Is(err, sentinel)) + require.Contains(t, err.Error(), `named handler "fail"`) +} + +func TestNamedHandlers_Concurrent_SetRemove(t *testing.T) { + n := NewNamedHandlers[*api.Message]() + + // Pre-populate so Handler() has something to iterate. + for i := range 5 { + name := fmt.Sprintf("h%d", i) + n.Set(name, func(c *Context, m *api.Message) error { return nil }) + } + + h := n.Handler() + var wg sync.WaitGroup + + // Concurrent readers (invoke handler). + for range 20 { + wg.Add(1) + go func() { + defer wg.Done() + _ = h(makeCtx(), makeMsg()) + }() + } + + // Concurrent writers. + for i := range 5 { + wg.Add(1) + go func(i int) { + defer wg.Done() + name := fmt.Sprintf("new%d", i) + n.Set(name, func(c *Context, m *api.Message) error { return nil }) + n.Remove(fmt.Sprintf("h%d", i)) + }(i) + } + + wg.Wait() +} + +func TestNamedHandlers_RemoveAndReinstate(t *testing.T) { + n := NewNamedHandlers[*api.Message]() + n.Set("a", func(c *Context, m *api.Message) error { return nil }) + n.Remove("a") + require.False(t, n.Has("a")) + + // Re-register after removal; should be added at end. + n.Set("b", func(c *Context, m *api.Message) error { return nil }) + n.Set("a", func(c *Context, m *api.Message) error { return nil }) + require.Equal(t, []string{"b", "a"}, n.Names()) +} diff --git a/dispatch/router.go b/dispatch/router.go new file mode 100644 index 0000000..7fa8eb5 --- /dev/null +++ b/dispatch/router.go @@ -0,0 +1,582 @@ +package dispatch + +import ( + "context" + "regexp" + "strings" + "sync" + "unicode/utf8" + + "github.com/lukaszraczylo/go-telegram/api" + "github.com/lukaszraczylo/go-telegram/client" + "github.com/lukaszraczylo/go-telegram/transport" +) + +// Router dispatches updates from any Updater to typed handlers. +// +// Matchers run in registration order; first match wins. A panic-recovery +// middleware is attached automatically and runs around every dispatch. +type Router struct { + bot *client.Bot + + commands []commandRoute + texts []textRoute + callbacks []callbackRoute + inlines []Handler[*api.InlineQuery] + editedMsg []Handler[*api.Message] + channelPosts []Handler[*api.Message] + editedChannelPosts []Handler[*api.Message] + + messageFilters []messageFilterRoute + callbackFilters []callbackFilterRoute + inlineFilters []inlineFilterRoute + + // typed update handlers + myChatMember []Handler[*api.ChatMemberUpdated] + chatMember []Handler[*api.ChatMemberUpdated] + chatJoinRequest []Handler[*api.ChatJoinRequest] + preCheckoutQuery []Handler[*api.PreCheckoutQuery] + shippingQuery []Handler[*api.ShippingQuery] + poll []Handler[*api.Poll] + pollAnswer []Handler[*api.PollAnswer] + chosenInlineResult []Handler[*api.ChosenInlineResult] + messageReaction []Handler[*api.MessageReactionUpdated] + messageReactionCnt []Handler[*api.MessageReactionCountUpdated] + chatBoost []Handler[*api.ChatBoostUpdated] + removedChatBoost []Handler[*api.ChatBoostRemoved] + businessConn []Handler[*api.BusinessConnection] + purchasedPaidMedia []Handler[*api.PaidMediaPurchased] + + myChatMemberFilters []chatMemberFilterRoute + chatMemberFilters []chatMemberFilterRoute + chatJoinRequestFilters []chatJoinRequestFilterRoute + preCheckoutFilters []preCheckoutFilterRoute + + // group-priority routes (registered via Router.Group()) + groupCommands []groupCommandRoute + groupTexts []groupTextRoute + groupMessageFilters []groupMessageFilterRoute + + globalMW []Middleware[*api.Update] + + maxConcurrency int // default 50; 0 = serial (legacy) + sem chan struct{} +} + +type messageFilterRoute struct { + filter Filter[*api.Message] + handler Handler[*api.Message] +} + +type callbackFilterRoute struct { + filter Filter[*api.CallbackQuery] + handler Handler[*api.CallbackQuery] +} + +type inlineFilterRoute struct { + filter Filter[*api.InlineQuery] + handler Handler[*api.InlineQuery] +} + +type chatMemberFilterRoute struct { + filter Filter[*api.ChatMemberUpdated] + handler Handler[*api.ChatMemberUpdated] +} + +type chatJoinRequestFilterRoute struct { + filter Filter[*api.ChatJoinRequest] + handler Handler[*api.ChatJoinRequest] +} + +type preCheckoutFilterRoute struct { + filter Filter[*api.PreCheckoutQuery] + handler Handler[*api.PreCheckoutQuery] +} + +// RouterOption configures a Router at construction time. +type RouterOption func(*Router) + +// WithMaxConcurrency sets the maximum number of updates processed in parallel. +// Default is 50. Pass 0 to dispatch serially (one update at a time, in the +// calling goroutine — the legacy behaviour before v1.1.0). +// +// Note: concurrent dispatch means handlers for different updates may run +// simultaneously. Handlers that mutate shared state must be safe for concurrent +// access. +func WithMaxConcurrency(n int) RouterOption { + return func(r *Router) { r.maxConcurrency = n } +} + +type commandRoute struct { + cmd string + handler Handler[*api.Message] +} + +type textRoute struct { + re *regexp.Regexp + handler Handler[*api.Message] +} + +type callbackRoute struct { + re *regexp.Regexp + handler Handler[*api.CallbackQuery] +} + +// New constructs a Router. Recovery middleware is added by default; users +// can disable it by passing WithoutRecovery (not implemented here, but +// the hook is in place via Use). +func New(b *client.Bot, opts ...RouterOption) *Router { + r := &Router{bot: b, maxConcurrency: 50} + for _, o := range opts { + o(r) + } + if r.maxConcurrency > 0 { + r.sem = make(chan struct{}, r.maxConcurrency) + } + r.Use(Recovery()) + return r +} + +// Use registers a global middleware applied to every Update dispatch. +func (r *Router) Use(mw Middleware[*api.Update]) { r.globalMW = append(r.globalMW, mw) } + +// OnCommand registers a handler for a slash command. The command string +// includes the leading slash (e.g. "/start"). Matching strips an optional +// "@BotName" suffix. +func (r *Router) OnCommand(cmd string, h Handler[*api.Message]) { + r.commands = append(r.commands, commandRoute{cmd: cmd, handler: h}) +} + +// OnText registers a handler for messages whose Text matches the regex. +// +// Panics at registration time if pattern is not a valid regular expression. +func (r *Router) OnText(pattern string, h Handler[*api.Message]) { + r.texts = append(r.texts, textRoute{re: regexp.MustCompile(pattern), handler: h}) +} + +// OnCallback registers a handler for callback queries whose Data matches +// the regex. +// +// Panics at registration time if pattern is not a valid regular expression. +func (r *Router) OnCallback(pattern string, h Handler[*api.CallbackQuery]) { + r.callbacks = append(r.callbacks, callbackRoute{re: regexp.MustCompile(pattern), handler: h}) +} + +// OnInlineQuery registers a handler for inline queries (one matcher only; +// inline queries are not partitioned by content here). +func (r *Router) OnInlineQuery(h Handler[*api.InlineQuery]) { + r.inlines = append(r.inlines, h) +} + +// OnEditedMessage registers a handler for edited message updates. +func (r *Router) OnEditedMessage(h Handler[*api.Message]) { + r.editedMsg = append(r.editedMsg, h) +} + +// OnChannelPost registers a handler for channel post updates. +func (r *Router) OnChannelPost(h Handler[*api.Message]) { + r.channelPosts = append(r.channelPosts, h) +} + +// OnEditedChannelPost registers a handler for edited channel post updates. +func (r *Router) OnEditedChannelPost(h Handler[*api.Message]) { + r.editedChannelPosts = append(r.editedChannelPosts, h) +} + +// OnMessageFilter registers a typed message handler gated by filter f. +// Filter routes are checked after command and text routes; first match wins. +func (r *Router) OnMessageFilter(f Filter[*api.Message], h Handler[*api.Message]) { + r.messageFilters = append(r.messageFilters, messageFilterRoute{filter: f, handler: h}) +} + +// OnCallbackFilter registers a typed callback-query handler gated by filter f. +// Filter routes are checked after pattern-based OnCallback routes; first match wins. +func (r *Router) OnCallbackFilter(f Filter[*api.CallbackQuery], h Handler[*api.CallbackQuery]) { + r.callbackFilters = append(r.callbackFilters, callbackFilterRoute{filter: f, handler: h}) +} + +// OnInlineQueryFilter registers an inline-query handler gated by filter f. +// Filter routes are checked after bare OnInlineQuery handlers; first match wins. +func (r *Router) OnInlineQueryFilter(f Filter[*api.InlineQuery], h Handler[*api.InlineQuery]) { + r.inlineFilters = append(r.inlineFilters, inlineFilterRoute{filter: f, handler: h}) +} + +// OnMyChatMember registers a handler for bot's own chat member status changes. +func (r *Router) OnMyChatMember(h Handler[*api.ChatMemberUpdated]) { + r.myChatMember = append(r.myChatMember, h) +} + +// OnMyChatMemberFilter registers a filtered handler for bot's own chat member status changes. +func (r *Router) OnMyChatMemberFilter(f Filter[*api.ChatMemberUpdated], h Handler[*api.ChatMemberUpdated]) { + r.myChatMemberFilters = append(r.myChatMemberFilters, chatMemberFilterRoute{filter: f, handler: h}) +} + +// OnChatMember registers a handler for chat member status changes. +func (r *Router) OnChatMember(h Handler[*api.ChatMemberUpdated]) { + r.chatMember = append(r.chatMember, h) +} + +// OnChatMemberFilter registers a filtered handler for chat member status changes. +func (r *Router) OnChatMemberFilter(f Filter[*api.ChatMemberUpdated], h Handler[*api.ChatMemberUpdated]) { + r.chatMemberFilters = append(r.chatMemberFilters, chatMemberFilterRoute{filter: f, handler: h}) +} + +// OnChatJoinRequest registers a handler for chat join requests. +func (r *Router) OnChatJoinRequest(h Handler[*api.ChatJoinRequest]) { + r.chatJoinRequest = append(r.chatJoinRequest, h) +} + +// OnChatJoinRequestFilter registers a filtered handler for chat join requests. +func (r *Router) OnChatJoinRequestFilter(f Filter[*api.ChatJoinRequest], h Handler[*api.ChatJoinRequest]) { + r.chatJoinRequestFilters = append(r.chatJoinRequestFilters, chatJoinRequestFilterRoute{filter: f, handler: h}) +} + +// OnPreCheckoutQuery registers a handler for pre-checkout queries. +func (r *Router) OnPreCheckoutQuery(h Handler[*api.PreCheckoutQuery]) { + r.preCheckoutQuery = append(r.preCheckoutQuery, h) +} + +// OnPreCheckoutQueryFilter registers a filtered handler for pre-checkout queries. +func (r *Router) OnPreCheckoutQueryFilter(f Filter[*api.PreCheckoutQuery], h Handler[*api.PreCheckoutQuery]) { + r.preCheckoutFilters = append(r.preCheckoutFilters, preCheckoutFilterRoute{filter: f, handler: h}) +} + +// OnShippingQuery registers a handler for shipping queries. +func (r *Router) OnShippingQuery(h Handler[*api.ShippingQuery]) { + r.shippingQuery = append(r.shippingQuery, h) +} + +// OnPoll registers a handler for poll state updates. +func (r *Router) OnPoll(h Handler[*api.Poll]) { + r.poll = append(r.poll, h) +} + +// OnPollAnswer registers a handler for poll answer updates. +func (r *Router) OnPollAnswer(h Handler[*api.PollAnswer]) { + r.pollAnswer = append(r.pollAnswer, h) +} + +// OnChosenInlineResult registers a handler for chosen inline results. +func (r *Router) OnChosenInlineResult(h Handler[*api.ChosenInlineResult]) { + r.chosenInlineResult = append(r.chosenInlineResult, h) +} + +// OnMessageReaction registers a handler for message reaction updates. +func (r *Router) OnMessageReaction(h Handler[*api.MessageReactionUpdated]) { + r.messageReaction = append(r.messageReaction, h) +} + +// OnMessageReactionCount registers a handler for anonymous message reaction count updates. +func (r *Router) OnMessageReactionCount(h Handler[*api.MessageReactionCountUpdated]) { + r.messageReactionCnt = append(r.messageReactionCnt, h) +} + +// OnChatBoost registers a handler for chat boost updates. +func (r *Router) OnChatBoost(h Handler[*api.ChatBoostUpdated]) { + r.chatBoost = append(r.chatBoost, h) +} + +// OnRemovedChatBoost registers a handler for removed chat boost updates. +func (r *Router) OnRemovedChatBoost(h Handler[*api.ChatBoostRemoved]) { + r.removedChatBoost = append(r.removedChatBoost, h) +} + +// OnBusinessConnection registers a handler for business connection updates. +func (r *Router) OnBusinessConnection(h Handler[*api.BusinessConnection]) { + r.businessConn = append(r.businessConn, h) +} + +// OnPurchasedPaidMedia registers a handler for purchased paid media updates. +func (r *Router) OnPurchasedPaidMedia(h Handler[*api.PaidMediaPurchased]) { + r.purchasedPaidMedia = append(r.purchasedPaidMedia, h) +} + +// Run consumes the Updater and dispatches each update. It blocks until +// the Updater's channel is closed or ctx is cancelled. +// +// By default updates are processed concurrently (up to WithMaxConcurrency(50) +// goroutines). Handlers for different updates may therefore run simultaneously; +// shared state must be protected. Pass WithMaxConcurrency(0) to New to restore +// serial (legacy) behaviour. +// +// Run waits for all in-flight handlers to finish before returning. +func (r *Router) Run(ctx context.Context, u transport.Updater) error { + runErr := make(chan error, 1) + go func() { runErr <- u.Run(ctx) }() + + root := r.dispatch + for i := len(r.globalMW) - 1; i >= 0; i-- { + root = r.globalMW[i](root) + } + + var wg sync.WaitGroup + defer wg.Wait() + + dispatch := func(up api.Update) { + c := NewContext(ctx, r.bot, &up) + if err := root(c, &up); err != nil { + if r.bot != nil { + r.bot.Logger().Error("dispatch handler error", "err", err, "update_id", up.UpdateID) + } + } + } + + for { + select { + case <-ctx.Done(): + return ctx.Err() + case err := <-runErr: + return err + case up, ok := <-u.Updates(): + if !ok { + // Channel closed; consume the run error if pending. + select { + case err := <-runErr: + return err + default: + } + return nil + } + + if r.sem == nil { + // Serial mode (legacy / WithMaxConcurrency(0)). + dispatch(up) + continue + } + + // Concurrent mode: acquire semaphore slot then launch goroutine. + select { + case r.sem <- struct{}{}: + case <-ctx.Done(): + return ctx.Err() + } + wg.Add(1) + go func(up api.Update) { + defer func() { + <-r.sem + wg.Done() + }() + dispatch(up) + }(up) + } + } +} + +func (r *Router) dispatch(c *Context, u *api.Update) error { + switch { + case u.Message != nil: + return r.handleMessage(c, u.Message) + case u.EditedMessage != nil: + return runHandlers(r.editedMsg, c, u.EditedMessage) + case u.ChannelPost != nil: + return runHandlers(r.channelPosts, c, u.ChannelPost) + case u.EditedChannelPost != nil: + return runHandlers(r.editedChannelPosts, c, u.EditedChannelPost) + case u.CallbackQuery != nil: + return r.handleCallback(c, u.CallbackQuery) + case u.InlineQuery != nil: + if err := runHandlers(r.inlines, c, u.InlineQuery); err != nil { + return err + } + for _, route := range r.inlineFilters { + if route.filter(u.InlineQuery) { + return route.handler(c, u.InlineQuery) + } + } + return nil + case u.MyChatMember != nil: + return r.handleChatMemberUpdate(c, u.MyChatMember, r.myChatMember, r.myChatMemberFilters) + case u.ChatMember != nil: + return r.handleChatMemberUpdate(c, u.ChatMember, r.chatMember, r.chatMemberFilters) + case u.ChatJoinRequest != nil: + return r.handleChatJoinRequest(c, u.ChatJoinRequest) + case u.PreCheckoutQuery != nil: + return r.handlePreCheckoutQuery(c, u.PreCheckoutQuery) + case u.ShippingQuery != nil: + return runHandlers(r.shippingQuery, c, u.ShippingQuery) + case u.Poll != nil: + return runHandlers(r.poll, c, u.Poll) + case u.PollAnswer != nil: + return runHandlers(r.pollAnswer, c, u.PollAnswer) + case u.ChosenInlineResult != nil: + return runHandlers(r.chosenInlineResult, c, u.ChosenInlineResult) + case u.MessageReaction != nil: + return runHandlers(r.messageReaction, c, u.MessageReaction) + case u.MessageReactionCount != nil: + return runHandlers(r.messageReactionCnt, c, u.MessageReactionCount) + case u.ChatBoost != nil: + return runHandlers(r.chatBoost, c, u.ChatBoost) + case u.RemovedChatBoost != nil: + return runHandlers(r.removedChatBoost, c, u.RemovedChatBoost) + case u.BusinessConnection != nil: + return runHandlers(r.businessConn, c, u.BusinessConnection) + case u.PurchasedPaidMedia != nil: + return runHandlers(r.purchasedPaidMedia, c, u.PurchasedPaidMedia) + } + return nil +} + +func (r *Router) handleChatMemberUpdate(c *Context, payload *api.ChatMemberUpdated, handlers []Handler[*api.ChatMemberUpdated], filters []chatMemberFilterRoute) error { + if err := runHandlers(handlers, c, payload); err != nil { + return err + } + for _, route := range filters { + if route.filter(payload) { + return route.handler(c, payload) + } + } + return nil +} + +func (r *Router) handleChatJoinRequest(c *Context, payload *api.ChatJoinRequest) error { + if err := runHandlers(r.chatJoinRequest, c, payload); err != nil { + return err + } + for _, route := range r.chatJoinRequestFilters { + if route.filter(payload) { + return route.handler(c, payload) + } + } + return nil +} + +func (r *Router) handlePreCheckoutQuery(c *Context, payload *api.PreCheckoutQuery) error { + if err := runHandlers(r.preCheckoutQuery, c, payload); err != nil { + return err + } + for _, route := range r.preCheckoutFilters { + if route.filter(payload) { + return route.handler(c, payload) + } + } + return nil +} + +// runHandlers invokes each handler in order; returns the first non-nil error. +func runHandlers[T any](handlers []Handler[T], c *Context, payload T) error { + for _, h := range handlers { + if err := h(c, payload); err != nil { + return err + } + } + return nil +} + +func (r *Router) handleMessage(c *Context, m *api.Message) error { + // Try command first (entity-aware). + if cmd, args, ok := extractCommand(m); ok { + for _, route := range r.commands { + if route.cmd == cmd { + c.Values["command"] = cmd + c.Values["command_args"] = args + return route.handler(c, m) + } + } + } + // Then text regex matchers. + if m.Text != "" { + for _, route := range r.texts { + if subs := route.re.FindStringSubmatch(m.Text); subs != nil { + c.Values["regex_match"] = subs + return route.handler(c, m) + } + } + } + // Filter-based routes. + for _, route := range r.messageFilters { + if route.filter(m) { + return route.handler(c, m) + } + } + // Group-priority routes (registered via RouterScope.Group()). + return r.dispatchGroups(c, m) +} + +func (r *Router) handleCallback(c *Context, q *api.CallbackQuery) error { + for _, route := range r.callbacks { + if subs := route.re.FindStringSubmatch(q.Data); subs != nil { + c.Values["regex_match"] = subs + return route.handler(c, q) + } + } + // Filter-based routes checked after pattern routes. + for _, route := range r.callbackFilters { + if route.filter(q) { + return route.handler(c, q) + } + } + return nil +} + +// extractCommand returns the command (e.g. "/start") and the remaining +// argument string, when m carries a leading bot_command entity. It strips +// optional "@BotName" suffix on the command itself. +func extractCommand(m *api.Message) (cmd, args string, ok bool) { + if len(m.Entities) == 0 || m.Text == "" { + return "", "", false + } + first := m.Entities[0] + if first.Type != string(api.EntityBotCommand) || first.Offset != 0 { + return "", "", false + } + cmd, sliceOk := utf16Slice(m.Text, int(first.Offset), int(first.Length)) + if !sliceOk { + return "", "", false + } + if i := strings.Index(cmd, "@"); i >= 0 { + cmd = cmd[:i] + } + end := int(first.Offset) + int(first.Length) + rest, _ := utf16Slice(m.Text, end, utf16Len(m.Text)-end) + args = strings.TrimSpace(rest) + return cmd, args, true +} + +// utf16Slice returns the substring of s identified by a UTF-16 offset/length +// pair, as Telegram's MessageEntity uses. ok is false if the indices fall +// outside s's UTF-16 length. +func utf16Slice(s string, offset, length int) (string, bool) { + runes := []rune(s) + var startBytes, endBytes int + var u16 int + found := false + for i, r := range runes { + if u16 == offset { + startBytes = byteIndex(runes, i) + found = true + } + if u16 == offset+length { + endBytes = byteIndex(runes, i) + return s[startBytes:endBytes], true + } + if r > 0xFFFF { + u16 += 2 + } else { + u16++ + } + } + if found && u16 == offset+length { + return s[startBytes:], true + } + return "", false +} + +func byteIndex(runes []rune, runeIdx int) int { + n := 0 + for i := 0; i < runeIdx; i++ { + n += utf8.RuneLen(runes[i]) + } + return n +} + +func utf16Len(s string) int { + n := 0 + for _, r := range s { + if r > 0xFFFF { + n += 2 + } else { + n++ + } + } + return n +} diff --git a/dispatch/router_test.go b/dispatch/router_test.go new file mode 100644 index 0000000..5414004 --- /dev/null +++ b/dispatch/router_test.go @@ -0,0 +1,940 @@ +package dispatch + +import ( + "context" + "sync/atomic" + "testing" + "time" + + "github.com/lukaszraczylo/go-telegram/api" + "github.com/lukaszraczylo/go-telegram/client" + "github.com/stretchr/testify/require" +) + +// fakeUpdater feeds a fixed slice of updates then closes. +type fakeUpdater struct{ ch chan api.Update } + +func newFake(ups ...api.Update) *fakeUpdater { + ch := make(chan api.Update, len(ups)) + for _, u := range ups { + ch <- u + } + close(ch) + return &fakeUpdater{ch: ch} +} + +func (f *fakeUpdater) Updates() <-chan api.Update { return f.ch } +func (f *fakeUpdater) Run(ctx context.Context) error { <-ctx.Done(); return ctx.Err() } +func (f *fakeUpdater) Stop(ctx context.Context) error { return nil } + +func cmdMessage(text string) api.Update { + return api.Update{ + UpdateID: 1, + Message: &api.Message{ + MessageID: 1, Date: 0, Chat: api.Chat{ID: 1, Type: string(api.ChatTypePrivate)}, + Text: text, + Entities: []api.MessageEntity{{Type: string(api.EntityBotCommand), Offset: 0, Length: int64(indexEnd(text))}}, + }, + } +} + +func indexEnd(text string) int { + for i, r := range text { + if r == ' ' { + return i + } + } + return len(text) +} + +func TestRouter_OnCommandMatches(t *testing.T) { + b := client.New("t") + r := New(b) + hit := make(chan string, 1) + r.OnCommand("/start", func(c *Context, m *api.Message) error { + hit <- c.Values["command"].(string) + return nil + }) + + ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) + defer cancel() + go func() { _ = r.Run(ctx, newFake(cmdMessage("/start"))) }() + + require.Equal(t, "/start", <-hit) +} + +func TestRouter_OnCommandStripsBotName(t *testing.T) { + r := New(client.New("t")) + hit := make(chan string, 1) + r.OnCommand("/start", func(c *Context, m *api.Message) error { + hit <- "matched" + return nil + }) + + ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) + defer cancel() + go func() { _ = r.Run(ctx, newFake(cmdMessage("/start@MyBot hello"))) }() + + require.Equal(t, "matched", <-hit) +} + +func TestRouter_OnText(t *testing.T) { + r := New(client.New("t")) + hit := make(chan []string, 1) + r.OnText(`^hello (\w+)$`, func(c *Context, m *api.Message) error { + hit <- c.Values["regex_match"].([]string) + return nil + }) + + u := api.Update{UpdateID: 1, Message: &api.Message{ + MessageID: 1, Chat: api.Chat{ID: 1, Type: "private"}, Text: "hello world", + }} + ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) + defer cancel() + go func() { _ = r.Run(ctx, newFake(u)) }() + + subs := <-hit + require.Equal(t, "world", subs[1]) +} + +func TestRouter_OnCallback(t *testing.T) { + r := New(client.New("t")) + hit := make(chan string, 1) + r.OnCallback(`^like:(\d+)$`, func(c *Context, q *api.CallbackQuery) error { + hit <- q.Data + return nil + }) + + u := api.Update{UpdateID: 1, CallbackQuery: &api.CallbackQuery{ + ID: "x", From: api.User{ID: 1}, ChatInstance: "y", Data: "like:42", + }} + ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) + defer cancel() + go func() { _ = r.Run(ctx, newFake(u)) }() + + require.Equal(t, "like:42", <-hit) +} + +func TestRouter_NoMatch(t *testing.T) { + r := New(client.New("t")) + called := false + r.OnCommand("/start", func(c *Context, m *api.Message) error { + called = true + return nil + }) + u := api.Update{UpdateID: 1, Message: &api.Message{Text: "no command"}} + + ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) + defer cancel() + _ = r.Run(ctx, newFake(u)) + require.False(t, called) +} + +func TestRouter_PanicRecovery(t *testing.T) { + r := New(client.New("t")) + r.OnCommand("/boom", func(c *Context, m *api.Message) error { + panic("kaboom") + }) + + ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) + defer cancel() + // Should not propagate panic to Run. + require.NotPanics(t, func() { _ = r.Run(ctx, newFake(cmdMessage("/boom"))) }) +} + +// TestRouter_NonASCIICommand verifies that UTF-16 entity offsets are used +// correctly when the command contains non-ASCII runes. "/старт" is 6 runes, +// each a BMP code point, so UTF-16 length == 6. +func TestRouter_NonASCIICommand(t *testing.T) { + const text = "/старт аргумент" + // "/старт" = 1 + 5 runes, all BMP → UTF-16 length 6 + const cmdU16Len = int64(6) + u := api.Update{ + UpdateID: 1, + Message: &api.Message{ + MessageID: 1, + Chat: api.Chat{ID: 1, Type: string(api.ChatTypePrivate)}, + Text: text, + Entities: []api.MessageEntity{ + {Type: string(api.EntityBotCommand), Offset: 0, Length: cmdU16Len}, + }, + }, + } + + r := New(client.New("t")) + hit := make(chan [2]string, 1) + r.OnCommand("/старт", func(c *Context, m *api.Message) error { + hit <- [2]string{ + c.Values["command"].(string), + c.Values["command_args"].(string), + } + return nil + }) + + ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) + defer cancel() + go func() { _ = r.Run(ctx, newFake(u)) }() + + got := <-hit + require.Equal(t, "/старт", got[0]) + require.Equal(t, "аргумент", got[1]) +} + +// TestRouter_CommandValuesNotLeakedOnNoMatch verifies that c.Values["command"] +// is not set when a command entity is present but no route matches, so a +// subsequent text handler doesn't see stale values. +func TestRouter_CommandValuesNotLeakedOnNoMatch(t *testing.T) { + r := New(client.New("t")) + // Register a text handler that should fire as fallback. + leaked := make(chan bool, 1) + r.OnText(`.*`, func(c *Context, m *api.Message) error { + _, hasCmd := c.Values["command"] + leaked <- hasCmd + return nil + }) + // No OnCommand registered, so the command entity won't match any route. + u := api.Update{UpdateID: 1, Message: &api.Message{ + MessageID: 1, Chat: api.Chat{ID: 1, Type: "private"}, + Text: "/unknown", + Entities: []api.MessageEntity{{Type: string(api.EntityBotCommand), Offset: 0, Length: 8}}, + }} + + ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) + defer cancel() + go func() { _ = r.Run(ctx, newFake(u)) }() + + require.False(t, <-leaked, "command value must not leak into text handler") +} + +func TestRouter_MiddlewareOrder(t *testing.T) { + r := New(client.New("t")) + var order []string + r.Use(func(next Handler[*api.Update]) Handler[*api.Update] { + return func(c *Context, u *api.Update) error { + order = append(order, "before-1") + err := next(c, u) + order = append(order, "after-1") + return err + } + }) + r.Use(func(next Handler[*api.Update]) Handler[*api.Update] { + return func(c *Context, u *api.Update) error { + order = append(order, "before-2") + err := next(c, u) + order = append(order, "after-2") + return err + } + }) + r.OnCommand("/x", func(c *Context, m *api.Message) error { + order = append(order, "handler") + return nil + }) + + ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) + defer cancel() + _ = r.Run(ctx, newFake(cmdMessage("/x"))) + + require.Equal(t, + []string{"before-1", "before-2", "handler", "after-2", "after-1"}, + order) +} +func TestRouter_OnChannelPost(t *testing.T) { + r := New(client.New("t")) + hit := make(chan int64, 1) + r.OnChannelPost(func(c *Context, m *api.Message) error { + hit <- m.MessageID + return nil + }) + + u := api.Update{UpdateID: 1, ChannelPost: &api.Message{ + MessageID: 99, Chat: api.Chat{ID: -100, Type: string(api.ChatTypeChannel)}, + }} + ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) + defer cancel() + go func() { _ = r.Run(ctx, newFake(u)) }() + + require.Equal(t, int64(99), <-hit) +} + +func TestRouter_RunsAllHandlersForEditedMessage(t *testing.T) { + r := New(client.New("t")) + var hits []string + r.OnEditedMessage(func(c *Context, m *api.Message) error { + hits = append(hits, "first") + return nil + }) + r.OnEditedMessage(func(c *Context, m *api.Message) error { + hits = append(hits, "second") + return nil + }) + + u := api.Update{UpdateID: 1, EditedMessage: &api.Message{ + MessageID: 1, Chat: api.Chat{ID: 1, Type: "private"}, Text: "edited", + }} + ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) + defer cancel() + _ = r.Run(ctx, newFake(u)) + + require.Equal(t, []string{"first", "second"}, hits) +} + +// --------------------------------------------------------------------------- +// Filter-route tests +// --------------------------------------------------------------------------- + +func TestRouter_OnMessageFilter_Matches(t *testing.T) { + r := New(client.New("t")) + hit := make(chan string, 1) + r.OnMessageFilter( + Filter[*api.Message](func(m *api.Message) bool { return m != nil && m.Text == "ping" }), + func(c *Context, m *api.Message) error { hit <- m.Text; return nil }, + ) + + u := api.Update{UpdateID: 1, Message: &api.Message{ + MessageID: 1, Chat: api.Chat{ID: 1, Type: "private"}, Text: "ping", + }} + ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) + defer cancel() + go func() { _ = r.Run(ctx, newFake(u)) }() + + require.Equal(t, "ping", <-hit) +} + +func TestRouter_OnMessageFilter_NoMatch(t *testing.T) { + r := New(client.New("t")) + called := false + r.OnMessageFilter( + Filter[*api.Message](func(m *api.Message) bool { return false }), + func(c *Context, m *api.Message) error { called = true; return nil }, + ) + + u := api.Update{UpdateID: 1, Message: &api.Message{ + MessageID: 1, Chat: api.Chat{ID: 1, Type: "private"}, Text: "any", + }} + ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) + defer cancel() + _ = r.Run(ctx, newFake(u)) + require.False(t, called) +} + +// Command routes must take priority over filter routes. +func TestRouter_OnMessageFilter_CommandWins(t *testing.T) { + r := New(client.New("t")) + var winner string + r.OnCommand("/start", func(c *Context, m *api.Message) error { winner = "command"; return nil }) + r.OnMessageFilter( + Filter[*api.Message](func(m *api.Message) bool { return true }), + func(c *Context, m *api.Message) error { winner = "filter"; return nil }, + ) + + ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) + defer cancel() + _ = r.Run(ctx, newFake(cmdMessage("/start"))) + + require.Equal(t, "command", winner) +} + +func TestRouter_OnCallbackFilter_Matches(t *testing.T) { + r := New(client.New("t")) + hit := make(chan string, 1) + r.OnCallbackFilter( + Filter[*api.CallbackQuery](func(q *api.CallbackQuery) bool { return q != nil && q.Data == "yes" }), + func(c *Context, q *api.CallbackQuery) error { hit <- q.Data; return nil }, + ) + + u := api.Update{UpdateID: 1, CallbackQuery: &api.CallbackQuery{ + ID: "x", From: api.User{ID: 1}, ChatInstance: "y", Data: "yes", + }} + ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) + defer cancel() + go func() { _ = r.Run(ctx, newFake(u)) }() + + require.Equal(t, "yes", <-hit) +} + +// Pattern-based OnCallback wins over OnCallbackFilter when both match. +func TestRouter_OnCallbackFilter_PatternWins(t *testing.T) { + r := New(client.New("t")) + var winner string + r.OnCallback(`^yes$`, func(c *Context, q *api.CallbackQuery) error { winner = "pattern"; return nil }) + r.OnCallbackFilter( + Filter[*api.CallbackQuery](func(q *api.CallbackQuery) bool { return true }), + func(c *Context, q *api.CallbackQuery) error { winner = "filter"; return nil }, + ) + + u := api.Update{UpdateID: 1, CallbackQuery: &api.CallbackQuery{ + ID: "x", From: api.User{ID: 1}, ChatInstance: "y", Data: "yes", + }} + ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) + defer cancel() + _ = r.Run(ctx, newFake(u)) + + require.Equal(t, "pattern", winner) +} + +func TestRouter_OnInlineQueryFilter_Matches(t *testing.T) { + r := New(client.New("t")) + hit := make(chan string, 1) + r.OnInlineQueryFilter( + Filter[*api.InlineQuery](func(q *api.InlineQuery) bool { return q != nil && q.Query == "find" }), + func(c *Context, q *api.InlineQuery) error { hit <- q.Query; return nil }, + ) + + u := api.Update{UpdateID: 1, InlineQuery: &api.InlineQuery{ + ID: "i", From: api.User{ID: 1}, Query: "find", + }} + ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) + defer cancel() + go func() { _ = r.Run(ctx, newFake(u)) }() + + require.Equal(t, "find", <-hit) +} + +func TestRouter_FilterChain_Composition(t *testing.T) { + // Filter: private chat AND text contains "hello" + privateChat := Filter[*api.Message](func(m *api.Message) bool { + return m != nil && m.Chat.Type == string(api.ChatTypePrivate) + }) + hasHello := Filter[*api.Message](func(m *api.Message) bool { + return m != nil && len(m.Text) > 0 && containsStr(m.Text, "hello") + }) + combined := privateChat.And(hasHello) + + r := New(client.New("t")) + hit := make(chan string, 1) + r.OnMessageFilter(combined, func(c *Context, m *api.Message) error { hit <- m.Text; return nil }) + + match := api.Update{UpdateID: 1, Message: &api.Message{ + MessageID: 1, Chat: api.Chat{ID: 1, Type: string(api.ChatTypePrivate)}, Text: "say hello", + }} + noMatch := api.Update{UpdateID: 2, Message: &api.Message{ + MessageID: 2, Chat: api.Chat{ID: 2, Type: string(api.ChatTypeGroup)}, Text: "say hello", + }} + + ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) + defer cancel() + go func() { _ = r.Run(ctx, newFake(match, noMatch)) }() + + require.Equal(t, "say hello", <-hit) +} + +// containsStr is a helper to avoid importing strings in test file unnecessarily. +func containsStr(s, sub string) bool { + return len(s) >= len(sub) && (s == sub || len(s) > 0 && containsSubstr(s, sub)) +} + +func containsSubstr(s, sub string) bool { + for i := 0; i <= len(s)-len(sub); i++ { + if s[i:i+len(sub)] == sub { + return true + } + } + return false +} + +// --------------------------------------------------------------------------- +// Concurrent dispatch tests +// --------------------------------------------------------------------------- + +// fakeSlowUpdater feeds n updates then blocks until ctx cancel. +type fakeSlowUpdater struct { + ch chan api.Update +} + +func newSlowFake(ups ...api.Update) *fakeSlowUpdater { + ch := make(chan api.Update, len(ups)) + for _, u := range ups { + ch <- u + } + close(ch) + return &fakeSlowUpdater{ch: ch} +} + +func (f *fakeSlowUpdater) Updates() <-chan api.Update { return f.ch } +func (f *fakeSlowUpdater) Run(ctx context.Context) error { <-ctx.Done(); return ctx.Err() } +func (f *fakeSlowUpdater) Stop(ctx context.Context) error { return nil } + +func TestRouter_ConcurrentDispatch_AllHandlersFire(t *testing.T) { + const n = 100 + var fired atomic.Int64 + + ups := make([]api.Update, n) + for i := range ups { + ups[i] = api.Update{UpdateID: int64(i + 1), Message: &api.Message{ + MessageID: int64(i + 1), + Chat: api.Chat{ID: 1, Type: string(api.ChatTypePrivate)}, + Text: "hi", + }} + } + + r := New(client.New("t"), WithMaxConcurrency(20)) + r.OnMessageFilter( + Filter[*api.Message](func(m *api.Message) bool { return true }), + func(c *Context, m *api.Message) error { fired.Add(1); return nil }, + ) + + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + _ = r.Run(ctx, newSlowFake(ups...)) + + require.Equal(t, int64(n), fired.Load()) +} + +func TestRouter_ConcurrentDispatch_SemaphoreBoundsConcurrency(t *testing.T) { + const limit = 5 + const n = 30 + + var inFlight atomic.Int64 + var maxSeen atomic.Int64 + ready := make(chan struct{}) // signals handler to proceed + started := make(chan struct{}) // first handler signals it's running + + ups := make([]api.Update, n) + for i := range ups { + ups[i] = api.Update{UpdateID: int64(i + 1), Message: &api.Message{ + MessageID: int64(i + 1), + Chat: api.Chat{ID: 1, Type: string(api.ChatTypePrivate)}, + Text: "hi", + }} + } + + once := atomic.Bool{} + r := New(client.New("t"), WithMaxConcurrency(limit)) + r.OnMessageFilter( + Filter[*api.Message](func(m *api.Message) bool { return true }), + func(c *Context, m *api.Message) error { + cur := inFlight.Add(1) + for { + old := maxSeen.Load() + if cur <= old || maxSeen.CompareAndSwap(old, cur) { + break + } + } + if once.CompareAndSwap(false, true) { + close(started) + } + <-ready + inFlight.Add(-1) + return nil + }, + ) + + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + + go func() { _ = r.Run(ctx, newSlowFake(ups...)) }() + + select { + case <-started: + case <-ctx.Done(): + t.Fatal("timed out waiting for first handler") + } + // Give the pool a moment to fill up. + time.Sleep(50 * time.Millisecond) + close(ready) + + // Wait for Run to drain by cancelling context after a short wait. + time.Sleep(200 * time.Millisecond) + cancel() + + require.LessOrEqual(t, maxSeen.Load(), int64(limit), + "in-flight goroutines exceeded semaphore limit") +} + +func TestRouter_ConcurrentDispatch_WaitsForInFlight(t *testing.T) { + unblock := make(chan struct{}) + done := make(chan struct{}) + + r := New(client.New("t"), WithMaxConcurrency(10)) + r.OnMessageFilter( + Filter[*api.Message](func(m *api.Message) bool { return true }), + func(c *Context, m *api.Message) error { + <-unblock + return nil + }, + ) + + u := api.Update{UpdateID: 1, Message: &api.Message{ + MessageID: 1, Chat: api.Chat{ID: 1, Type: string(api.ChatTypePrivate)}, Text: "hi", + }} + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + + go func() { + _ = r.Run(ctx, newSlowFake(u)) + close(done) + }() + + // Give Run time to pick up the update and launch the goroutine. + time.Sleep(30 * time.Millisecond) + cancel() // trigger Run to exit its loop + + // Run should not return until handler unblocks. + select { + case <-done: + t.Fatal("Run returned before in-flight handler finished") + case <-time.After(50 * time.Millisecond): + } + + close(unblock) + + select { + case <-done: + case <-time.After(2 * time.Second): + t.Fatal("Run did not return after handler finished") + } +} + +func TestRouter_SerialMode_NoRace(t *testing.T) { + // WithMaxConcurrency(0) — serial; shared slice is safe without a mutex. + var order []int64 + + const n = 20 + ups := make([]api.Update, n) + for i := range ups { + ups[i] = api.Update{UpdateID: int64(i + 1), Message: &api.Message{ + MessageID: int64(i + 1), + Chat: api.Chat{ID: 1, Type: string(api.ChatTypePrivate)}, + Text: "hi", + }} + } + + r := New(client.New("t"), WithMaxConcurrency(0)) + r.OnMessageFilter( + Filter[*api.Message](func(m *api.Message) bool { return true }), + func(c *Context, m *api.Message) error { + order = append(order, m.MessageID) + return nil + }, + ) + + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + _ = r.Run(ctx, newSlowFake(ups...)) + + require.Len(t, order, n) + for i, v := range order { + require.Equal(t, int64(i+1), v) + } +} + +// liveUpdater is an updater whose channel stays open until stopCh is closed. +type liveUpdater struct { + ch chan api.Update + stopCh chan struct{} +} + +func newLiveUpdater() *liveUpdater { + return &liveUpdater{ch: make(chan api.Update, 8), stopCh: make(chan struct{})} +} + +func (l *liveUpdater) Send(u api.Update) { l.ch <- u } +func (l *liveUpdater) Close() { close(l.stopCh) } +func (l *liveUpdater) Updates() <-chan api.Update { return l.ch } +func (l *liveUpdater) Stop(ctx context.Context) error { return nil } +func (l *liveUpdater) Run(ctx context.Context) error { + select { + case <-ctx.Done(): + return ctx.Err() + case <-l.stopCh: + return nil + } +} + +// --------------------------------------------------------------------------- +// Typed handler tests (Feature 1) +// --------------------------------------------------------------------------- + +func TestRouter_OnMyChatMember(t *testing.T) { + r := New(client.New("t")) + hit := make(chan int64, 1) + r.OnMyChatMember(func(c *Context, u *api.ChatMemberUpdated) error { hit <- u.From.ID; return nil }) + + upd := api.Update{UpdateID: 1, MyChatMember: &api.ChatMemberUpdated{ + From: api.User{ID: 42}, + Chat: api.Chat{ID: 1}, + }} + ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) + defer cancel() + go func() { _ = r.Run(ctx, newFake(upd)) }() + require.Equal(t, int64(42), <-hit) +} + +func TestRouter_OnMyChatMemberFilter(t *testing.T) { + r := New(client.New("t")) + hit := make(chan int64, 1) + f := Filter[*api.ChatMemberUpdated](func(u *api.ChatMemberUpdated) bool { return u.From.ID == 99 }) + r.OnMyChatMemberFilter(f, func(c *Context, u *api.ChatMemberUpdated) error { hit <- u.From.ID; return nil }) + + match := api.Update{UpdateID: 1, MyChatMember: &api.ChatMemberUpdated{From: api.User{ID: 99}}} + noMatch := api.Update{UpdateID: 2, MyChatMember: &api.ChatMemberUpdated{From: api.User{ID: 1}}} + + ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) + defer cancel() + go func() { _ = r.Run(ctx, newFake(noMatch, match)) }() + require.Equal(t, int64(99), <-hit) +} + +func TestRouter_OnChatMember(t *testing.T) { + r := New(client.New("t")) + hit := make(chan int64, 1) + r.OnChatMember(func(c *Context, u *api.ChatMemberUpdated) error { hit <- u.Chat.ID; return nil }) + + upd := api.Update{UpdateID: 1, ChatMember: &api.ChatMemberUpdated{ + From: api.User{ID: 1}, + Chat: api.Chat{ID: 77}, + }} + ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) + defer cancel() + go func() { _ = r.Run(ctx, newFake(upd)) }() + require.Equal(t, int64(77), <-hit) +} + +func TestRouter_OnChatMemberFilter(t *testing.T) { + r := New(client.New("t")) + hit := make(chan int64, 1) + f := Filter[*api.ChatMemberUpdated](func(u *api.ChatMemberUpdated) bool { return u.Chat.ID == 55 }) + r.OnChatMemberFilter(f, func(c *Context, u *api.ChatMemberUpdated) error { hit <- u.Chat.ID; return nil }) + + upd := api.Update{UpdateID: 1, ChatMember: &api.ChatMemberUpdated{Chat: api.Chat{ID: 55}}} + ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) + defer cancel() + go func() { _ = r.Run(ctx, newFake(upd)) }() + require.Equal(t, int64(55), <-hit) +} + +func TestRouter_OnChatJoinRequest(t *testing.T) { + r := New(client.New("t")) + hit := make(chan int64, 1) + r.OnChatJoinRequest(func(c *Context, req *api.ChatJoinRequest) error { hit <- req.From.ID; return nil }) + + upd := api.Update{UpdateID: 1, ChatJoinRequest: &api.ChatJoinRequest{ + From: api.User{ID: 11}, + Chat: api.Chat{ID: 1}, + }} + ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) + defer cancel() + go func() { _ = r.Run(ctx, newFake(upd)) }() + require.Equal(t, int64(11), <-hit) +} + +func TestRouter_OnChatJoinRequestFilter(t *testing.T) { + r := New(client.New("t")) + hit := make(chan int64, 1) + f := Filter[*api.ChatJoinRequest](func(req *api.ChatJoinRequest) bool { return req.Chat.ID == 22 }) + r.OnChatJoinRequestFilter(f, func(c *Context, req *api.ChatJoinRequest) error { hit <- req.Chat.ID; return nil }) + + upd := api.Update{UpdateID: 1, ChatJoinRequest: &api.ChatJoinRequest{ + From: api.User{ID: 1}, + Chat: api.Chat{ID: 22}, + }} + ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) + defer cancel() + go func() { _ = r.Run(ctx, newFake(upd)) }() + require.Equal(t, int64(22), <-hit) +} + +func TestRouter_OnPreCheckoutQuery(t *testing.T) { + r := New(client.New("t")) + hit := make(chan string, 1) + r.OnPreCheckoutQuery(func(c *Context, q *api.PreCheckoutQuery) error { hit <- q.Currency; return nil }) + + upd := api.Update{UpdateID: 1, PreCheckoutQuery: &api.PreCheckoutQuery{ + ID: "q1", From: api.User{ID: 1}, Currency: "USD", + }} + ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) + defer cancel() + go func() { _ = r.Run(ctx, newFake(upd)) }() + require.Equal(t, "USD", <-hit) +} + +func TestRouter_OnPreCheckoutQueryFilter(t *testing.T) { + r := New(client.New("t")) + hit := make(chan string, 1) + f := Filter[*api.PreCheckoutQuery](func(q *api.PreCheckoutQuery) bool { return q.Currency == "EUR" }) + r.OnPreCheckoutQueryFilter(f, func(c *Context, q *api.PreCheckoutQuery) error { hit <- q.Currency; return nil }) + + upd := api.Update{UpdateID: 1, PreCheckoutQuery: &api.PreCheckoutQuery{ + ID: "q1", From: api.User{ID: 1}, Currency: "EUR", + }} + ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) + defer cancel() + go func() { _ = r.Run(ctx, newFake(upd)) }() + require.Equal(t, "EUR", <-hit) +} + +func TestRouter_OnShippingQuery(t *testing.T) { + r := New(client.New("t")) + hit := make(chan string, 1) + r.OnShippingQuery(func(c *Context, q *api.ShippingQuery) error { hit <- q.ID; return nil }) + + upd := api.Update{UpdateID: 1, ShippingQuery: &api.ShippingQuery{ID: "sq1", From: api.User{ID: 1}}} + ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) + defer cancel() + go func() { _ = r.Run(ctx, newFake(upd)) }() + require.Equal(t, "sq1", <-hit) +} + +func TestRouter_OnPoll(t *testing.T) { + r := New(client.New("t")) + hit := make(chan string, 1) + r.OnPoll(func(c *Context, p *api.Poll) error { hit <- p.ID; return nil }) + + upd := api.Update{UpdateID: 1, Poll: &api.Poll{ID: "poll1"}} + ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) + defer cancel() + go func() { _ = r.Run(ctx, newFake(upd)) }() + require.Equal(t, "poll1", <-hit) +} + +func TestRouter_OnPollAnswer(t *testing.T) { + r := New(client.New("t")) + hit := make(chan string, 1) + r.OnPollAnswer(func(c *Context, a *api.PollAnswer) error { hit <- a.PollID; return nil }) + + upd := api.Update{UpdateID: 1, PollAnswer: &api.PollAnswer{PollID: "p1", OptionIds: []int64{0}}} + ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) + defer cancel() + go func() { _ = r.Run(ctx, newFake(upd)) }() + require.Equal(t, "p1", <-hit) +} + +func TestRouter_OnChosenInlineResult(t *testing.T) { + r := New(client.New("t")) + hit := make(chan string, 1) + r.OnChosenInlineResult(func(c *Context, res *api.ChosenInlineResult) error { hit <- res.ResultID; return nil }) + + upd := api.Update{UpdateID: 1, ChosenInlineResult: &api.ChosenInlineResult{ResultID: "r1", From: api.User{ID: 1}}} + ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) + defer cancel() + go func() { _ = r.Run(ctx, newFake(upd)) }() + require.Equal(t, "r1", <-hit) +} + +func TestRouter_OnMessageReaction(t *testing.T) { + r := New(client.New("t")) + hit := make(chan int64, 1) + r.OnMessageReaction(func(c *Context, u *api.MessageReactionUpdated) error { hit <- u.Chat.ID; return nil }) + + upd := api.Update{UpdateID: 1, MessageReaction: &api.MessageReactionUpdated{Chat: api.Chat{ID: 33}}} + ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) + defer cancel() + go func() { _ = r.Run(ctx, newFake(upd)) }() + require.Equal(t, int64(33), <-hit) +} + +func TestRouter_OnMessageReactionCount(t *testing.T) { + r := New(client.New("t")) + hit := make(chan int64, 1) + r.OnMessageReactionCount(func(c *Context, u *api.MessageReactionCountUpdated) error { hit <- u.Chat.ID; return nil }) + + upd := api.Update{UpdateID: 1, MessageReactionCount: &api.MessageReactionCountUpdated{Chat: api.Chat{ID: 44}}} + ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) + defer cancel() + go func() { _ = r.Run(ctx, newFake(upd)) }() + require.Equal(t, int64(44), <-hit) +} + +func TestRouter_OnChatBoost(t *testing.T) { + r := New(client.New("t")) + hit := make(chan int64, 1) + r.OnChatBoost(func(c *Context, u *api.ChatBoostUpdated) error { hit <- u.Chat.ID; return nil }) + + upd := api.Update{UpdateID: 1, ChatBoost: &api.ChatBoostUpdated{Chat: api.Chat{ID: 55}}} + ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) + defer cancel() + go func() { _ = r.Run(ctx, newFake(upd)) }() + require.Equal(t, int64(55), <-hit) +} + +func TestRouter_OnRemovedChatBoost(t *testing.T) { + r := New(client.New("t")) + hit := make(chan int64, 1) + r.OnRemovedChatBoost(func(c *Context, u *api.ChatBoostRemoved) error { hit <- u.Chat.ID; return nil }) + + upd := api.Update{UpdateID: 1, RemovedChatBoost: &api.ChatBoostRemoved{Chat: api.Chat{ID: 66}}} + ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) + defer cancel() + go func() { _ = r.Run(ctx, newFake(upd)) }() + require.Equal(t, int64(66), <-hit) +} + +func TestRouter_OnBusinessConnection(t *testing.T) { + r := New(client.New("t")) + hit := make(chan string, 1) + r.OnBusinessConnection(func(c *Context, bc *api.BusinessConnection) error { hit <- bc.ID; return nil }) + + upd := api.Update{UpdateID: 1, BusinessConnection: &api.BusinessConnection{ID: "bc1", UserChatID: 1, User: api.User{ID: 1}}} + ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) + defer cancel() + go func() { _ = r.Run(ctx, newFake(upd)) }() + require.Equal(t, "bc1", <-hit) +} + +func TestRouter_OnPurchasedPaidMedia(t *testing.T) { + r := New(client.New("t")) + hit := make(chan string, 1) + r.OnPurchasedPaidMedia(func(c *Context, p *api.PaidMediaPurchased) error { hit <- p.PaidMediaPayload; return nil }) + + upd := api.Update{UpdateID: 1, PurchasedPaidMedia: &api.PaidMediaPurchased{From: api.User{ID: 1}, PaidMediaPayload: "payload1"}} + ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) + defer cancel() + go func() { _ = r.Run(ctx, newFake(upd)) }() + require.Equal(t, "payload1", <-hit) +} + +func TestRouter_ContextCancel_UnblocksWaitingAcquire(t *testing.T) { + // Fill the semaphore with slow handlers, send one more update, then cancel + // ctx. Run must unblock from the semaphore-acquire select and return. + const limit = 2 + unblock := make(chan struct{}) + + slowHandler := func(c *Context, m *api.Message) error { + <-unblock + return nil + } + + lu := newLiveUpdater() + r := New(client.New("t"), WithMaxConcurrency(limit)) + r.OnMessageFilter(Filter[*api.Message](func(m *api.Message) bool { return true }), slowHandler) + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + runDone := make(chan error, 1) + go func() { runDone <- r.Run(ctx, lu) }() + + // Send enough updates to fill semaphore. + for i := range limit { + lu.Send(api.Update{UpdateID: int64(i + 1), Message: &api.Message{ + MessageID: int64(i + 1), + Chat: api.Chat{ID: 1, Type: string(api.ChatTypePrivate)}, + Text: "hi", + }}) + } + + // Give goroutines time to acquire all semaphore slots. + time.Sleep(50 * time.Millisecond) + + // Send one more update — Run will block trying to acquire the full semaphore. + lu.Send(api.Update{UpdateID: int64(limit + 1), Message: &api.Message{ + MessageID: int64(limit + 1), + Chat: api.Chat{ID: 1, Type: string(api.ChatTypePrivate)}, + Text: "extra", + }}) + + // Give Run a moment to reach the semaphore-acquire select. + time.Sleep(30 * time.Millisecond) + cancel() + + // Unblock handlers so wg.Wait() inside Run can complete, allowing Run to + // return (and write to runDone). + close(unblock) + + select { + case err := <-runDone: + require.Error(t, err) + case <-time.After(2 * time.Second): + t.Fatal("Run did not unblock after context cancel") + } +} diff --git a/doc.go b/doc.go new file mode 100644 index 0000000..254e7db --- /dev/null +++ b/doc.go @@ -0,0 +1,5 @@ +// Package gotelegram is the module root. +// +// The public API lives in the api, client, transport, and dispatch packages. +// See https://github.com/lukaszraczylo/go-telegram for documentation. +package gotelegram diff --git a/examples/README.md b/examples/README.md new file mode 100644 index 0000000..0e1228f --- /dev/null +++ b/examples/README.md @@ -0,0 +1,39 @@ +# Examples + +Each subdirectory contains a self-contained sample bot demonstrating one feature area. + +| Example | What it shows | +|---|---| +| [echo](./echo) | Long-poll bot that echoes text back to the sender | +| [webhook](./webhook) | Webhook delivery with secret-token verification | +| [callback](./callback) | Inline keyboard with callback queries and counter state | +| [conversation](./conversation) | Multi-step conversation flow with `dispatch/conversation` | +| [files](./files) | Upload and download files via `api.DownloadFile` | +| [inline](./inline) | Inline-mode bot returning search-style results | +| [middleware](./middleware) | Custom middleware chains via `Router.Use` | +| [stateful](./stateful) | Per-user state managed via closures | +| [welcome](./welcome) | Greet new chat members; detect and log departures | +| [moderation](./moderation) | `/kick`, `/ban`, `/mute`, `/warn` with admin permission checks | +| [polls](./polls) | Create polls and tally answers via `OnPollAnswer` | +| [payments](./payments) | Telegram Payments: sendInvoice → pre_checkout_query → successful_payment | +| [pagination](./pagination) | Multi-page inline keyboard with stateless prev/next navigation | +| [admin](./admin) | Auth middleware allowlisting specific user IDs via `Router.Use` | + +## Running + +All examples follow the same pattern: + +```bash +export TELEGRAM_BOT_TOKEN=123456:ABC... +go run ./examples/ +``` + +Webhook examples need a public HTTPS endpoint (use Cloudflare Tunnel, ngrok, or similar). + +## Common patterns + +**Retry-safe HTTP** — every example wraps the HTTP client with `client.NewRetryDoer`, which automatically honours Telegram's `retry_after` field on 429 responses. + +**Graceful shutdown** — all examples use `signal.NotifyContext` so the bot drains cleanly on `SIGINT`/`SIGTERM`. + +**Structured logging** — for production, wire a logger via `client.WithLogger` and wrap the process in supervision (systemd unit, k8s liveness probe, etc.). diff --git a/examples/admin/README.md b/examples/admin/README.md new file mode 100644 index 0000000..ac07279 --- /dev/null +++ b/examples/admin/README.md @@ -0,0 +1,40 @@ +# admin + +Authentication middleware that restricts the bot to an allowlist of Telegram user IDs. + +## What it shows + +- `router.Use(...)` to install a global `Middleware[*api.Update]` +- Parsing `ALLOWED_USERS` env var into a `map[int64]bool` lookup set +- Extracting sender ID from multiple update types in one helper +- Silent drop pattern for unauthorized updates (no error, no reply) + +## Environment variables + +| Variable | Required | Description | +|---|---|---| +| `TELEGRAM_BOT_TOKEN` | Yes | Bot token from @BotFather | +| `ALLOWED_USERS` | No | Comma-separated numeric user IDs, e.g. `123456,789012`. If unset, all users are permitted. | + +## Finding your user ID + +Send `/whoami` to the bot — it replies with your numeric Telegram user ID. Add that ID to `ALLOWED_USERS` to restrict the bot to you. + +## Extending + +Combine with `examples/moderation` to ensure only group admins can invoke moderation commands: + +```go +router.Use(allowlistMiddleware(adminIDs)) +router.OnCommand("/ban", banHandler) +``` + +For group-context admin checks (verify the sender is an admin of *that specific group*), use `api.GetChatAdministrators` and check the result dynamically rather than a static ID list. + +## Running + +```bash +export TELEGRAM_BOT_TOKEN=123456:ABC... +export ALLOWED_USERS=111111,222222 +go run ./examples/admin +``` diff --git a/examples/admin/main.go b/examples/admin/main.go new file mode 100644 index 0000000..29e52c7 --- /dev/null +++ b/examples/admin/main.go @@ -0,0 +1,127 @@ +// Package main demonstrates auth middleware that restricts the bot to an +// allowlist of Telegram user IDs. +// +// Set ALLOWED_USERS to a comma-separated list of numeric user IDs. +// Messages from all other users are silently dropped. +// +// TELEGRAM_BOT_TOKEN=xxx ALLOWED_USERS=123456,789012 go run ./examples/admin +package main + +import ( + "context" + "log" + "os" + "os/signal" + "strconv" + "strings" + "syscall" + + "github.com/lukaszraczylo/go-telegram/api" + "github.com/lukaszraczylo/go-telegram/client" + "github.com/lukaszraczylo/go-telegram/dispatch" + "github.com/lukaszraczylo/go-telegram/transport" +) + +// parseAllowedIDs parses a comma-separated list of user IDs from an env var. +func parseAllowedIDs(raw string) map[int64]bool { + out := make(map[int64]bool) + for _, part := range strings.Split(raw, ",") { + part = strings.TrimSpace(part) + if part == "" { + continue + } + id, err := strconv.ParseInt(part, 10, 64) + if err != nil { + log.Printf("invalid user ID in ALLOWED_USERS: %q — skipping", part) + continue + } + out[id] = true + } + return out +} + +// extractSenderID returns the Telegram user ID from the most common update types. +func extractSenderID(u *api.Update) int64 { + if u.Message != nil && u.Message.From != nil { + return u.Message.From.ID + } + if u.EditedMessage != nil && u.EditedMessage.From != nil { + return u.EditedMessage.From.ID + } + if u.CallbackQuery != nil && u.CallbackQuery.From.ID != 0 { + return u.CallbackQuery.From.ID + } + if u.InlineQuery != nil { + return u.InlineQuery.From.ID + } + return 0 +} + +// allowlistMiddleware drops updates from users not in the allowlist. +// Passing an empty allowlist (ALLOWED_USERS unset) allows everyone through, +// so this example is safe to run without the env var set. +func allowlistMiddleware(allowed map[int64]bool) dispatch.Middleware[*api.Update] { + return func(next dispatch.Handler[*api.Update]) dispatch.Handler[*api.Update] { + return func(c *dispatch.Context, u *api.Update) error { + if len(allowed) == 0 { + // No allowlist configured — permit all. + return next(c, u) + } + senderID := extractSenderID(u) + if senderID != 0 && !allowed[senderID] { + log.Printf("dropping update from unauthorized user %d", senderID) + return nil // Silent drop. + } + return next(c, u) + } + } +} + +func main() { + token := os.Getenv("TELEGRAM_BOT_TOKEN") + if token == "" { + log.Fatal("TELEGRAM_BOT_TOKEN required") + } + + allowedIDs := parseAllowedIDs(os.Getenv("ALLOWED_USERS")) + if len(allowedIDs) == 0 { + log.Println("ALLOWED_USERS not set — all users permitted (demo mode)") + } else { + log.Printf("allowlist: %d user(s)", len(allowedIDs)) + } + + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + + bot := client.New(token, + client.WithHTTPClient(client.NewRetryDoer(client.NewDefaultHTTPDoer())), + ) + + router := dispatch.New(bot) + router.Use(allowlistMiddleware(allowedIDs)) + + router.OnCommand("/start", func(c *dispatch.Context, m *api.Message) error { + _, err := api.SendMessage(c.Ctx, c.Bot, &api.SendMessageParams{ + ChatID: api.ChatIDFromInt(m.Chat.ID), + Text: "You are authorized.", + }) + return err + }) + + router.OnCommand("/whoami", func(c *dispatch.Context, m *api.Message) error { + from := m.From + if from == nil { + return nil + } + _, err := api.SendMessage(c.Ctx, c.Bot, &api.SendMessageParams{ + ChatID: api.ChatIDFromInt(m.Chat.ID), + Text: "Your user ID is: " + strconv.FormatInt(from.ID, 10), + }) + return err + }) + + poller := transport.NewLongPoller(bot) + if err := router.Run(ctx, poller); err != nil && err != context.Canceled { + log.Printf("router exited: %v", err) + } +} diff --git a/examples/callback/README.md b/examples/callback/README.md new file mode 100644 index 0000000..7d0a176 --- /dev/null +++ b/examples/callback/README.md @@ -0,0 +1,12 @@ +# callback + +Inline keyboard with a counter that updates via callback queries. Demonstrates `OnCallback`, `AnswerCallbackQuery`, and `EditMessageText`. + +## Run + +```bash +export TELEGRAM_BOT_TOKEN=... +go run ./examples/callback +``` + +Send `/start` in a chat with the bot. diff --git a/examples/callback/handlers.go b/examples/callback/handlers.go new file mode 100644 index 0000000..129c047 --- /dev/null +++ b/examples/callback/handlers.go @@ -0,0 +1,75 @@ +package main + +import ( + "context" + "fmt" + "strconv" + + "github.com/lukaszraczylo/go-telegram/api" + "github.com/lukaszraczylo/go-telegram/client" + "github.com/lukaszraczylo/go-telegram/dispatch" +) + +// register wires all handlers onto the router. +func register(r *dispatch.Router) { + r.OnCommand("/start", handleStart) + r.OnCallback(`^count:(-?\d+):(inc|dec)$`, handleCallback) +} + +func handleStart(c *dispatch.Context, m *api.Message) error { + return sendMenu(c.Ctx, c.Bot, m.Chat.ID, 0) +} + +func handleCallback(c *dispatch.Context, q *api.CallbackQuery) error { + groups := c.Values["regex_match"].([]string) + current, _ := strconv.Atoi(groups[1]) + if groups[2] == "inc" { + current++ + } else { + current-- + } + + // Acknowledge the callback (removes the loading spinner). + _, _ = api.AnswerCallbackQuery(c.Ctx, c.Bot, &api.AnswerCallbackQueryParams{ + CallbackQueryID: q.ID, + Text: fmt.Sprintf("counter is now %d", current), + }) + + // Edit the message to reflect the new state. + if q.Message == nil { + return nil + } + msg, ok := q.Message.(*api.Message) + if !ok { + return nil + } + chatID := api.ChatIDFromInt(msg.Chat.ID) + mid := msg.MessageID + _, err := api.EditMessageText(c.Ctx, c.Bot, &api.EditMessageTextParams{ + ChatID: &chatID, + MessageID: &mid, + Text: fmt.Sprintf("Counter: %d", current), + ReplyMarkup: counterKeyboard(current), + }) + return err +} + +func sendMenu(ctx context.Context, bot *client.Bot, chatID int64, value int) error { + _, err := api.SendMessage(ctx, bot, &api.SendMessageParams{ + ChatID: api.ChatIDFromInt(chatID), + Text: fmt.Sprintf("Counter: %d", value), + ReplyMarkup: counterKeyboard(value), + }) + return err +} + +func counterKeyboard(value int) *api.InlineKeyboardMarkup { + return &api.InlineKeyboardMarkup{ + InlineKeyboard: [][]api.InlineKeyboardButton{ + { + {Text: "−", CallbackData: fmt.Sprintf("count:%d:dec", value)}, + {Text: "+", CallbackData: fmt.Sprintf("count:%d:inc", value)}, + }, + }, + } +} diff --git a/examples/callback/handlers_test.go b/examples/callback/handlers_test.go new file mode 100644 index 0000000..9644dc1 --- /dev/null +++ b/examples/callback/handlers_test.go @@ -0,0 +1,146 @@ +package main + +import ( + "bytes" + "context" + "io" + "net/http" + "strings" + "testing" + + "github.com/lukaszraczylo/go-telegram/api" + "github.com/lukaszraczylo/go-telegram/client" + "github.com/lukaszraczylo/go-telegram/dispatch" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" +) + +type mockDoer struct{ mock.Mock } + +func (m *mockDoer) Do(r *http.Request) (*http.Response, error) { + args := m.Called(r) + if v := args.Get(0); v != nil { + return v.(*http.Response), args.Error(1) + } + return nil, args.Error(1) +} + +func okResp(body string) *http.Response { + return &http.Response{ + StatusCode: 200, + Body: io.NopCloser(bytes.NewBufferString(body)), + Header: http.Header{"Content-Type": []string{"application/json"}}, + } +} + +const ( + sendMsgResult = `{"ok":true,"result":{"message_id":1,"date":0,"chat":{"id":42,"type":"private"}}}` + editMsgResult = `{"ok":true,"result":{"message_id":10,"date":0,"chat":{"id":42,"type":"private"}}}` + answerCbResult = `{"ok":true,"result":true}` +) + +func makeCtx(bot *client.Bot, upd *api.Update, extra map[string]any) *dispatch.Context { + c := dispatch.NewContext(context.Background(), bot, upd) + for k, v := range extra { + c.Values[k] = v + } + return c +} + +// --- handleStart --- + +func TestHandleStart_SendsInitialKeyboard(t *testing.T) { + m := &mockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + if !strings.HasSuffix(r.URL.Path, "/sendMessage") { + return false + } + buf := new(bytes.Buffer) + _, _ = buf.ReadFrom(r.Body) + body := buf.String() + // Counter starts at 0; keyboard must contain both buttons + return strings.Contains(body, `"Counter: 0"`) && + strings.Contains(body, `"reply_markup"`) && + strings.Contains(body, `"count:0:dec"`) && + strings.Contains(body, `"count:0:inc"`) + })).Return(okResp(sendMsgResult), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + msg := &api.Message{ + MessageID: 1, + Chat: api.Chat{ID: 42, Type: string(api.ChatTypePrivate)}, + From: &api.User{ID: 7, FirstName: "Alice"}, + Text: "/start", + } + upd := &api.Update{UpdateID: 1, Message: msg} + + require.NoError(t, handleStart(makeCtx(bot, upd, nil), msg)) + m.AssertExpectations(t) +} + +// --- handleCallback --- + +func callbackCtx(bot *client.Bot, q *api.CallbackQuery, groups []string) *dispatch.Context { + upd := &api.Update{UpdateID: 1, CallbackQuery: q} + return makeCtx(bot, upd, map[string]any{"regex_match": groups}) +} + +func callbackQuery(data string, msgID int64, chatID int64) *api.CallbackQuery { + msg := &api.Message{ + MessageID: msgID, + Chat: api.Chat{ID: chatID, Type: string(api.ChatTypePrivate)}, + } + return &api.CallbackQuery{ + ID: "cb1", + From: api.User{ID: 7}, + Message: msg, + Data: data, + } +} + +func TestHandleCallback_Increments(t *testing.T) { + m := &mockDoer{} + // AnswerCallbackQuery + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/answerCallbackQuery") + })).Return(okResp(answerCbResult), nil) + // EditMessageText — counter must show 6 + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + if !strings.HasSuffix(r.URL.Path, "/editMessageText") { + return false + } + buf := new(bytes.Buffer) + _, _ = buf.ReadFrom(r.Body) + return strings.Contains(buf.String(), `"Counter: 6"`) + })).Return(okResp(editMsgResult), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + q := callbackQuery("count:5:inc", 10, 42) + // groups: [full_match, "5", "inc"] + c := callbackCtx(bot, q, []string{"count:5:inc", "5", "inc"}) + + require.NoError(t, handleCallback(c, q)) + m.AssertExpectations(t) +} + +func TestHandleCallback_Decrements(t *testing.T) { + m := &mockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/answerCallbackQuery") + })).Return(okResp(answerCbResult), nil) + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + if !strings.HasSuffix(r.URL.Path, "/editMessageText") { + return false + } + buf := new(bytes.Buffer) + _, _ = buf.ReadFrom(r.Body) + return strings.Contains(buf.String(), `"Counter: 4"`) + })).Return(okResp(editMsgResult), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + q := callbackQuery("count:5:dec", 10, 42) + c := callbackCtx(bot, q, []string{"count:5:dec", "5", "dec"}) + + require.NoError(t, handleCallback(c, q)) + m.AssertExpectations(t) +} diff --git a/examples/callback/main.go b/examples/callback/main.go new file mode 100644 index 0000000..fdccc00 --- /dev/null +++ b/examples/callback/main.go @@ -0,0 +1,39 @@ +// Package main demonstrates inline keyboards and callback queries with +// go-telegram. Send /start to the bot in any chat to see two buttons. +// +// TELEGRAM_BOT_TOKEN=xxx go run ./examples/callback +package main + +import ( + "context" + "log" + "os" + "os/signal" + "syscall" + + "github.com/lukaszraczylo/go-telegram/client" + "github.com/lukaszraczylo/go-telegram/dispatch" + "github.com/lukaszraczylo/go-telegram/transport" +) + +func main() { + token := os.Getenv("TELEGRAM_BOT_TOKEN") + if token == "" { + log.Fatal("TELEGRAM_BOT_TOKEN required") + } + + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + + bot := client.New(token, + client.WithHTTPClient(client.NewRetryDoer(client.NewDefaultHTTPDoer())), + ) + + router := dispatch.New(bot) + register(router) + + poller := transport.NewLongPoller(bot) + if err := router.Run(ctx, poller); err != nil && err != context.Canceled { + log.Printf("router exited: %v", err) + } +} diff --git a/examples/conversation/README.md b/examples/conversation/README.md new file mode 100644 index 0000000..0b86f78 --- /dev/null +++ b/examples/conversation/README.md @@ -0,0 +1,10 @@ +# conversation + +Multi-step conversation flow demonstrating `dispatch/conversation`. Send `/newbot` to start; reply with a name then a description. Send `/cancel` at any point to abort. + +## Run + +```bash +export TELEGRAM_BOT_TOKEN=... +go run ./examples/conversation +``` diff --git a/examples/conversation/handlers.go b/examples/conversation/handlers.go new file mode 100644 index 0000000..10353b0 --- /dev/null +++ b/examples/conversation/handlers.go @@ -0,0 +1,75 @@ +package main + +import ( + "github.com/lukaszraczylo/go-telegram/api" + "github.com/lukaszraczylo/go-telegram/client" + "github.com/lukaszraczylo/go-telegram/dispatch" + "github.com/lukaszraczylo/go-telegram/dispatch/conversation" + msgfilter "github.com/lukaszraczylo/go-telegram/dispatch/filters/message" +) + +// onMsg lifts a Filter[*api.Message] into a Filter[*api.Update]. +func onMsg(f dispatch.Filter[*api.Message]) dispatch.Filter[*api.Update] { + return func(u *api.Update) bool { return u.Message != nil && f(u.Message) } +} + +// notCmd matches message updates that are NOT a bot command. +var notCmd = onMsg(msgfilter.AnyCommand().Not()) + +// buildConv constructs the /newbot conversation. Accepts an optional Storage +// so tests can inject MemoryStorage for isolation; pass nil for the default. +func buildConv(storage conversation.Storage) *conversation.Conversation { + conv := &conversation.Conversation{ + Storage: storage, + EntryPoints: []conversation.Step{{ + Filter: onMsg(msgfilter.Command("/newbot")), + Handler: func(c *dispatch.Context, u *api.Update) error { + _, _ = api.SendMessage(c.Ctx, c.Bot, &api.SendMessageParams{ + ChatID: api.ChatIDFromInt(u.Message.Chat.ID), + Text: "What should the bot's name be?", + }) + return conversation.Next("await_name") + }, + }}, + States: map[conversation.State][]conversation.Step{ + "await_name": {{ + Filter: notCmd, + Handler: func(c *dispatch.Context, u *api.Update) error { + _, _ = api.SendMessage(c.Ctx, c.Bot, &api.SendMessageParams{ + ChatID: api.ChatIDFromInt(u.Message.Chat.ID), + Text: "Got it! What's the description?", + }) + return conversation.Next("await_desc") + }, + }}, + "await_desc": {{ + Filter: notCmd, + Handler: func(c *dispatch.Context, u *api.Update) error { + _, _ = api.SendMessage(c.Ctx, c.Bot, &api.SendMessageParams{ + ChatID: api.ChatIDFromInt(u.Message.Chat.ID), + Text: "Done! Your bot has been configured.", + }) + return conversation.End() + }, + }}, + }, + Exits: []conversation.Step{{ + Filter: onMsg(msgfilter.Command("/cancel")), + Handler: func(c *dispatch.Context, u *api.Update) error { + _, _ = api.SendMessage(c.Ctx, c.Bot, &api.SendMessageParams{ + ChatID: api.ChatIDFromInt(u.Message.Chat.ID), + Text: "Cancelled.", + }) + return conversation.End() + }, + }}, + } + return conv +} + +// register wires the conversation middleware onto the router. +func register(r *dispatch.Router, bot *client.Bot) { + _ = bot // bot available for future handlers if needed + conv := buildConv(nil) + r.Use(conv.Dispatch) +} diff --git a/examples/conversation/handlers_test.go b/examples/conversation/handlers_test.go new file mode 100644 index 0000000..f97ffc6 --- /dev/null +++ b/examples/conversation/handlers_test.go @@ -0,0 +1,133 @@ +package main + +import ( + "bytes" + "context" + "io" + "net/http" + "testing" + + "github.com/lukaszraczylo/go-telegram/api" + "github.com/lukaszraczylo/go-telegram/client" + "github.com/lukaszraczylo/go-telegram/dispatch" + "github.com/lukaszraczylo/go-telegram/dispatch/conversation" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" +) + +// mockDoer satisfies client.HTTPDoer. +type mockDoer struct{ mock.Mock } + +func (m *mockDoer) Do(r *http.Request) (*http.Response, error) { + args := m.Called(r) + if v := args.Get(0); v != nil { + return v.(*http.Response), args.Error(1) + } + return nil, args.Error(1) +} + +func anyResp() *http.Response { + return &http.Response{ + StatusCode: 200, + Body: io.NopCloser(bytes.NewBufferString(`{"ok":true,"result":{"message_id":1,"date":0,"chat":{"id":1,"type":"private"}}}`)), + Header: http.Header{"Content-Type": []string{"application/json"}}, + } +} + +// msgUpd builds a message update with the given user/chat/text. +func msgUpd(userID, chatID int64, text string) api.Update { + entities := []api.MessageEntity{} + if len(text) > 0 && text[0] == '/' { + end := len(text) + for i, r := range text { + if r == ' ' { + end = i + break + } + } + entities = append(entities, api.MessageEntity{ + Type: string(api.EntityBotCommand), + Offset: 0, + Length: int64(end), + }) + } + return api.Update{ + UpdateID: 1, + Message: &api.Message{ + MessageID: 1, + From: &api.User{ID: userID}, + Chat: api.Chat{ID: chatID, Type: string(api.ChatTypePrivate)}, + Text: text, + Entities: entities, + }, + } +} + +func makeCtx(bot *client.Bot, u *api.Update) *dispatch.Context { + return dispatch.NewContext(context.Background(), bot, u) +} + +// allowAny mocks unlimited sendMessage calls. +func allowAny(m *mockDoer) { + m.On("Do", mock.Anything).Return(anyResp(), nil) +} + +func TestConversation_NewBot_AsksName(t *testing.T) { + m := &mockDoer{} + allowAny(m) + bot := client.New("test:token", client.WithHTTPClient(m)) + + store := conversation.NewMemoryStorage() + conv := buildConv(store) + mw := conv.Dispatch(func(c *dispatch.Context, u *api.Update) error { return nil }) + + u := msgUpd(42, 1, "/newbot") + require.NoError(t, mw(makeCtx(bot, &u), &u)) + + state, err := store.Get(context.Background(), "uc:1:42") + require.NoError(t, err) + require.Equal(t, conversation.State("await_name"), state) +} + +func TestConversation_NewBot_StoresName_AsksDesc(t *testing.T) { + m := &mockDoer{} + allowAny(m) + bot := client.New("test:token", client.WithHTTPClient(m)) + + store := conversation.NewMemoryStorage() + conv := buildConv(store) + mw := conv.Dispatch(func(c *dispatch.Context, u *api.Update) error { return nil }) + + // Enter conversation. + u1 := msgUpd(42, 1, "/newbot") + require.NoError(t, mw(makeCtx(bot, &u1), &u1)) + + // Reply with name — should advance to await_desc. + u2 := msgUpd(42, 1, "MyBot") + require.NoError(t, mw(makeCtx(bot, &u2), &u2)) + + state, err := store.Get(context.Background(), "uc:1:42") + require.NoError(t, err) + require.Equal(t, conversation.State("await_desc"), state) +} + +func TestConversation_Cancel_EndsConversation(t *testing.T) { + m := &mockDoer{} + allowAny(m) + bot := client.New("test:token", client.WithHTTPClient(m)) + + store := conversation.NewMemoryStorage() + conv := buildConv(store) + mw := conv.Dispatch(func(c *dispatch.Context, u *api.Update) error { return nil }) + + // Enter conversation. + u1 := msgUpd(42, 1, "/newbot") + require.NoError(t, mw(makeCtx(bot, &u1), &u1)) + + // Cancel mid-flow. + u2 := msgUpd(42, 1, "/cancel") + require.NoError(t, mw(makeCtx(bot, &u2), &u2)) + + _, err := store.Get(context.Background(), "uc:1:42") + require.ErrorIs(t, err, conversation.ErrKeyNotFound, "cancel must clear state") +} diff --git a/examples/conversation/main.go b/examples/conversation/main.go new file mode 100644 index 0000000..55fe0f8 --- /dev/null +++ b/examples/conversation/main.go @@ -0,0 +1,37 @@ +// Package main demonstrates a /newbot-style conversation flow using +// dispatch/conversation. +// +// TELEGRAM_BOT_TOKEN=xxx go run ./examples/conversation +package main + +import ( + "context" + "log" + "os" + "os/signal" + "syscall" + + "github.com/lukaszraczylo/go-telegram/client" + "github.com/lukaszraczylo/go-telegram/dispatch" + "github.com/lukaszraczylo/go-telegram/transport" +) + +func main() { + token := os.Getenv("TELEGRAM_BOT_TOKEN") + if token == "" { + log.Fatal("TELEGRAM_BOT_TOKEN required") + } + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + + bot := client.New(token, + client.WithHTTPClient(client.NewRetryDoer(client.NewDefaultHTTPDoer()))) + + router := dispatch.New(bot) + register(router, bot) + + poller := transport.NewLongPoller(bot) + if err := router.Run(ctx, poller); err != nil && err != context.Canceled { + log.Printf("router exited: %v", err) + } +} diff --git a/examples/echo/README.md b/examples/echo/README.md new file mode 100644 index 0000000..9e2fbf2 --- /dev/null +++ b/examples/echo/README.md @@ -0,0 +1,10 @@ +# echo + +Long-poll echo bot. Replies to `/start` with a greeting and echoes any other text. + +## Run + +```bash +export TELEGRAM_BOT_TOKEN=123456:ABC... +go run ./examples/echo +``` diff --git a/examples/echo/handlers.go b/examples/echo/handlers.go new file mode 100644 index 0000000..d7e1699 --- /dev/null +++ b/examples/echo/handlers.go @@ -0,0 +1,32 @@ +package main + +import ( + "fmt" + + "github.com/lukaszraczylo/go-telegram/api" + "github.com/lukaszraczylo/go-telegram/dispatch" +) + +// register wires all handlers onto the router. Exposed so tests can call +// handlers directly without going through the router run loop. +func register(r *dispatch.Router) { + r.OnCommand("/start", handleStart) + r.OnText(`.+`, handleEcho) +} + +func handleStart(c *dispatch.Context, m *api.Message) error { + _, err := api.SendMessage(c.Ctx, c.Bot, &api.SendMessageParams{ + ChatID: api.ChatIDFromInt(m.Chat.ID), + Text: fmt.Sprintf("hello %s, send me anything to echo", m.From.FirstName), + }) + return err +} + +func handleEcho(c *dispatch.Context, m *api.Message) error { + _, err := api.SendMessage(c.Ctx, c.Bot, &api.SendMessageParams{ + ChatID: api.ChatIDFromInt(m.Chat.ID), + Text: m.Text, + ReplyParameters: &api.ReplyParameters{MessageID: m.MessageID}, + }) + return err +} diff --git a/examples/echo/handlers_test.go b/examples/echo/handlers_test.go new file mode 100644 index 0000000..c93a18c --- /dev/null +++ b/examples/echo/handlers_test.go @@ -0,0 +1,93 @@ +package main + +import ( + "bytes" + "context" + "io" + "net/http" + "strings" + "testing" + + "github.com/lukaszraczylo/go-telegram/api" + "github.com/lukaszraczylo/go-telegram/client" + "github.com/lukaszraczylo/go-telegram/dispatch" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" +) + +// mockDoer satisfies client.HTTPDoer via testify/mock. +type mockDoer struct{ mock.Mock } + +func (m *mockDoer) Do(r *http.Request) (*http.Response, error) { + args := m.Called(r) + if v := args.Get(0); v != nil { + return v.(*http.Response), args.Error(1) + } + return nil, args.Error(1) +} + +func okResp(body string) *http.Response { + return &http.Response{ + StatusCode: 200, + Body: io.NopCloser(bytes.NewBufferString(body)), + Header: http.Header{"Content-Type": []string{"application/json"}}, + } +} + +const sendMsgResult = `{"ok":true,"result":{"message_id":1,"date":0,"chat":{"id":42,"type":"private"}}}` + +func makeCtx(bot *client.Bot, upd *api.Update) *dispatch.Context { + return dispatch.NewContext(context.Background(), bot, upd) +} + +func TestHandleStart_GreetsUser(t *testing.T) { + m := &mockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + if !strings.HasSuffix(r.URL.Path, "/sendMessage") { + return false + } + buf := new(bytes.Buffer) + _, _ = buf.ReadFrom(r.Body) + body := buf.String() + return strings.Contains(body, `"text"`) && strings.Contains(body, "Alice") + })).Return(okResp(sendMsgResult), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + msg := &api.Message{ + MessageID: 1, + Chat: api.Chat{ID: 42, Type: string(api.ChatTypePrivate)}, + From: &api.User{ID: 7, FirstName: "Alice"}, + Text: "/start", + } + upd := &api.Update{UpdateID: 1, Message: msg} + + require.NoError(t, handleStart(makeCtx(bot, upd), msg)) + m.AssertExpectations(t) +} + +func TestHandleEcho_RepliesWithSameText(t *testing.T) { + m := &mockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + if !strings.HasSuffix(r.URL.Path, "/sendMessage") { + return false + } + buf := new(bytes.Buffer) + _, _ = buf.ReadFrom(r.Body) + body := buf.String() + // text is echoed and reply_to_message_id is set to source message ID (5) + return strings.Contains(body, `"hello echo"`) && + strings.Contains(body, `"message_id":5`) + })).Return(okResp(sendMsgResult), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + msg := &api.Message{ + MessageID: 5, + Chat: api.Chat{ID: 42, Type: string(api.ChatTypePrivate)}, + From: &api.User{ID: 7, FirstName: "Alice"}, + Text: "hello echo", + } + upd := &api.Update{UpdateID: 1, Message: msg} + + require.NoError(t, handleEcho(makeCtx(bot, upd), msg)) + m.AssertExpectations(t) +} diff --git a/examples/echo/main.go b/examples/echo/main.go new file mode 100644 index 0000000..cf98090 --- /dev/null +++ b/examples/echo/main.go @@ -0,0 +1,43 @@ +// Package main is a long-poll echo bot. Run with: +// +// TELEGRAM_BOT_TOKEN=xxx go run ./examples/echo +package main + +import ( + "context" + "log" + "os" + "os/signal" + "syscall" + + "github.com/lukaszraczylo/go-telegram/api" + "github.com/lukaszraczylo/go-telegram/client" + "github.com/lukaszraczylo/go-telegram/dispatch" + "github.com/lukaszraczylo/go-telegram/transport" +) + +func main() { + token := os.Getenv("TELEGRAM_BOT_TOKEN") + if token == "" { + log.Fatal("TELEGRAM_BOT_TOKEN required") + } + + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + + bot := client.New(token, + client.WithHTTPClient(client.NewRetryDoer(client.NewDefaultHTTPDoer()))) + me, err := api.GetMe(ctx, bot, &api.GetMeParams{}) + if err != nil { + log.Fatalf("getMe: %v", err) + } + log.Printf("running as @%s", me.Username) + + router := dispatch.New(bot) + register(router) + + poller := transport.NewLongPoller(bot) + if err := router.Run(ctx, poller); err != nil && err != context.Canceled { + log.Printf("router exited: %v", err) + } +} diff --git a/examples/files/README.md b/examples/files/README.md new file mode 100644 index 0000000..53e8616 --- /dev/null +++ b/examples/files/README.md @@ -0,0 +1,12 @@ +# files + +Bot that downloads documents users send and re-uploads them. Demonstrates `api.DownloadFile`, `api.SendDocument` with `*InputFile`, and middleware-based dispatch on document updates. + +## Run + +```bash +export TELEGRAM_BOT_TOKEN=... +go run ./examples/files +``` + +Send any document to the bot. diff --git a/examples/files/main.go b/examples/files/main.go new file mode 100644 index 0000000..5a2ee8d --- /dev/null +++ b/examples/files/main.go @@ -0,0 +1,110 @@ +// Package main demonstrates file upload and download with go-telegram. +// Send any document or photo to the bot — it downloads, then re-uploads +// the file with a "received: " caption. +// +// TELEGRAM_BOT_TOKEN=xxx go run ./examples/files +package main + +import ( + "bytes" + "context" + "fmt" + "io" + "log" + "os" + "os/signal" + "path/filepath" + "syscall" + + "github.com/lukaszraczylo/go-telegram/api" + "github.com/lukaszraczylo/go-telegram/client" + "github.com/lukaszraczylo/go-telegram/dispatch" + "github.com/lukaszraczylo/go-telegram/transport" +) + +func main() { + token := os.Getenv("TELEGRAM_BOT_TOKEN") + if token == "" { + log.Fatal("TELEGRAM_BOT_TOKEN required") + } + + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + + bot := client.New(token, + client.WithHTTPClient(client.NewRetryDoer(client.NewDefaultHTTPDoer())), + ) + + router := dispatch.New(bot) + + router.OnCommand("/start", func(c *dispatch.Context, m *api.Message) error { + _, err := api.SendMessage(c.Ctx, c.Bot, &api.SendMessageParams{ + ChatID: api.ChatIDFromInt(m.Chat.ID), + Text: "Send me a document and I'll download then re-upload it.", + }) + return err + }) + + // Document uploads land in Message.Document. Use middleware to handle them. + router.Use(func(next dispatch.Handler[*api.Update]) dispatch.Handler[*api.Update] { + return func(c *dispatch.Context, u *api.Update) error { + if u.Message != nil && u.Message.Document != nil { + return handleDocument(c, u.Message) + } + return next(c, u) + } + }) + + poller := transport.NewLongPoller(bot) + if err := router.Run(ctx, poller); err != nil && err != context.Canceled { + log.Printf("router exited: %v", err) + } +} + +func handleDocument(c *dispatch.Context, m *api.Message) error { + doc := m.Document + fileSize := int64(0) + if doc.FileSize != nil { + fileSize = *doc.FileSize + } + log.Printf("received: %s (%d bytes)", doc.FileName, fileSize) + + // Download. + rc, _, err := api.DownloadFile(c.Ctx, c.Bot, doc.FileID) + if err != nil { + return reply(c, m.Chat.ID, fmt.Sprintf("download failed: %v", err)) + } + defer func() { + _ = rc.Close() + }() + body, err := io.ReadAll(rc) + if err != nil { + return reply(c, m.Chat.ID, fmt.Sprintf("read failed: %v", err)) + } + + // Re-upload. + name := filepath.Base(doc.FileName) + if name == "" || name == "." { + name = "file" + } + _, err = api.SendDocument(c.Ctx, c.Bot, &api.SendDocumentParams{ + ChatID: api.ChatIDFromInt(m.Chat.ID), + Document: &api.InputFile{ + Reader: bytes.NewReader(body), + Filename: name, + }, + Caption: fmt.Sprintf("received: %d bytes", len(body)), + }) + if err != nil { + return reply(c, m.Chat.ID, fmt.Sprintf("upload failed: %v", err)) + } + return nil +} + +func reply(c *dispatch.Context, chatID int64, text string) error { + _, err := api.SendMessage(c.Ctx, c.Bot, &api.SendMessageParams{ + ChatID: api.ChatIDFromInt(chatID), + Text: text, + }) + return err +} diff --git a/examples/inline/README.md b/examples/inline/README.md new file mode 100644 index 0000000..c41f69c --- /dev/null +++ b/examples/inline/README.md @@ -0,0 +1,12 @@ +# inline + +Demonstrates inline-mode queries. Enable inline mode for your bot via [@BotFather](https://t.me/BotFather) (`/setinline`). + +## Run + +```bash +export TELEGRAM_BOT_TOKEN=... +go run ./examples/inline +``` + +In any Telegram chat, type `@yourbot something` to see two results: an echo and an UPPERCASE'd version. diff --git a/examples/inline/main.go b/examples/inline/main.go new file mode 100644 index 0000000..1e8dd02 --- /dev/null +++ b/examples/inline/main.go @@ -0,0 +1,64 @@ +// Package main demonstrates inline-mode queries with go-telegram. +// +// Enable inline mode for your bot via @BotFather: /setinline → enable. +// Then type @yourbot something in any chat to see results. +// +// TELEGRAM_BOT_TOKEN=xxx go run ./examples/inline +package main + +import ( + "context" + "log" + "os" + "os/signal" + "strings" + "syscall" + + "github.com/lukaszraczylo/go-telegram/api" + "github.com/lukaszraczylo/go-telegram/client" + "github.com/lukaszraczylo/go-telegram/dispatch" + "github.com/lukaszraczylo/go-telegram/transport" +) + +func main() { + token := os.Getenv("TELEGRAM_BOT_TOKEN") + if token == "" { + log.Fatal("TELEGRAM_BOT_TOKEN required") + } + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + + bot := client.New(token) + router := dispatch.New(bot) + + router.OnInlineQuery(func(c *dispatch.Context, q *api.InlineQuery) error { + // Echo the query as article results. + results := []api.InlineQueryResult{ + &api.InlineQueryResultArticle{ + Type: "article", + ID: "echo", + Title: "Echo: " + q.Query, + InputMessageContent: &api.InputTextMessageContent{ + MessageText: q.Query, + }, + }, + &api.InlineQueryResultArticle{ + Type: "article", + ID: "upper", + Title: "UPPER: " + strings.ToUpper(q.Query), + InputMessageContent: &api.InputTextMessageContent{ + MessageText: strings.ToUpper(q.Query), + }, + }, + } + _, err := api.AnswerInlineQuery(c.Ctx, c.Bot, &api.AnswerInlineQueryParams{ + InlineQueryID: q.ID, + Results: results, + }) + return err + }) + + if err := router.Run(ctx, transport.NewLongPoller(bot)); err != nil && err != context.Canceled { + log.Printf("router exited: %v", err) + } +} diff --git a/examples/middleware/README.md b/examples/middleware/README.md new file mode 100644 index 0000000..1d0ec1c --- /dev/null +++ b/examples/middleware/README.md @@ -0,0 +1,11 @@ +# middleware + +Demonstrates two custom dispatch middlewares: timing (logs handler latency) and auth (restricts updates to a single owner via `OWNER_USER_ID` env var). + +## Run + +```bash +export TELEGRAM_BOT_TOKEN=... +export OWNER_USER_ID=123456789 # optional +go run ./examples/middleware +``` diff --git a/examples/middleware/main.go b/examples/middleware/main.go new file mode 100644 index 0000000..cb019a0 --- /dev/null +++ b/examples/middleware/main.go @@ -0,0 +1,86 @@ +// Package main demonstrates custom middleware for go-telegram. +// +// TELEGRAM_BOT_TOKEN=xxx go run ./examples/middleware +package main + +import ( + "context" + "fmt" + "log" + "os" + "os/signal" + "syscall" + "time" + + "github.com/lukaszraczylo/go-telegram/api" + "github.com/lukaszraczylo/go-telegram/client" + "github.com/lukaszraczylo/go-telegram/dispatch" + "github.com/lukaszraczylo/go-telegram/transport" +) + +// timing wraps a handler chain with start-end timing logged via stdlib log. +func timing() dispatch.Middleware[*api.Update] { + return func(next dispatch.Handler[*api.Update]) dispatch.Handler[*api.Update] { + return func(c *dispatch.Context, u *api.Update) error { + start := time.Now() + err := next(c, u) + log.Printf("update %d processed in %s err=%v", u.UpdateID, time.Since(start), err) + return err + } + } +} + +// auth restricts updates to a single allowed user ID via env var. +func auth(allowedUserID int64) dispatch.Middleware[*api.Update] { + return func(next dispatch.Handler[*api.Update]) dispatch.Handler[*api.Update] { + return func(c *dispatch.Context, u *api.Update) error { + sender := senderID(u) + if allowedUserID != 0 && sender != allowedUserID { + log.Printf("blocked update %d from user %d", u.UpdateID, sender) + return nil + } + return next(c, u) + } + } +} + +func senderID(u *api.Update) int64 { + switch { + case u.Message != nil && u.Message.From != nil: + return u.Message.From.ID + case u.CallbackQuery != nil: + return u.CallbackQuery.From.ID + } + return 0 +} + +func main() { + token := os.Getenv("TELEGRAM_BOT_TOKEN") + if token == "" { + log.Fatal("TELEGRAM_BOT_TOKEN required") + } + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + + bot := client.New(token) + router := dispatch.New(bot) + router.Use(timing()) + // To restrict to a single owner, set OWNER_USER_ID env to your numeric ID. + var ownerID int64 + _, _ = fmt.Sscanf(os.Getenv("OWNER_USER_ID"), "%d", &ownerID) + if ownerID != 0 { + router.Use(auth(ownerID)) + } + + router.OnCommand("/start", func(c *dispatch.Context, m *api.Message) error { + _, err := api.SendMessage(c.Ctx, c.Bot, &api.SendMessageParams{ + ChatID: api.ChatIDFromInt(m.Chat.ID), + Text: "middleware demo: this update was timed and (optionally) auth-checked", + }) + return err + }) + + if err := router.Run(ctx, transport.NewLongPoller(bot)); err != nil && err != context.Canceled { + log.Printf("router exited: %v", err) + } +} diff --git a/examples/moderation/README.md b/examples/moderation/README.md new file mode 100644 index 0000000..8a0034c --- /dev/null +++ b/examples/moderation/README.md @@ -0,0 +1,39 @@ +# moderation + +Group moderation commands: `/kick`, `/ban`, `/mute`, `/warn`, `/unwarn`. + +## What it shows + +- `OnCommand` for each moderation action +- `api.BanChatMember` / `api.UnbanChatMember` for kick and ban +- `api.RestrictChatMember` with `ChatPermissions` for muting +- `errors.Is(err, client.ErrForbidden)` to surface missing-permissions errors cleanly +- In-memory warn counter via `sync.Map` (auto-bans at 3 warnings) + +## Required bot permissions + +The bot must be an **admin** in the group with **"can ban users"** and **"can restrict members"** permissions. Without those rights, commands will reply with a friendly error message instead of crashing. + +## Usage + +All commands work by **replying** to a target user's message: + +``` +/kick — remove from group (can rejoin) +/ban — permanent ban +/mute — silence for 1 hour +/warn — issue a warning (3 warnings = auto-ban) +/unwarn — remove the last warning +``` + +## Production notes + +- The warn counter is in-memory and lost on restart. For production, back it with Redis or a database. +- Consider adding an admin check (see `examples/admin`) so only group admins can invoke these commands. + +## Running + +```bash +export TELEGRAM_BOT_TOKEN=123456:ABC... +go run ./examples/moderation +``` diff --git a/examples/moderation/main.go b/examples/moderation/main.go new file mode 100644 index 0000000..5f28386 --- /dev/null +++ b/examples/moderation/main.go @@ -0,0 +1,206 @@ +// Package main demonstrates group moderation commands: /kick, /ban, /mute, /warn. +// +// The bot must be an admin in the group with "can ban users" permission. +// Use by replying to a target user's message, e.g.: /kick (as a reply). +// +// TELEGRAM_BOT_TOKEN=xxx go run ./examples/moderation +package main + +import ( + "context" + "errors" + "fmt" + "log" + "os" + "os/signal" + "sync" + "syscall" + "time" + + "github.com/lukaszraczylo/go-telegram/api" + "github.com/lukaszraczylo/go-telegram/client" + "github.com/lukaszraczylo/go-telegram/dispatch" + "github.com/lukaszraczylo/go-telegram/transport" +) + +const maxWarns = 3 + +// warnKey uniquely identifies a user in a chat. +type warnKey struct { + chatID int64 + userID int64 +} + +var warnCounts sync.Map // map[warnKey]int — in-memory only; use a DB in production + +func main() { + token := os.Getenv("TELEGRAM_BOT_TOKEN") + if token == "" { + log.Fatal("TELEGRAM_BOT_TOKEN required") + } + + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + + bot := client.New(token, + client.WithHTTPClient(client.NewRetryDoer(client.NewDefaultHTTPDoer())), + ) + + router := dispatch.New(bot) + router.OnCommand("/kick", kickHandler) + router.OnCommand("/ban", banHandler) + router.OnCommand("/mute", muteHandler) + router.OnCommand("/warn", warnHandler) + router.OnCommand("/unwarn", unwarnHandler) + + poller := transport.NewLongPoller(bot) + if err := router.Run(ctx, poller); err != nil && err != context.Canceled { + log.Printf("router exited: %v", err) + } +} + +// resolveTarget returns the user ID of the moderation target. +// Priority: replied-to message sender, then first @mention in the text. +func resolveTarget(m *api.Message) int64 { + if m.ReplyToMessage != nil && m.ReplyToMessage.From != nil { + return m.ReplyToMessage.From.ID + } + return 0 +} + +func reply(c *dispatch.Context, chatID int64, text string) { + _, _ = api.SendMessage(c.Ctx, c.Bot, &api.SendMessageParams{ + ChatID: api.ChatIDFromInt(chatID), + Text: text, + }) +} + +func handleAdminErr(c *dispatch.Context, chatID int64, err error) error { + if errors.Is(err, client.ErrForbidden) { + reply(c, chatID, "I need admin rights with 'can ban users' permission.") + return nil + } + return err +} + +func kickHandler(c *dispatch.Context, m *api.Message) error { + target := resolveTarget(m) + if target == 0 { + reply(c, m.Chat.ID, "Reply to a user's message with /kick to remove them.") + return nil + } + // Kick = ban then immediately unban (removes from group, can rejoin). + if _, err := api.BanChatMember(c.Ctx, c.Bot, &api.BanChatMemberParams{ + ChatID: api.ChatIDFromInt(m.Chat.ID), + UserID: target, + }); err != nil { + return handleAdminErr(c, m.Chat.ID, err) + } + truVal := true + if _, err := api.UnbanChatMember(c.Ctx, c.Bot, &api.UnbanChatMemberParams{ + ChatID: api.ChatIDFromInt(m.Chat.ID), + UserID: target, + OnlyIfBanned: &truVal, + }); err != nil { + log.Printf("unban after kick: %v", err) + } + reply(c, m.Chat.ID, fmt.Sprintf("User %d has been kicked.", target)) + return nil +} + +func banHandler(c *dispatch.Context, m *api.Message) error { + target := resolveTarget(m) + if target == 0 { + reply(c, m.Chat.ID, "Reply to a user's message with /ban to ban them permanently.") + return nil + } + if _, err := api.BanChatMember(c.Ctx, c.Bot, &api.BanChatMemberParams{ + ChatID: api.ChatIDFromInt(m.Chat.ID), + UserID: target, + }); err != nil { + return handleAdminErr(c, m.Chat.ID, err) + } + reply(c, m.Chat.ID, fmt.Sprintf("User %d has been banned.", target)) + return nil +} + +func muteHandler(c *dispatch.Context, m *api.Message) error { + target := resolveTarget(m) + if target == 0 { + reply(c, m.Chat.ID, "Reply to a user's message with /mute to silence them for 1 hour.") + return nil + } + until := time.Now().Add(time.Hour).Unix() + falseVal := false + if _, err := api.RestrictChatMember(c.Ctx, c.Bot, &api.RestrictChatMemberParams{ + ChatID: api.ChatIDFromInt(m.Chat.ID), + UserID: target, + Permissions: api.ChatPermissions{ + CanSendMessages: &falseVal, + CanSendAudios: &falseVal, + CanSendDocuments: &falseVal, + CanSendPhotos: &falseVal, + CanSendVideos: &falseVal, + CanSendVideoNotes: &falseVal, + CanSendVoiceNotes: &falseVal, + CanSendPolls: &falseVal, + CanSendOtherMessages: &falseVal, + }, + UntilDate: &until, + }); err != nil { + return handleAdminErr(c, m.Chat.ID, err) + } + reply(c, m.Chat.ID, fmt.Sprintf("User %d muted for 1 hour.", target)) + return nil +} + +func warnHandler(c *dispatch.Context, m *api.Message) error { + target := resolveTarget(m) + if target == 0 { + reply(c, m.Chat.ID, "Reply to a user's message with /warn to issue a warning.") + return nil + } + key := warnKey{chatID: m.Chat.ID, userID: target} + var count int + if v, ok := warnCounts.Load(key); ok { + count = v.(int) + } + count++ + warnCounts.Store(key, count) + + if count >= maxWarns { + warnCounts.Delete(key) + reply(c, m.Chat.ID, fmt.Sprintf("User %d reached %d warnings — auto-banning.", target, maxWarns)) + if _, err := api.BanChatMember(c.Ctx, c.Bot, &api.BanChatMemberParams{ + ChatID: api.ChatIDFromInt(m.Chat.ID), + UserID: target, + }); err != nil { + return handleAdminErr(c, m.Chat.ID, err) + } + return nil + } + reply(c, m.Chat.ID, fmt.Sprintf("User %d warned (%d/%d). Reach %d and they're banned.", target, count, maxWarns, maxWarns)) + return nil +} + +func unwarnHandler(c *dispatch.Context, m *api.Message) error { + target := resolveTarget(m) + if target == 0 { + reply(c, m.Chat.ID, "Reply to a user's message with /unwarn to remove their last warning.") + return nil + } + key := warnKey{chatID: m.Chat.ID, userID: target} + if v, ok := warnCounts.Load(key); ok { + count := v.(int) - 1 + if count <= 0 { + warnCounts.Delete(key) + reply(c, m.Chat.ID, fmt.Sprintf("User %d has no more warnings.", target)) + } else { + warnCounts.Store(key, count) + reply(c, m.Chat.ID, fmt.Sprintf("User %d warning removed (%d/%d remaining).", target, count, maxWarns)) + } + } else { + reply(c, m.Chat.ID, fmt.Sprintf("User %d has no warnings.", target)) + } + return nil +} diff --git a/examples/pagination/README.md b/examples/pagination/README.md new file mode 100644 index 0000000..178a1c6 --- /dev/null +++ b/examples/pagination/README.md @@ -0,0 +1,29 @@ +# pagination + +Multi-page inline keyboard for browsing a list. No server-side session required — page state is encoded in callback data. + +## What it shows + +- `OnCommand("/list")` sends the first page with inline navigation buttons +- `OnCallback("^page:(\\d+)$")` parses page number from callback data via `c.Values["regex_match"]` +- `api.EditMessageText` edits the message in-place on each page turn +- `api.AnswerCallbackQuery` dismisses the loading spinner + +## Pattern + +Callback data format: `page:` where `n` is the 0-based page index. + +The `renderPage` helper builds both the text content and the keyboard in one call. Only [« Prev] or [Next »] buttons that make sense for the current page are rendered, so the keyboard is always minimal. + +## Running + +```bash +export TELEGRAM_BOT_TOKEN=123456:ABC... +go run ./examples/pagination +``` + +Send `/list` to the bot. Tap Next/Prev to navigate 20 sample items, 5 per page. + +## Extending + +To paginate dynamic data (database results, API responses), replace `sampleItems` with a function that takes `(page, pageSize)` and returns items + total count. diff --git a/examples/pagination/main.go b/examples/pagination/main.go new file mode 100644 index 0000000..cb05e02 --- /dev/null +++ b/examples/pagination/main.go @@ -0,0 +1,146 @@ +// Package main demonstrates multi-page inline keyboard navigation. +// +// /list shows page 1 of a sample item list with [« Prev] [Next »] buttons. +// Tapping a button edits the message in-place to show the next/previous page. +// Page state is encoded directly in callback data ("page:") — no server-side +// session needed. +// +// TELEGRAM_BOT_TOKEN=xxx go run ./examples/pagination +package main + +import ( + "context" + "fmt" + "log" + "os" + "os/signal" + "strconv" + "strings" + "syscall" + + "github.com/lukaszraczylo/go-telegram/api" + "github.com/lukaszraczylo/go-telegram/client" + "github.com/lukaszraczylo/go-telegram/dispatch" + "github.com/lukaszraczylo/go-telegram/transport" +) + +const itemsPerPage = 5 + +// sampleItems is the list being paginated. +var sampleItems = []string{ + "Alpha", "Bravo", "Charlie", "Delta", "Echo", + "Foxtrot", "Golf", "Hotel", "India", "Juliet", + "Kilo", "Lima", "Mike", "November", "Oscar", + "Papa", "Quebec", "Romeo", "Sierra", "Tango", +} + +// renderPage builds the message text and keyboard for the given page number. +func renderPage(items []string, page int) (string, *api.InlineKeyboardMarkup) { + start := page * itemsPerPage + if start >= len(items) { + start = 0 + page = 0 + } + end := start + itemsPerPage + if end > len(items) { + end = len(items) + } + + var sb strings.Builder + fmt.Fprintf(&sb, "Items (page %d of %d):\n\n", page+1, totalPages(len(items))) + for i := start; i < end; i++ { + fmt.Fprintf(&sb, "%d. %s\n", i+1, items[i]) + } + + var btns []api.InlineKeyboardButton + if page > 0 { + btns = append(btns, api.InlineKeyboardButton{ + Text: "« Prev", + CallbackData: fmt.Sprintf("page:%d", page-1), + }) + } + if end < len(items) { + btns = append(btns, api.InlineKeyboardButton{ + Text: "Next »", + CallbackData: fmt.Sprintf("page:%d", page+1), + }) + } + + var markup *api.InlineKeyboardMarkup + if len(btns) > 0 { + markup = &api.InlineKeyboardMarkup{ + InlineKeyboard: [][]api.InlineKeyboardButton{btns}, + } + } + return sb.String(), markup +} + +func totalPages(total int) int { + pages := total / itemsPerPage + if total%itemsPerPage != 0 { + pages++ + } + return pages +} + +func main() { + token := os.Getenv("TELEGRAM_BOT_TOKEN") + if token == "" { + log.Fatal("TELEGRAM_BOT_TOKEN required") + } + + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + + bot := client.New(token, + client.WithHTTPClient(client.NewRetryDoer(client.NewDefaultHTTPDoer())), + ) + + router := dispatch.New(bot) + + // /list — send page 0. + router.OnCommand("/list", func(c *dispatch.Context, m *api.Message) error { + text, markup := renderPage(sampleItems, 0) + _, err := api.SendMessage(c.Ctx, c.Bot, &api.SendMessageParams{ + ChatID: api.ChatIDFromInt(m.Chat.ID), + Text: text, + ReplyMarkup: markup, + }) + return err + }) + + // page: callbacks — edit message in-place. + router.OnCallback(`^page:(\d+)$`, func(c *dispatch.Context, q *api.CallbackQuery) error { + groups := c.Values["regex_match"].([]string) + page, _ := strconv.Atoi(groups[1]) + + // Acknowledge the tap first. + _, _ = api.AnswerCallbackQuery(c.Ctx, c.Bot, &api.AnswerCallbackQueryParams{ + CallbackQueryID: q.ID, + }) + + if q.Message == nil { + return nil + } + msg, ok := q.Message.(*api.Message) + if !ok { + return nil + } + + text, markup := renderPage(sampleItems, page) + chatID := api.ChatIDFromInt(msg.Chat.ID) + mid := msg.MessageID + _, err := api.EditMessageText(c.Ctx, c.Bot, &api.EditMessageTextParams{ + ChatID: &chatID, + MessageID: &mid, + Text: text, + ReplyMarkup: markup, + }) + return err + }) + + poller := transport.NewLongPoller(bot) + if err := router.Run(ctx, poller); err != nil && err != context.Canceled { + log.Printf("router exited: %v", err) + } +} diff --git a/examples/payments/README.md b/examples/payments/README.md new file mode 100644 index 0000000..f4f8386 --- /dev/null +++ b/examples/payments/README.md @@ -0,0 +1,47 @@ +# payments + +Full Telegram Payments flow: invoice → pre-checkout confirmation → successful payment. + +## What it shows + +- `api.SendInvoice` to send a product invoice with `LabeledPrice` breakdown +- `router.OnPreCheckoutQuery` + `api.AnswerPreCheckoutQuery` — must respond within 10 s +- `router.OnMessageFilter` matching `Message.SuccessfulPayment` to confirm payment + +## Environment variables + +| Variable | Required | Description | +|---|---|---| +| `TELEGRAM_BOT_TOKEN` | Yes | Bot token from @BotFather | +| `PAYMENT_PROVIDER_TOKEN` | No | Provider token from @BotFather. Leave empty for Telegram Stars (XTR). | +| `CURRENCY` | No | ISO 4217 code (default: `USD`). Use `XTR` for Stars. | + +## Test payments + +Telegram provides a test payment provider to avoid real charges during development: + +1. In @BotFather, use `/mybots` → choose your bot → **Payments** → select "Stripe TEST". +2. Use the test provider token — test payments are free and won't charge users. +3. In the Telegram client, use a test card number such as `4242 4242 4242 4242`. + +**Never expose a live provider token in source code.** Use environment variables or secrets management. + +## Flow + +``` +User: /buy +Bot: [Invoice message — "Premium Widget $2.19"] +User: [taps Pay] +Telegram → Bot: pre_checkout_query (bot has 10 s to respond) +Bot → Telegram: answerPreCheckoutQuery ok=true +Telegram → Bot: Message.SuccessfulPayment +Bot: "Payment received! Your widget is on its way." +``` + +## Running + +```bash +export TELEGRAM_BOT_TOKEN=123456:ABC... +export PAYMENT_PROVIDER_TOKEN= +go run ./examples/payments +``` diff --git a/examples/payments/main.go b/examples/payments/main.go new file mode 100644 index 0000000..991a6e4 --- /dev/null +++ b/examples/payments/main.go @@ -0,0 +1,101 @@ +// Package main demonstrates the Telegram Payments flow: +// +// 1. /buy → bot sends an invoice via sendInvoice +// 2. User confirms → Telegram sends pre_checkout_query → bot answers ok=true +// 3. User pays → Telegram sends successful_payment in a Message +// +// For testing, use Telegram's test payment provider. +// Set PAYMENT_PROVIDER_TOKEN to the token from @BotFather (test or live). +// For Telegram Stars payments, set PAYMENT_PROVIDER_TOKEN="" and CURRENCY="XTR". +// +// TELEGRAM_BOT_TOKEN=xxx PAYMENT_PROVIDER_TOKEN=yyy go run ./examples/payments +package main + +import ( + "context" + "log" + "os" + "os/signal" + "syscall" + + "github.com/lukaszraczylo/go-telegram/api" + "github.com/lukaszraczylo/go-telegram/client" + "github.com/lukaszraczylo/go-telegram/dispatch" + "github.com/lukaszraczylo/go-telegram/transport" +) + +func main() { + token := os.Getenv("TELEGRAM_BOT_TOKEN") + if token == "" { + log.Fatal("TELEGRAM_BOT_TOKEN required") + } + providerToken := os.Getenv("PAYMENT_PROVIDER_TOKEN") // empty = Telegram Stars (XTR) + currency := os.Getenv("CURRENCY") + if currency == "" { + currency = "USD" + } + + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + + bot := client.New(token, + client.WithHTTPClient(client.NewRetryDoer(client.NewDefaultHTTPDoer())), + ) + + router := dispatch.New(bot) + + // Step 1: user sends /buy — bot replies with an invoice. + router.OnCommand("/buy", func(c *dispatch.Context, m *api.Message) error { + _, err := api.SendInvoice(c.Ctx, c.Bot, &api.SendInvoiceParams{ + ChatID: api.ChatIDFromInt(m.Chat.ID), + Title: "Premium Widget", + Description: "A top-quality widget that does absolutely everything.", + Payload: "widget-purchase-v1", + ProviderToken: providerToken, + Currency: currency, + Prices: []api.LabeledPrice{ + {Label: "Widget", Amount: 199}, // $1.99 + {Label: "Tax", Amount: 20}, // $0.20 + }, + }) + if err != nil { + log.Printf("sendInvoice error: %v", err) + } + return err + }) + + // Step 2: user confirms order — Telegram sends pre_checkout_query. + // Bot MUST respond within 10 seconds. + router.OnPreCheckoutQuery(func(c *dispatch.Context, q *api.PreCheckoutQuery) error { + log.Printf("pre_checkout: id=%s payload=%q total=%d %s from=%d", + q.ID, q.InvoicePayload, q.TotalAmount, q.Currency, q.From.ID) + + // Validate the order here (check stock, pricing, etc.). + // For this demo, always approve. + _, err := api.AnswerPreCheckoutQuery(c.Ctx, c.Bot, &api.AnswerPreCheckoutQueryParams{ + PreCheckoutQueryID: q.ID, + Ok: true, + }) + return err + }) + + // Step 3: payment completed — Telegram delivers a Message.SuccessfulPayment. + router.OnMessageFilter( + func(m *api.Message) bool { return m.SuccessfulPayment != nil }, + func(c *dispatch.Context, m *api.Message) error { + sp := m.SuccessfulPayment + log.Printf("payment success: charge_id=%s payload=%q amount=%d %s", + sp.TelegramPaymentChargeID, sp.InvoicePayload, sp.TotalAmount, sp.Currency) + _, err := api.SendMessage(c.Ctx, c.Bot, &api.SendMessageParams{ + ChatID: api.ChatIDFromInt(m.Chat.ID), + Text: "Payment received! Your widget is on its way.", + }) + return err + }, + ) + + poller := transport.NewLongPoller(bot) + if err := router.Run(ctx, poller); err != nil && err != context.Canceled { + log.Printf("router exited: %v", err) + } +} diff --git a/examples/polls/README.md b/examples/polls/README.md new file mode 100644 index 0000000..86e074c --- /dev/null +++ b/examples/polls/README.md @@ -0,0 +1,29 @@ +# polls + +Create polls and tally answers in real time via `OnPollAnswer`. + +## What it shows + +- `api.SendPoll` with `[]api.InputPollOption` and `IsAnonymous: false` +- `router.OnPollAnswer` to receive vote updates (`PollAnswer.OptionIds`, `PollAnswer.User`) +- Concurrent-safe in-memory tally with `sync.Mutex` + +## Commands + +| Command | Description | +|---|---| +| `/poll ` | Creates a poll with four preset options (A/B/C/D) | +| `/tally ` | Shows current vote counts for a poll | + +## Notes + +- `OnPollAnswer` only fires for **non-anonymous** polls. For anonymous polls, Telegram does not send user identifiers. +- The poll ID is logged when the poll is created; copy it to use with `/tally`. +- Vote tallies are in-memory and reset on restart. + +## Running + +```bash +export TELEGRAM_BOT_TOKEN=123456:ABC... +go run ./examples/polls +``` diff --git a/examples/polls/main.go b/examples/polls/main.go new file mode 100644 index 0000000..e58fb6a --- /dev/null +++ b/examples/polls/main.go @@ -0,0 +1,146 @@ +// Package main demonstrates creating polls and tallying answers via OnPollAnswer. +// +// Usage: send "/poll " in a group or private chat. +// The bot creates a non-anonymous poll with four preset options and tallies votes. +// +// TELEGRAM_BOT_TOKEN=xxx go run ./examples/polls +package main + +import ( + "context" + "fmt" + "log" + "os" + "os/signal" + "strings" + "sync" + "syscall" + + "github.com/lukaszraczylo/go-telegram/api" + "github.com/lukaszraczylo/go-telegram/client" + "github.com/lukaszraczylo/go-telegram/dispatch" + "github.com/lukaszraczylo/go-telegram/transport" +) + +// pollTally maps pollID → optionIndex → voteCount. +type pollTally struct { + mu sync.Mutex + votes map[string]map[int64]int +} + +func newPollTally() *pollTally { + return &pollTally{votes: make(map[string]map[int64]int)} +} + +func (t *pollTally) record(pollID string, opts []int64) { + t.mu.Lock() + defer t.mu.Unlock() + if t.votes[pollID] == nil { + t.votes[pollID] = make(map[int64]int) + } + for _, opt := range opts { + t.votes[pollID][opt]++ + } +} + +func (t *pollTally) summary(pollID string) string { + t.mu.Lock() + defer t.mu.Unlock() + m := t.votes[pollID] + if len(m) == 0 { + return "No votes yet." + } + var sb strings.Builder + fmt.Fprintf(&sb, "Tally for poll %s:\n", pollID) + for opt, count := range m { + fmt.Fprintf(&sb, " Option %d: %d vote(s)\n", opt, count) + } + return sb.String() +} + +var pollOptions = []api.InputPollOption{ + {Text: "Option A"}, + {Text: "Option B"}, + {Text: "Option C"}, + {Text: "Option D"}, +} + +func main() { + token := os.Getenv("TELEGRAM_BOT_TOKEN") + if token == "" { + log.Fatal("TELEGRAM_BOT_TOKEN required") + } + + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + + bot := client.New(token, + client.WithHTTPClient(client.NewRetryDoer(client.NewDefaultHTTPDoer())), + ) + + tally := newPollTally() + router := dispatch.New(bot) + + router.OnCommand("/poll", func(c *dispatch.Context, m *api.Message) error { + question := strings.TrimSpace(m.Text) + // Strip the "/poll" command prefix. + if after, ok := strings.CutPrefix(question, "/poll"); ok { + question = strings.TrimSpace(after) + } + if question == "" { + _, _ = api.SendMessage(c.Ctx, c.Bot, &api.SendMessageParams{ + ChatID: api.ChatIDFromInt(m.Chat.ID), + Text: "Usage: /poll ", + }) + return nil + } + isAnon := false + msg, err := api.SendPoll(c.Ctx, c.Bot, &api.SendPollParams{ + ChatID: api.ChatIDFromInt(m.Chat.ID), + Question: question, + Options: pollOptions, + IsAnonymous: &isAnon, + }) + if err != nil { + return err + } + if msg != nil && msg.Poll != nil { + log.Printf("poll created: id=%s question=%q", msg.Poll.ID, msg.Poll.Question) + } + return nil + }) + + router.OnCommand("/tally", func(c *dispatch.Context, m *api.Message) error { + pollID := strings.TrimSpace(m.Text) + if after, ok := strings.CutPrefix(pollID, "/tally"); ok { + pollID = strings.TrimSpace(after) + } + if pollID == "" { + _, _ = api.SendMessage(c.Ctx, c.Bot, &api.SendMessageParams{ + ChatID: api.ChatIDFromInt(m.Chat.ID), + Text: "Usage: /tally ", + }) + return nil + } + _, _ = api.SendMessage(c.Ctx, c.Bot, &api.SendMessageParams{ + ChatID: api.ChatIDFromInt(m.Chat.ID), + Text: tally.summary(pollID), + }) + return nil + }) + + router.OnPollAnswer(func(c *dispatch.Context, pa *api.PollAnswer) error { + userID := int64(0) + if pa.User != nil { + userID = pa.User.ID + } + log.Printf("poll answer: poll=%s user=%d options=%v", pa.PollID, userID, pa.OptionIds) + tally.record(pa.PollID, pa.OptionIds) + return nil + }) + + poller := transport.NewLongPoller(bot) + if err := router.Run(ctx, poller); err != nil && err != context.Canceled { + log.Printf("router exited: %v", err) + } +} diff --git a/examples/stateful/README.md b/examples/stateful/README.md new file mode 100644 index 0000000..ca41330 --- /dev/null +++ b/examples/stateful/README.md @@ -0,0 +1,12 @@ +# stateful + +Per-user counter with no globals: state lives in a struct passed by closure into handlers. + +## Run + +```bash +export TELEGRAM_BOT_TOKEN=... +go run ./examples/stateful +``` + +Send `/count` to the bot in any chat. Each user has an independent counter. diff --git a/examples/stateful/main.go b/examples/stateful/main.go new file mode 100644 index 0000000..c2ded20 --- /dev/null +++ b/examples/stateful/main.go @@ -0,0 +1,64 @@ +// Package main demonstrates per-user state without globals via closures. +// Each user has an independent counter that persists for the bot's lifetime. +// +// TELEGRAM_BOT_TOKEN=xxx go run ./examples/stateful +package main + +import ( + "context" + "fmt" + "log" + "os" + "os/signal" + "sync" + "syscall" + + "github.com/lukaszraczylo/go-telegram/api" + "github.com/lukaszraczylo/go-telegram/client" + "github.com/lukaszraczylo/go-telegram/dispatch" + "github.com/lukaszraczylo/go-telegram/transport" +) + +// counterStore is a concurrent-safe per-user counter. Production code +// would back this with Redis / Postgres / sqlite. For demo purposes, +// in-memory is fine. +type counterStore struct { + mu sync.Mutex + counts map[int64]int +} + +func (s *counterStore) inc(userID int64) int { + s.mu.Lock() + defer s.mu.Unlock() + s.counts[userID]++ + return s.counts[userID] +} + +func main() { + token := os.Getenv("TELEGRAM_BOT_TOKEN") + if token == "" { + log.Fatal("TELEGRAM_BOT_TOKEN required") + } + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + + bot := client.New(token) + store := &counterStore{counts: map[int64]int{}} + + router := dispatch.New(bot) + router.OnCommand("/count", func(c *dispatch.Context, m *api.Message) error { + if m.From == nil { + return nil + } + n := store.inc(m.From.ID) + _, err := api.SendMessage(c.Ctx, c.Bot, &api.SendMessageParams{ + ChatID: api.ChatIDFromInt(m.Chat.ID), + Text: fmt.Sprintf("Your count: %d", n), + }) + return err + }) + + if err := router.Run(ctx, transport.NewLongPoller(bot)); err != nil && err != context.Canceled { + log.Printf("router exited: %v", err) + } +} diff --git a/examples/webhook/README.md b/examples/webhook/README.md new file mode 100644 index 0000000..3e495a8 --- /dev/null +++ b/examples/webhook/README.md @@ -0,0 +1,14 @@ +# webhook + +Bot using HTTPS webhooks. Replies to `/ping` with `pong`. + +## Run + +You need a public HTTPS endpoint pointed at port 8080. For local development use a tunnel like Cloudflare Tunnel or ngrok. + +```bash +export TELEGRAM_BOT_TOKEN=123456:ABC... +export WEBHOOK_URL=https://your.tunnel.example/bot +export WEBHOOK_SECRET=randomsecret123 +go run ./examples/webhook +``` diff --git a/examples/webhook/handlers.go b/examples/webhook/handlers.go new file mode 100644 index 0000000..40cde34 --- /dev/null +++ b/examples/webhook/handlers.go @@ -0,0 +1,19 @@ +package main + +import ( + "github.com/lukaszraczylo/go-telegram/api" + "github.com/lukaszraczylo/go-telegram/dispatch" +) + +// register wires all handlers onto the router. +func register(r *dispatch.Router) { + r.OnCommand("/ping", handlePing) +} + +func handlePing(c *dispatch.Context, m *api.Message) error { + _, err := api.SendMessage(c.Ctx, c.Bot, &api.SendMessageParams{ + ChatID: api.ChatIDFromInt(m.Chat.ID), + Text: "pong", + }) + return err +} diff --git a/examples/webhook/handlers_test.go b/examples/webhook/handlers_test.go new file mode 100644 index 0000000..5ce1c3d --- /dev/null +++ b/examples/webhook/handlers_test.go @@ -0,0 +1,61 @@ +package main + +import ( + "bytes" + "context" + "io" + "net/http" + "strings" + "testing" + + "github.com/lukaszraczylo/go-telegram/api" + "github.com/lukaszraczylo/go-telegram/client" + "github.com/lukaszraczylo/go-telegram/dispatch" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" +) + +type mockDoer struct{ mock.Mock } + +func (m *mockDoer) Do(r *http.Request) (*http.Response, error) { + args := m.Called(r) + if v := args.Get(0); v != nil { + return v.(*http.Response), args.Error(1) + } + return nil, args.Error(1) +} + +func okResp(body string) *http.Response { + return &http.Response{ + StatusCode: 200, + Body: io.NopCloser(bytes.NewBufferString(body)), + Header: http.Header{"Content-Type": []string{"application/json"}}, + } +} + +const sendMsgResult = `{"ok":true,"result":{"message_id":1,"date":0,"chat":{"id":42,"type":"private"}}}` + +func TestHandlePing_RepliesWithPong(t *testing.T) { + m := &mockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + if !strings.HasSuffix(r.URL.Path, "/sendMessage") { + return false + } + buf := new(bytes.Buffer) + _, _ = buf.ReadFrom(r.Body) + return strings.Contains(buf.String(), `"pong"`) + })).Return(okResp(sendMsgResult), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + msg := &api.Message{ + MessageID: 1, + Chat: api.Chat{ID: 42, Type: string(api.ChatTypePrivate)}, + From: &api.User{ID: 7, FirstName: "Alice"}, + Text: "/ping", + } + upd := &api.Update{UpdateID: 1, Message: msg} + c := dispatch.NewContext(context.Background(), bot, upd) + + require.NoError(t, handlePing(c, msg)) + m.AssertExpectations(t) +} diff --git a/examples/webhook/main.go b/examples/webhook/main.go new file mode 100644 index 0000000..35503cb --- /dev/null +++ b/examples/webhook/main.go @@ -0,0 +1,75 @@ +// Package main is a webhook bot. Run with: +// +// TELEGRAM_BOT_TOKEN=xxx \ +// WEBHOOK_URL=https://example.com/bot \ +// WEBHOOK_SECRET=somethingrandom \ +// go run ./examples/webhook +// +// The bot sets its webhook to WEBHOOK_URL on startup, listens on :8080, +// and clears the webhook on shutdown. +package main + +import ( + "context" + "log" + "net/http" + "os" + "os/signal" + "syscall" + "time" + + "github.com/lukaszraczylo/go-telegram/api" + "github.com/lukaszraczylo/go-telegram/client" + "github.com/lukaszraczylo/go-telegram/dispatch" + "github.com/lukaszraczylo/go-telegram/transport" +) + +func main() { + token := os.Getenv("TELEGRAM_BOT_TOKEN") + url := os.Getenv("WEBHOOK_URL") + secret := os.Getenv("WEBHOOK_SECRET") + if token == "" || url == "" { + log.Fatal("TELEGRAM_BOT_TOKEN and WEBHOOK_URL required") + } + + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + + bot := client.New(token, + client.WithHTTPClient(client.NewRetryDoer(client.NewDefaultHTTPDoer()))) + + if _, err := api.SetWebhook(ctx, bot, &api.SetWebhookParams{ + URL: url, + SecretToken: secret, + }); err != nil { + log.Fatalf("setWebhook: %v", err) + } + defer func() { + _, _ = api.DeleteWebhook(context.Background(), bot, &api.DeleteWebhookParams{}) + }() + + wh := transport.NewWebhookServer(bot) + wh.SecretToken = secret + + router := dispatch.New(bot) + register(router) + + mux := http.NewServeMux() + mux.Handle("/bot", wh) + srv := &http.Server{ + Addr: ":8080", + Handler: mux, + ReadHeaderTimeout: 10 * time.Second, + } + go func() { + if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed { + log.Printf("http server exited: %v", err) + stop() + } + }() + + if err := router.Run(ctx, wh); err != nil && err != context.Canceled { + log.Printf("router exited: %v", err) + } + _ = srv.Shutdown(context.Background()) +} diff --git a/examples/welcome/README.md b/examples/welcome/README.md new file mode 100644 index 0000000..56f2174 --- /dev/null +++ b/examples/welcome/README.md @@ -0,0 +1,22 @@ +# welcome + +Greet new chat members as they join a group and log member departures. + +## What it shows + +- `OnMessageFilter` matching `Message.NewChatMembers` to send a welcome message for each joiner +- `OnMessageFilter` matching `Message.LeftChatMember` to log departures +- `OnMyChatMember` to detect when the bot itself is added to or removed from a group + +## Required bot permissions + +The bot must be an **admin** in the group (or at minimum have the *"Read Messages"* permission granted to non-admin bots via `setMyDefaultAdminRights`). Without this, Telegram does not forward service messages about member joins and leaves. + +## Running + +```bash +export TELEGRAM_BOT_TOKEN=123456:ABC... +go run ./examples/welcome +``` + +Add the bot to a group, then have another user join or leave — the bot will greet joiners and log departures to stdout. diff --git a/examples/welcome/main.go b/examples/welcome/main.go new file mode 100644 index 0000000..fc44f0f --- /dev/null +++ b/examples/welcome/main.go @@ -0,0 +1,82 @@ +// Package main demonstrates greeting new chat members and detecting leaves. +// +// The bot must be an admin in the group with "can read messages" (or at least +// be able to receive service messages) to get new-member and left-member events. +// +// TELEGRAM_BOT_TOKEN=xxx go run ./examples/welcome +package main + +import ( + "context" + "fmt" + "log" + "os" + "os/signal" + "syscall" + + "github.com/lukaszraczylo/go-telegram/api" + "github.com/lukaszraczylo/go-telegram/client" + "github.com/lukaszraczylo/go-telegram/dispatch" + "github.com/lukaszraczylo/go-telegram/transport" +) + +func main() { + token := os.Getenv("TELEGRAM_BOT_TOKEN") + if token == "" { + log.Fatal("TELEGRAM_BOT_TOKEN required") + } + + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + + bot := client.New(token, + client.WithHTTPClient(client.NewRetryDoer(client.NewDefaultHTTPDoer())), + ) + + router := dispatch.New(bot) + + // Greet every new member that joins the group. + router.OnMessageFilter( + func(m *api.Message) bool { return len(m.NewChatMembers) > 0 }, + func(c *dispatch.Context, m *api.Message) error { + for _, u := range m.NewChatMembers { + name := u.FirstName + if u.LastName != "" { + name += " " + u.LastName + } + _, err := api.SendMessage(c.Ctx, c.Bot, &api.SendMessageParams{ + ChatID: api.ChatIDFromInt(m.Chat.ID), + Text: fmt.Sprintf("Welcome, %s! Please read the pinned rules before posting.", name), + }) + if err != nil { + log.Printf("send welcome: %v", err) + } + } + return nil + }, + ) + + // Log when a member leaves (or is removed from) the group. + router.OnMessageFilter( + func(m *api.Message) bool { return m.LeftChatMember != nil }, + func(c *dispatch.Context, m *api.Message) error { + log.Printf("user %d (%s) left chat %d", + m.LeftChatMember.ID, + m.LeftChatMember.FirstName, + m.Chat.ID, + ) + return nil + }, + ) + + // Detect when the bot itself is added to a group. + router.OnMyChatMember(func(c *dispatch.Context, u *api.ChatMemberUpdated) error { + log.Printf("bot chat membership changed in %d: new status = %T", u.Chat.ID, u.NewChatMember) + return nil + }) + + poller := transport.NewLongPoller(bot) + if err := router.Run(ctx, poller); err != nil && err != context.Canceled { + log.Printf("router exited: %v", err) + } +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..9c1d825 --- /dev/null +++ b/go.mod @@ -0,0 +1,16 @@ +module github.com/lukaszraczylo/go-telegram + +go 1.25.0 + +require ( + github.com/goccy/go-json v0.10.6 + github.com/stretchr/testify v1.9.0 + golang.org/x/net v0.54.0 +) + +require ( + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + github.com/stretchr/objx v0.5.2 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..7e341ba --- /dev/null +++ b/go.sum @@ -0,0 +1,16 @@ +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/goccy/go-json v0.10.6 h1:p8HrPJzOakx/mn/bQtjgNjdTcN+/S6FcG2CTtQOrHVU= +github.com/goccy/go-json v0.10.6/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY= +github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= +github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= +github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +golang.org/x/net v0.54.0 h1:2zJIZAxAHV/OHCDTCOHAYehQzLfSXuf/5SoL/Dv6w/w= +golang.org/x/net v0.54.0/go.mod h1:Sj4oj8jK6XmHpBZU/zWHw3BV3abl4Kvi+Ut7cQcY+cQ= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/internal/spec/api.json b/internal/spec/api.json new file mode 100644 index 0000000..dd42d29 --- /dev/null +++ b/internal/spec/api.json @@ -0,0 +1,27664 @@ +{ + "version": "10.0", + "types": [ + { + "name": "Update", + "doc": "This object represents an incoming update.At most one of the optional fields can be present in any given update.", + "fields": [ + { + "name": "UpdateID", + "json_name": "update_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "The update's unique identifier. Update identifiers start from a certain positive number and increase sequentially. This identifier becomes especially handy if you're using webhooks, since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order. If there are no new updates for at least a week, then identifier of the next update will be chosen randomly instead of sequentially." + }, + { + "name": "Message", + "json_name": "message", + "type": { + "kind": "named", + "name": "Message" + }, + "doc": "Optional. New incoming message of any kind - text, photo, sticker, etc." + }, + { + "name": "EditedMessage", + "json_name": "edited_message", + "type": { + "kind": "named", + "name": "Message" + }, + "doc": "Optional. New version of a message that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot." + }, + { + "name": "ChannelPost", + "json_name": "channel_post", + "type": { + "kind": "named", + "name": "Message" + }, + "doc": "Optional. New incoming channel post of any kind - text, photo, sticker, etc." + }, + { + "name": "EditedChannelPost", + "json_name": "edited_channel_post", + "type": { + "kind": "named", + "name": "Message" + }, + "doc": "Optional. New version of a channel post that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot." + }, + { + "name": "BusinessConnection", + "json_name": "business_connection", + "type": { + "kind": "named", + "name": "BusinessConnection" + }, + "doc": "Optional. The bot was connected to or disconnected from a business account, or a user edited an existing connection with the bot" + }, + { + "name": "BusinessMessage", + "json_name": "business_message", + "type": { + "kind": "named", + "name": "Message" + }, + "doc": "Optional. New message from a connected business account" + }, + { + "name": "EditedBusinessMessage", + "json_name": "edited_business_message", + "type": { + "kind": "named", + "name": "Message" + }, + "doc": "Optional. New version of a message from a connected business account" + }, + { + "name": "DeletedBusinessMessages", + "json_name": "deleted_business_messages", + "type": { + "kind": "named", + "name": "BusinessMessagesDeleted" + }, + "doc": "Optional. Messages were deleted from a connected business account" + }, + { + "name": "GuestMessage", + "json_name": "guest_message", + "type": { + "kind": "named", + "name": "Message" + }, + "doc": "Optional. New guest message. The bot can use the field Message.guest_query_id and the method answerGuestQuery to send a message in response." + }, + { + "name": "MessageReaction", + "json_name": "message_reaction", + "type": { + "kind": "named", + "name": "MessageReactionUpdated" + }, + "doc": "Optional. A reaction to a message was changed by a user. The bot must be an administrator in the chat and must explicitly specify \"message_reaction\" in the list of allowed_updates to receive these updates. The update isn't received for reactions set by bots." + }, + { + "name": "MessageReactionCount", + "json_name": "message_reaction_count", + "type": { + "kind": "named", + "name": "MessageReactionCountUpdated" + }, + "doc": "Optional. Reactions to a message with anonymous reactions were changed. The bot must be an administrator in the chat and must explicitly specify \"message_reaction_count\" in the list of allowed_updates to receive these updates. The updates are grouped and can be sent with delay up to a few minutes." + }, + { + "name": "InlineQuery", + "json_name": "inline_query", + "type": { + "kind": "named", + "name": "InlineQuery" + }, + "doc": "Optional. New incoming inline query" + }, + { + "name": "ChosenInlineResult", + "json_name": "chosen_inline_result", + "type": { + "kind": "named", + "name": "ChosenInlineResult" + }, + "doc": "Optional. The result of an inline query that was chosen by a user and sent to their chat partner. Please see our documentation on the feedback collecting for details on how to enable these updates for your bot." + }, + { + "name": "CallbackQuery", + "json_name": "callback_query", + "type": { + "kind": "named", + "name": "CallbackQuery" + }, + "doc": "Optional. New incoming callback query" + }, + { + "name": "ShippingQuery", + "json_name": "shipping_query", + "type": { + "kind": "named", + "name": "ShippingQuery" + }, + "doc": "Optional. New incoming shipping query. Only for invoices with flexible price" + }, + { + "name": "PreCheckoutQuery", + "json_name": "pre_checkout_query", + "type": { + "kind": "named", + "name": "PreCheckoutQuery" + }, + "doc": "Optional. New incoming pre-checkout query. Contains full information about checkout" + }, + { + "name": "PurchasedPaidMedia", + "json_name": "purchased_paid_media", + "type": { + "kind": "named", + "name": "PaidMediaPurchased" + }, + "doc": "Optional. A user purchased paid media with a non-empty payload sent by the bot in a non-channel chat" + }, + { + "name": "Poll", + "json_name": "poll", + "type": { + "kind": "named", + "name": "Poll" + }, + "doc": "Optional. New poll state. Bots receive only updates about manually stopped polls and polls, which are sent by the bot" + }, + { + "name": "PollAnswer", + "json_name": "poll_answer", + "type": { + "kind": "named", + "name": "PollAnswer" + }, + "doc": "Optional. A user changed their answer in a non-anonymous poll. Bots receive new votes only in polls that were sent by the bot itself." + }, + { + "name": "MyChatMember", + "json_name": "my_chat_member", + "type": { + "kind": "named", + "name": "ChatMemberUpdated" + }, + "doc": "Optional. The bot's chat member status was updated in a chat. For private chats, this update is received only when the bot is blocked or unblocked by the user." + }, + { + "name": "ChatMember", + "json_name": "chat_member", + "type": { + "kind": "named", + "name": "ChatMemberUpdated" + }, + "doc": "Optional. A chat member's status was updated in a chat. The bot must be an administrator in the chat and must explicitly specify \"chat_member\" in the list of allowed_updates to receive these updates." + }, + { + "name": "ChatJoinRequest", + "json_name": "chat_join_request", + "type": { + "kind": "named", + "name": "ChatJoinRequest" + }, + "doc": "Optional. A request to join the chat has been sent. The bot must have the can_invite_users administrator right in the chat to receive these updates." + }, + { + "name": "ChatBoost", + "json_name": "chat_boost", + "type": { + "kind": "named", + "name": "ChatBoostUpdated" + }, + "doc": "Optional. A chat boost was added or changed. The bot must be an administrator in the chat to receive these updates." + }, + { + "name": "RemovedChatBoost", + "json_name": "removed_chat_boost", + "type": { + "kind": "named", + "name": "ChatBoostRemoved" + }, + "doc": "Optional. A boost was removed from a chat. The bot must be an administrator in the chat to receive these updates." + }, + { + "name": "ManagedBot", + "json_name": "managed_bot", + "type": { + "kind": "named", + "name": "ManagedBotUpdated" + }, + "doc": "Optional. A new bot was created to be managed by the bot, or token or owner of a managed bot was changed" + } + ] + }, + { + "name": "WebhookInfo", + "doc": "Describes the current status of a webhook.", + "fields": [ + { + "name": "URL", + "json_name": "url", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Webhook URL, may be empty if webhook is not set up" + }, + { + "name": "HasCustomCertificate", + "json_name": "has_custom_certificate", + "type": { + "kind": "primitive", + "name": "bool" + }, + "required": true, + "doc": "True, if a custom certificate was provided for webhook certificate checks" + }, + { + "name": "PendingUpdateCount", + "json_name": "pending_update_count", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Number of updates awaiting delivery" + }, + { + "name": "IPAddress", + "json_name": "ip_address", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Currently used webhook IP address" + }, + { + "name": "LastErrorDate", + "json_name": "last_error_date", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. Unix time for the most recent error that happened when trying to deliver an update via webhook" + }, + { + "name": "LastErrorMessage", + "json_name": "last_error_message", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Error message in human-readable format for the most recent error that happened when trying to deliver an update via webhook" + }, + { + "name": "LastSynchronizationErrorDate", + "json_name": "last_synchronization_error_date", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. Unix time of the most recent error that happened when trying to synchronize available updates with Telegram datacenters" + }, + { + "name": "MaxConnections", + "json_name": "max_connections", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. The maximum allowed number of simultaneous HTTPS connections to the webhook for update delivery" + }, + { + "name": "AllowedUpdates", + "json_name": "allowed_updates", + "type": { + "kind": "array", + "elem_type": { + "kind": "primitive", + "name": "string" + } + }, + "doc": "Optional. A list of update types the bot is subscribed to. Defaults to all update types except chat_member" + } + ] + }, + { + "name": "User", + "doc": "This object represents a Telegram user or bot.", + "fields": [ + { + "name": "ID", + "json_name": "id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Unique identifier for this user or bot. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a 64-bit integer or double-precision float type are safe for storing this identifier." + }, + { + "name": "IsBot", + "json_name": "is_bot", + "type": { + "kind": "primitive", + "name": "bool" + }, + "required": true, + "doc": "True, if this user is a bot" + }, + { + "name": "FirstName", + "json_name": "first_name", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "User's or bot's first name" + }, + { + "name": "LastName", + "json_name": "last_name", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. User's or bot's last name" + }, + { + "name": "Username", + "json_name": "username", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. User's or bot's username" + }, + { + "name": "LanguageCode", + "json_name": "language_code", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. IETF language tag of the user's language" + }, + { + "name": "IsPremium", + "json_name": "is_premium", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if this user is a Telegram Premium user" + }, + { + "name": "AddedToAttachmentMenu", + "json_name": "added_to_attachment_menu", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if this user added the bot to the attachment menu" + }, + { + "name": "CanJoinGroups", + "json_name": "can_join_groups", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the bot can be invited to groups. Returned only in getMe." + }, + { + "name": "CanReadAllGroupMessages", + "json_name": "can_read_all_group_messages", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if privacy mode is disabled for the bot. Returned only in getMe." + }, + { + "name": "SupportsGuestQueries", + "json_name": "supports_guest_queries", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the bot supports guest queries from chats it is not a member of. Returned only in getMe." + }, + { + "name": "SupportsInlineQueries", + "json_name": "supports_inline_queries", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the bot supports inline queries. Returned only in getMe." + }, + { + "name": "CanConnectToBusiness", + "json_name": "can_connect_to_business", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the bot can be connected to a user account to manage it. Returned only in getMe." + }, + { + "name": "HasMainWebApp", + "json_name": "has_main_web_app", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the bot has a main Web App. Returned only in getMe." + }, + { + "name": "HasTopicsEnabled", + "json_name": "has_topics_enabled", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the bot has forum topic mode enabled in private chats. Returned only in getMe." + }, + { + "name": "AllowsUsersToCreateTopics", + "json_name": "allows_users_to_create_topics", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the bot allows users to create and delete topics in private chats. Returned only in getMe." + }, + { + "name": "CanManageBots", + "json_name": "can_manage_bots", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if other bots can be created to be controlled by the bot. Returned only in getMe." + } + ] + }, + { + "name": "Chat", + "doc": "This object represents a chat.", + "fields": [ + { + "name": "ID", + "json_name": "id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Unique identifier for this chat. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this identifier." + }, + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of the chat, can be either “private”, “group”, “supergroup” or “channel”" + }, + { + "name": "Title", + "json_name": "title", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Title, for supergroups, channels and group chats" + }, + { + "name": "Username", + "json_name": "username", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Username, for private chats, supergroups and channels if available" + }, + { + "name": "FirstName", + "json_name": "first_name", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. First name of the other party in a private chat" + }, + { + "name": "LastName", + "json_name": "last_name", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Last name of the other party in a private chat" + }, + { + "name": "IsForum", + "json_name": "is_forum", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the supergroup chat is a forum (has topics enabled)" + }, + { + "name": "IsDirectMessages", + "json_name": "is_direct_messages", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the chat is the direct messages chat of a channel" + } + ] + }, + { + "name": "ChatFullInfo", + "doc": "This object contains full information about a chat.", + "fields": [ + { + "name": "ID", + "json_name": "id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Unique identifier for this chat. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this identifier." + }, + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of the chat, can be either “private”, “group”, “supergroup” or “channel”" + }, + { + "name": "Title", + "json_name": "title", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Title, for supergroups, channels and group chats" + }, + { + "name": "Username", + "json_name": "username", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Username, for private chats, supergroups and channels if available" + }, + { + "name": "FirstName", + "json_name": "first_name", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. First name of the other party in a private chat" + }, + { + "name": "LastName", + "json_name": "last_name", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Last name of the other party in a private chat" + }, + { + "name": "IsForum", + "json_name": "is_forum", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the supergroup chat is a forum (has topics enabled)" + }, + { + "name": "IsDirectMessages", + "json_name": "is_direct_messages", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the chat is the direct messages chat of a channel" + }, + { + "name": "AccentColorID", + "json_name": "accent_color_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Identifier of the accent color for the chat name and backgrounds of the chat photo, reply header, and link preview. See accent colors for more details." + }, + { + "name": "MaxReactionCount", + "json_name": "max_reaction_count", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "The maximum number of reactions that can be set on a message in the chat" + }, + { + "name": "Photo", + "json_name": "photo", + "type": { + "kind": "named", + "name": "ChatPhoto" + }, + "doc": "Optional. Chat photo" + }, + { + "name": "ActiveUsernames", + "json_name": "active_usernames", + "type": { + "kind": "array", + "elem_type": { + "kind": "primitive", + "name": "string" + } + }, + "doc": "Optional. If non-empty, the list of all active chat usernames; for private chats, supergroups and channels" + }, + { + "name": "Birthdate", + "json_name": "birthdate", + "type": { + "kind": "named", + "name": "Birthdate" + }, + "doc": "Optional. For private chats, the date of birth of the user" + }, + { + "name": "BusinessIntro", + "json_name": "business_intro", + "type": { + "kind": "named", + "name": "BusinessIntro" + }, + "doc": "Optional. For private chats with business accounts, the intro of the business" + }, + { + "name": "BusinessLocation", + "json_name": "business_location", + "type": { + "kind": "named", + "name": "BusinessLocation" + }, + "doc": "Optional. For private chats with business accounts, the location of the business" + }, + { + "name": "BusinessOpeningHours", + "json_name": "business_opening_hours", + "type": { + "kind": "named", + "name": "BusinessOpeningHours" + }, + "doc": "Optional. For private chats with business accounts, the opening hours of the business" + }, + { + "name": "PersonalChat", + "json_name": "personal_chat", + "type": { + "kind": "named", + "name": "Chat" + }, + "doc": "Optional. For private chats, the personal channel of the user" + }, + { + "name": "ParentChat", + "json_name": "parent_chat", + "type": { + "kind": "named", + "name": "Chat" + }, + "doc": "Optional. Information about the corresponding channel chat; for direct messages chats only" + }, + { + "name": "AvailableReactions", + "json_name": "available_reactions", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "ReactionType" + } + }, + "doc": "Optional. List of available reactions allowed in the chat. If omitted, then all emoji reactions are allowed." + }, + { + "name": "BackgroundCustomEmojiID", + "json_name": "background_custom_emoji_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Custom emoji identifier of the emoji chosen by the chat for the reply header and link preview background" + }, + { + "name": "ProfileAccentColorID", + "json_name": "profile_accent_color_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. Identifier of the accent color for the chat's profile background. See profile accent colors for more details." + }, + { + "name": "ProfileBackgroundCustomEmojiID", + "json_name": "profile_background_custom_emoji_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Custom emoji identifier of the emoji chosen by the chat for its profile background" + }, + { + "name": "EmojiStatusCustomEmojiID", + "json_name": "emoji_status_custom_emoji_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Custom emoji identifier of the emoji status of the chat or the other party in a private chat" + }, + { + "name": "EmojiStatusExpirationDate", + "json_name": "emoji_status_expiration_date", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. Expiration date of the emoji status of the chat or the other party in a private chat, in Unix time, if any" + }, + { + "name": "Bio", + "json_name": "bio", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Bio of the other party in a private chat" + }, + { + "name": "HasPrivateForwards", + "json_name": "has_private_forwards", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if privacy settings of the other party in the private chat allows to use tg://user?id= links only in chats with the user" + }, + { + "name": "HasRestrictedVoiceAndVideoMessages", + "json_name": "has_restricted_voice_and_video_messages", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the privacy settings of the other party restrict sending voice and video note messages in the private chat" + }, + { + "name": "JoinToSendMessages", + "json_name": "join_to_send_messages", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if users need to join the supergroup before they can send messages" + }, + { + "name": "JoinByRequest", + "json_name": "join_by_request", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if all users directly joining the supergroup without using an invite link need to be approved by supergroup administrators" + }, + { + "name": "Description", + "json_name": "description", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Description, for groups, supergroups and channel chats" + }, + { + "name": "InviteLink", + "json_name": "invite_link", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Primary invite link, for groups, supergroups and channel chats" + }, + { + "name": "PinnedMessage", + "json_name": "pinned_message", + "type": { + "kind": "named", + "name": "Message" + }, + "doc": "Optional. The most recent pinned message (by sending date)" + }, + { + "name": "Permissions", + "json_name": "permissions", + "type": { + "kind": "named", + "name": "ChatPermissions" + }, + "doc": "Optional. Default chat member permissions, for groups and supergroups" + }, + { + "name": "AcceptedGiftTypes", + "json_name": "accepted_gift_types", + "type": { + "kind": "named", + "name": "AcceptedGiftTypes" + }, + "required": true, + "doc": "Information about types of gifts that are accepted by the chat or by the corresponding user for private chats" + }, + { + "name": "CanSendPaidMedia", + "json_name": "can_send_paid_media", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if paid media messages can be sent or forwarded to the channel chat. The field is available only for channel chats." + }, + { + "name": "SlowModeDelay", + "json_name": "slow_mode_delay", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. For supergroups, the minimum allowed delay between consecutive messages sent by each unprivileged user; in seconds" + }, + { + "name": "UnrestrictBoostCount", + "json_name": "unrestrict_boost_count", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. For supergroups, the minimum number of boosts that a non-administrator user needs to add in order to ignore slow mode and chat permissions" + }, + { + "name": "MessageAutoDeleteTime", + "json_name": "message_auto_delete_time", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. The time after which all messages sent to the chat will be automatically deleted; in seconds" + }, + { + "name": "HasAggressiveAntiSpamEnabled", + "json_name": "has_aggressive_anti_spam_enabled", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if aggressive anti-spam checks are enabled in the supergroup. The field is only available to chat administrators." + }, + { + "name": "HasHiddenMembers", + "json_name": "has_hidden_members", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if non-administrators can only get the list of bots and administrators in the chat" + }, + { + "name": "HasProtectedContent", + "json_name": "has_protected_content", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if messages from the chat can't be forwarded to other chats" + }, + { + "name": "HasVisibleHistory", + "json_name": "has_visible_history", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if new chat members will have access to old messages; available only to chat administrators" + }, + { + "name": "StickerSetName", + "json_name": "sticker_set_name", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. For supergroups, name of the group sticker set" + }, + { + "name": "CanSetStickerSet", + "json_name": "can_set_sticker_set", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the bot can change the group sticker set" + }, + { + "name": "CustomEmojiStickerSetName", + "json_name": "custom_emoji_sticker_set_name", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. For supergroups, the name of the group's custom emoji sticker set. Custom emoji from this set can be used by all users and bots in the group." + }, + { + "name": "LinkedChatID", + "json_name": "linked_chat_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. Unique identifier for the linked chat, i.e. the discussion group identifier for a channel and vice versa; for supergroups and channel chats. This identifier may be greater than 32 bits and some programming languages may have difficulty/silent defects in interpreting it. But it is smaller than 52 bits, so a signed 64 bit integer or double-precision float type are safe for storing this identifier." + }, + { + "name": "Location", + "json_name": "location", + "type": { + "kind": "named", + "name": "ChatLocation" + }, + "doc": "Optional. For supergroups, the location to which the supergroup is connected" + }, + { + "name": "Rating", + "json_name": "rating", + "type": { + "kind": "named", + "name": "UserRating" + }, + "doc": "Optional. For private chats, the rating of the user if any" + }, + { + "name": "FirstProfileAudio", + "json_name": "first_profile_audio", + "type": { + "kind": "named", + "name": "Audio" + }, + "doc": "Optional. For private chats, the first audio added to the profile of the user" + }, + { + "name": "UniqueGiftColors", + "json_name": "unique_gift_colors", + "type": { + "kind": "named", + "name": "UniqueGiftColors" + }, + "doc": "Optional. The color scheme based on a unique gift that must be used for the chat's name, message replies and link previews" + }, + { + "name": "PaidMessageStarCount", + "json_name": "paid_message_star_count", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. The number of Telegram Stars a general user have to pay to send a message to the chat" + } + ] + }, + { + "name": "Message", + "doc": "This object represents a message.", + "fields": [ + { + "name": "MessageID", + "json_name": "message_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Unique message identifier inside this chat. In specific instances (e.g., message containing a video sent to a big chat), the server might automatically schedule a message instead of sending it immediately. In such cases, this field will be 0 and the relevant message will be unusable until it is actually sent" + }, + { + "name": "MessageThreadID", + "json_name": "message_thread_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. Unique identifier of a message thread or forum topic to which the message belongs; for supergroups and private chats only" + }, + { + "name": "DirectMessagesTopic", + "json_name": "direct_messages_topic", + "type": { + "kind": "named", + "name": "DirectMessagesTopic" + }, + "doc": "Optional. Information about the direct messages chat topic that contains the message" + }, + { + "name": "From", + "json_name": "from", + "type": { + "kind": "named", + "name": "User" + }, + "doc": "Optional. Sender of the message; may be empty for messages sent to channels. For backward compatibility, if the message was sent on behalf of a chat, the field contains a fake sender user in non-channel chats" + }, + { + "name": "SenderChat", + "json_name": "sender_chat", + "type": { + "kind": "named", + "name": "Chat" + }, + "doc": "Optional. Sender of the message when sent on behalf of a chat. For example, the supergroup itself for messages sent by its anonymous administrators or a linked channel for messages automatically forwarded to the channel's discussion group. For backward compatibility, if the message was sent on behalf of a chat, the field from contains a fake sender user in non-channel chats." + }, + { + "name": "SenderBoostCount", + "json_name": "sender_boost_count", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. If the sender of the message boosted the chat, the number of boosts added by the user" + }, + { + "name": "SenderBusinessBot", + "json_name": "sender_business_bot", + "type": { + "kind": "named", + "name": "User" + }, + "doc": "Optional. The bot that actually sent the message on behalf of the business account. Available only for outgoing messages sent on behalf of the connected business account." + }, + { + "name": "SenderTag", + "json_name": "sender_tag", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Tag or custom title of the sender of the message; for supergroups only" + }, + { + "name": "Date", + "json_name": "date", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Date the message was sent in Unix time. It is always a positive number, representing a valid date." + }, + { + "name": "GuestQueryID", + "json_name": "guest_query_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. The unique identifier for the guest query. Use this identifier with the method answerGuestQuery to send a response message. If non-empty, the message belongs to the chat where the guest bot was summoned, which may not coincide with other existing bot chats sharing the same identifier." + }, + { + "name": "BusinessConnectionID", + "json_name": "business_connection_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Unique identifier of the business connection from which the message was received. If non-empty, the message belongs to a chat of the corresponding business account that is independent from any potential bot chat which might share the same identifier." + }, + { + "name": "Chat", + "json_name": "chat", + "type": { + "kind": "named", + "name": "Chat" + }, + "required": true, + "doc": "Chat the message belongs to" + }, + { + "name": "ForwardOrigin", + "json_name": "forward_origin", + "type": { + "kind": "named", + "name": "MessageOrigin" + }, + "doc": "Optional. Information about the original message for forwarded messages" + }, + { + "name": "IsTopicMessage", + "json_name": "is_topic_message", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the message is sent to a topic in a forum supergroup or a private chat with the bot" + }, + { + "name": "IsAutomaticForward", + "json_name": "is_automatic_forward", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the message is a channel post that was automatically forwarded to the connected discussion group" + }, + { + "name": "ReplyToMessage", + "json_name": "reply_to_message", + "type": { + "kind": "named", + "name": "Message" + }, + "doc": "Optional. For replies in the same chat and message thread, the original message. Note that the Message object in this field will not contain further reply_to_message fields even if it itself is a reply." + }, + { + "name": "ExternalReply", + "json_name": "external_reply", + "type": { + "kind": "named", + "name": "ExternalReplyInfo" + }, + "doc": "Optional. Information about the message that is being replied to, which may come from another chat or forum topic" + }, + { + "name": "Quote", + "json_name": "quote", + "type": { + "kind": "named", + "name": "TextQuote" + }, + "doc": "Optional. For replies that quote part of the original message, the quoted part of the message" + }, + { + "name": "ReplyToStory", + "json_name": "reply_to_story", + "type": { + "kind": "named", + "name": "Story" + }, + "doc": "Optional. For replies to a story, the original story" + }, + { + "name": "ReplyToChecklistTaskID", + "json_name": "reply_to_checklist_task_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. Identifier of the specific checklist task that is being replied to" + }, + { + "name": "ReplyToPollOptionID", + "json_name": "reply_to_poll_option_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Persistent identifier of the specific poll option that is being replied to" + }, + { + "name": "ViaBot", + "json_name": "via_bot", + "type": { + "kind": "named", + "name": "User" + }, + "doc": "Optional. Bot through which the message was sent" + }, + { + "name": "GuestBotCallerUser", + "json_name": "guest_bot_caller_user", + "type": { + "kind": "named", + "name": "User" + }, + "doc": "Optional. For a message sent by a guest bot, this is the user whose original message triggered the bot's response" + }, + { + "name": "GuestBotCallerChat", + "json_name": "guest_bot_caller_chat", + "type": { + "kind": "named", + "name": "Chat" + }, + "doc": "Optional. For a message sent by a guest bot, this is the chat whose original message triggered the bot's response" + }, + { + "name": "EditDate", + "json_name": "edit_date", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. Date the message was last edited in Unix time" + }, + { + "name": "HasProtectedContent", + "json_name": "has_protected_content", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the message can't be forwarded" + }, + { + "name": "IsFromOffline", + "json_name": "is_from_offline", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the message was sent by an implicit action, for example, as an away or a greeting business message, or as a scheduled message" + }, + { + "name": "IsPaidPost", + "json_name": "is_paid_post", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the message is a paid post. Note that such posts must not be deleted for 24 hours to receive the payment and can't be edited." + }, + { + "name": "MediaGroupID", + "json_name": "media_group_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. The unique identifier inside this chat of a media message group this message belongs to" + }, + { + "name": "AuthorSignature", + "json_name": "author_signature", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Signature of the post author for messages in channels, or the custom title of an anonymous group administrator" + }, + { + "name": "PaidStarCount", + "json_name": "paid_star_count", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. The number of Telegram Stars that were paid by the sender of the message to send it" + }, + { + "name": "Text", + "json_name": "text", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. For text messages, the actual UTF-8 text of the message" + }, + { + "name": "Entities", + "json_name": "entities", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "MessageEntity" + } + }, + "doc": "Optional. For text messages, special entities like usernames, URLs, bot commands, etc. that appear in the text" + }, + { + "name": "LinkPreviewOptions", + "json_name": "link_preview_options", + "type": { + "kind": "named", + "name": "LinkPreviewOptions" + }, + "doc": "Optional. Options used for link preview generation for the message, if it is a text message and link preview options were changed" + }, + { + "name": "SuggestedPostInfo", + "json_name": "suggested_post_info", + "type": { + "kind": "named", + "name": "SuggestedPostInfo" + }, + "doc": "Optional. Information about suggested post parameters if the message is a suggested post in a channel direct messages chat. If the message is an approved or declined suggested post, then it can't be edited." + }, + { + "name": "EffectID", + "json_name": "effect_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Unique identifier of the message effect added to the message" + }, + { + "name": "Animation", + "json_name": "animation", + "type": { + "kind": "named", + "name": "Animation" + }, + "doc": "Optional. Message is an animation, information about the animation. For backward compatibility, when this field is set, the document field will also be set" + }, + { + "name": "Audio", + "json_name": "audio", + "type": { + "kind": "named", + "name": "Audio" + }, + "doc": "Optional. Message is an audio file, information about the file" + }, + { + "name": "Document", + "json_name": "document", + "type": { + "kind": "named", + "name": "Document" + }, + "doc": "Optional. Message is a general file, information about the file" + }, + { + "name": "LivePhoto", + "json_name": "live_photo", + "type": { + "kind": "named", + "name": "LivePhoto" + }, + "doc": "Optional. Message is a live photo, information about the live photo. For backward compatibility, when this field is set, the photo field will also be set" + }, + { + "name": "PaidMedia", + "json_name": "paid_media", + "type": { + "kind": "named", + "name": "PaidMediaInfo" + }, + "doc": "Optional. Message contains paid media; information about the paid media" + }, + { + "name": "Photo", + "json_name": "photo", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "PhotoSize" + } + }, + "doc": "Optional. Message is a photo, available sizes of the photo" + }, + { + "name": "Sticker", + "json_name": "sticker", + "type": { + "kind": "named", + "name": "Sticker" + }, + "doc": "Optional. Message is a sticker, information about the sticker" + }, + { + "name": "Story", + "json_name": "story", + "type": { + "kind": "named", + "name": "Story" + }, + "doc": "Optional. Message is a forwarded story" + }, + { + "name": "Video", + "json_name": "video", + "type": { + "kind": "named", + "name": "Video" + }, + "doc": "Optional. Message is a video, information about the video" + }, + { + "name": "VideoNote", + "json_name": "video_note", + "type": { + "kind": "named", + "name": "VideoNote" + }, + "doc": "Optional. Message is a video note, information about the video message" + }, + { + "name": "Voice", + "json_name": "voice", + "type": { + "kind": "named", + "name": "Voice" + }, + "doc": "Optional. Message is a voice message, information about the file" + }, + { + "name": "Caption", + "json_name": "caption", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Caption for the animation, audio, document, paid media, photo, video or voice" + }, + { + "name": "CaptionEntities", + "json_name": "caption_entities", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "MessageEntity" + } + }, + "doc": "Optional. For messages with a caption, special entities like usernames, URLs, bot commands, etc. that appear in the caption" + }, + { + "name": "ShowCaptionAboveMedia", + "json_name": "show_caption_above_media", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the caption must be shown above the message media" + }, + { + "name": "HasMediaSpoiler", + "json_name": "has_media_spoiler", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the message media is covered by a spoiler animation" + }, + { + "name": "Checklist", + "json_name": "checklist", + "type": { + "kind": "named", + "name": "Checklist" + }, + "doc": "Optional. Message is a checklist" + }, + { + "name": "Contact", + "json_name": "contact", + "type": { + "kind": "named", + "name": "Contact" + }, + "doc": "Optional. Message is a shared contact, information about the contact" + }, + { + "name": "Dice", + "json_name": "dice", + "type": { + "kind": "named", + "name": "Dice" + }, + "doc": "Optional. Message is a dice with random value" + }, + { + "name": "Game", + "json_name": "game", + "type": { + "kind": "named", + "name": "Game" + }, + "doc": "Optional. Message is a game, information about the game. More about games »" + }, + { + "name": "Poll", + "json_name": "poll", + "type": { + "kind": "named", + "name": "Poll" + }, + "doc": "Optional. Message is a native poll, information about the poll" + }, + { + "name": "Venue", + "json_name": "venue", + "type": { + "kind": "named", + "name": "Venue" + }, + "doc": "Optional. Message is a venue, information about the venue. For backward compatibility, when this field is set, the location field will also be set" + }, + { + "name": "Location", + "json_name": "location", + "type": { + "kind": "named", + "name": "Location" + }, + "doc": "Optional. Message is a shared location, information about the location" + }, + { + "name": "NewChatMembers", + "json_name": "new_chat_members", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "User" + } + }, + "doc": "Optional. New members that were added to the group or supergroup and information about them (the bot itself may be one of these members)" + }, + { + "name": "LeftChatMember", + "json_name": "left_chat_member", + "type": { + "kind": "named", + "name": "User" + }, + "doc": "Optional. A member was removed from the group, information about them (this member may be the bot itself)" + }, + { + "name": "ChatOwnerLeft", + "json_name": "chat_owner_left", + "type": { + "kind": "named", + "name": "ChatOwnerLeft" + }, + "doc": "Optional. Service message: chat owner has left" + }, + { + "name": "ChatOwnerChanged", + "json_name": "chat_owner_changed", + "type": { + "kind": "named", + "name": "ChatOwnerChanged" + }, + "doc": "Optional. Service message: chat owner has changed" + }, + { + "name": "NewChatTitle", + "json_name": "new_chat_title", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. A chat title was changed to this value" + }, + { + "name": "NewChatPhoto", + "json_name": "new_chat_photo", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "PhotoSize" + } + }, + "doc": "Optional. A chat photo was change to this value" + }, + { + "name": "DeleteChatPhoto", + "json_name": "delete_chat_photo", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. Service message: the chat photo was deleted" + }, + { + "name": "GroupChatCreated", + "json_name": "group_chat_created", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. Service message: the group has been created" + }, + { + "name": "SupergroupChatCreated", + "json_name": "supergroup_chat_created", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. Service message: the supergroup has been created. This field can't be received in a message coming through updates, because bot can't be a member of a supergroup when it is created. It can only be found in reply_to_message if someone replies to a very first message in a directly created supergroup." + }, + { + "name": "ChannelChatCreated", + "json_name": "channel_chat_created", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. Service message: the channel has been created. This field can't be received in a message coming through updates, because bot can't be a member of a channel when it is created. It can only be found in reply_to_message if someone replies to a very first message in a channel." + }, + { + "name": "MessageAutoDeleteTimerChanged", + "json_name": "message_auto_delete_timer_changed", + "type": { + "kind": "named", + "name": "MessageAutoDeleteTimerChanged" + }, + "doc": "Optional. Service message: auto-delete timer settings changed in the chat" + }, + { + "name": "MigrateToChatID", + "json_name": "migrate_to_chat_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. The group has been migrated to a supergroup with the specified identifier. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this identifier." + }, + { + "name": "MigrateFromChatID", + "json_name": "migrate_from_chat_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. The supergroup has been migrated from a group with the specified identifier. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this identifier." + }, + { + "name": "PinnedMessage", + "json_name": "pinned_message", + "type": { + "kind": "named", + "name": "MaybeInaccessibleMessage" + }, + "doc": "Optional. Specified message was pinned. Note that the Message object in this field will not contain further reply_to_message fields even if it itself is a reply." + }, + { + "name": "Invoice", + "json_name": "invoice", + "type": { + "kind": "named", + "name": "Invoice" + }, + "doc": "Optional. Message is an invoice for a payment, information about the invoice. More about payments »" + }, + { + "name": "SuccessfulPayment", + "json_name": "successful_payment", + "type": { + "kind": "named", + "name": "SuccessfulPayment" + }, + "doc": "Optional. Message is a service message about a successful payment, information about the payment. More about payments »" + }, + { + "name": "RefundedPayment", + "json_name": "refunded_payment", + "type": { + "kind": "named", + "name": "RefundedPayment" + }, + "doc": "Optional. Message is a service message about a refunded payment, information about the payment. More about payments »" + }, + { + "name": "UsersShared", + "json_name": "users_shared", + "type": { + "kind": "named", + "name": "UsersShared" + }, + "doc": "Optional. Service message: users were shared with the bot" + }, + { + "name": "ChatShared", + "json_name": "chat_shared", + "type": { + "kind": "named", + "name": "ChatShared" + }, + "doc": "Optional. Service message: a chat was shared with the bot" + }, + { + "name": "Gift", + "json_name": "gift", + "type": { + "kind": "named", + "name": "GiftInfo" + }, + "doc": "Optional. Service message: a regular gift was sent or received" + }, + { + "name": "UniqueGift", + "json_name": "unique_gift", + "type": { + "kind": "named", + "name": "UniqueGiftInfo" + }, + "doc": "Optional. Service message: a unique gift was sent or received" + }, + { + "name": "GiftUpgradeSent", + "json_name": "gift_upgrade_sent", + "type": { + "kind": "named", + "name": "GiftInfo" + }, + "doc": "Optional. Service message: upgrade of a gift was purchased after the gift was sent" + }, + { + "name": "ConnectedWebsite", + "json_name": "connected_website", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. The domain name of the website on which the user has logged in. More about Telegram Login »" + }, + { + "name": "WriteAccessAllowed", + "json_name": "write_access_allowed", + "type": { + "kind": "named", + "name": "WriteAccessAllowed" + }, + "doc": "Optional. Service message: the user allowed the bot to write messages after adding it to the attachment or side menu, launching a Web App from a link, or accepting an explicit request from a Web App sent by the method requestWriteAccess" + }, + { + "name": "PassportData", + "json_name": "passport_data", + "type": { + "kind": "named", + "name": "PassportData" + }, + "doc": "Optional. Telegram Passport data" + }, + { + "name": "ProximityAlertTriggered", + "json_name": "proximity_alert_triggered", + "type": { + "kind": "named", + "name": "ProximityAlertTriggered" + }, + "doc": "Optional. Service message. A user in the chat triggered another user's proximity alert while sharing Live Location." + }, + { + "name": "BoostAdded", + "json_name": "boost_added", + "type": { + "kind": "named", + "name": "ChatBoostAdded" + }, + "doc": "Optional. Service message: user boosted the chat" + }, + { + "name": "ChatBackgroundSet", + "json_name": "chat_background_set", + "type": { + "kind": "named", + "name": "ChatBackground" + }, + "doc": "Optional. Service message: chat background set" + }, + { + "name": "ChecklistTasksDone", + "json_name": "checklist_tasks_done", + "type": { + "kind": "named", + "name": "ChecklistTasksDone" + }, + "doc": "Optional. Service message: some tasks in a checklist were marked as done or not done" + }, + { + "name": "ChecklistTasksAdded", + "json_name": "checklist_tasks_added", + "type": { + "kind": "named", + "name": "ChecklistTasksAdded" + }, + "doc": "Optional. Service message: tasks were added to a checklist" + }, + { + "name": "DirectMessagePriceChanged", + "json_name": "direct_message_price_changed", + "type": { + "kind": "named", + "name": "DirectMessagePriceChanged" + }, + "doc": "Optional. Service message: the price for paid messages in the corresponding direct messages chat of a channel has changed" + }, + { + "name": "ForumTopicCreated", + "json_name": "forum_topic_created", + "type": { + "kind": "named", + "name": "ForumTopicCreated" + }, + "doc": "Optional. Service message: forum topic created" + }, + { + "name": "ForumTopicEdited", + "json_name": "forum_topic_edited", + "type": { + "kind": "named", + "name": "ForumTopicEdited" + }, + "doc": "Optional. Service message: forum topic edited" + }, + { + "name": "ForumTopicClosed", + "json_name": "forum_topic_closed", + "type": { + "kind": "named", + "name": "ForumTopicClosed" + }, + "doc": "Optional. Service message: forum topic closed" + }, + { + "name": "ForumTopicReopened", + "json_name": "forum_topic_reopened", + "type": { + "kind": "named", + "name": "ForumTopicReopened" + }, + "doc": "Optional. Service message: forum topic reopened" + }, + { + "name": "GeneralForumTopicHidden", + "json_name": "general_forum_topic_hidden", + "type": { + "kind": "named", + "name": "GeneralForumTopicHidden" + }, + "doc": "Optional. Service message: the 'General' forum topic hidden" + }, + { + "name": "GeneralForumTopicUnhidden", + "json_name": "general_forum_topic_unhidden", + "type": { + "kind": "named", + "name": "GeneralForumTopicUnhidden" + }, + "doc": "Optional. Service message: the 'General' forum topic unhidden" + }, + { + "name": "GiveawayCreated", + "json_name": "giveaway_created", + "type": { + "kind": "named", + "name": "GiveawayCreated" + }, + "doc": "Optional. Service message: a scheduled giveaway was created" + }, + { + "name": "Giveaway", + "json_name": "giveaway", + "type": { + "kind": "named", + "name": "Giveaway" + }, + "doc": "Optional. The message is a scheduled giveaway message" + }, + { + "name": "GiveawayWinners", + "json_name": "giveaway_winners", + "type": { + "kind": "named", + "name": "GiveawayWinners" + }, + "doc": "Optional. A giveaway with public winners was completed" + }, + { + "name": "GiveawayCompleted", + "json_name": "giveaway_completed", + "type": { + "kind": "named", + "name": "GiveawayCompleted" + }, + "doc": "Optional. Service message: a giveaway without public winners was completed" + }, + { + "name": "ManagedBotCreated", + "json_name": "managed_bot_created", + "type": { + "kind": "named", + "name": "ManagedBotCreated" + }, + "doc": "Optional. Service message: user created a bot that will be managed by the current bot" + }, + { + "name": "PaidMessagePriceChanged", + "json_name": "paid_message_price_changed", + "type": { + "kind": "named", + "name": "PaidMessagePriceChanged" + }, + "doc": "Optional. Service message: the price for paid messages has changed in the chat" + }, + { + "name": "PollOptionAdded", + "json_name": "poll_option_added", + "type": { + "kind": "named", + "name": "PollOptionAdded" + }, + "doc": "Optional. Service message: answer option was added to a poll" + }, + { + "name": "PollOptionDeleted", + "json_name": "poll_option_deleted", + "type": { + "kind": "named", + "name": "PollOptionDeleted" + }, + "doc": "Optional. Service message: answer option was deleted from a poll" + }, + { + "name": "SuggestedPostApproved", + "json_name": "suggested_post_approved", + "type": { + "kind": "named", + "name": "SuggestedPostApproved" + }, + "doc": "Optional. Service message: a suggested post was approved" + }, + { + "name": "SuggestedPostApprovalFailed", + "json_name": "suggested_post_approval_failed", + "type": { + "kind": "named", + "name": "SuggestedPostApprovalFailed" + }, + "doc": "Optional. Service message: approval of a suggested post has failed" + }, + { + "name": "SuggestedPostDeclined", + "json_name": "suggested_post_declined", + "type": { + "kind": "named", + "name": "SuggestedPostDeclined" + }, + "doc": "Optional. Service message: a suggested post was declined" + }, + { + "name": "SuggestedPostPaid", + "json_name": "suggested_post_paid", + "type": { + "kind": "named", + "name": "SuggestedPostPaid" + }, + "doc": "Optional. Service message: payment for a suggested post was received" + }, + { + "name": "SuggestedPostRefunded", + "json_name": "suggested_post_refunded", + "type": { + "kind": "named", + "name": "SuggestedPostRefunded" + }, + "doc": "Optional. Service message: payment for a suggested post was refunded" + }, + { + "name": "VideoChatScheduled", + "json_name": "video_chat_scheduled", + "type": { + "kind": "named", + "name": "VideoChatScheduled" + }, + "doc": "Optional. Service message: video chat scheduled" + }, + { + "name": "VideoChatStarted", + "json_name": "video_chat_started", + "type": { + "kind": "named", + "name": "VideoChatStarted" + }, + "doc": "Optional. Service message: video chat started" + }, + { + "name": "VideoChatEnded", + "json_name": "video_chat_ended", + "type": { + "kind": "named", + "name": "VideoChatEnded" + }, + "doc": "Optional. Service message: video chat ended" + }, + { + "name": "VideoChatParticipantsInvited", + "json_name": "video_chat_participants_invited", + "type": { + "kind": "named", + "name": "VideoChatParticipantsInvited" + }, + "doc": "Optional. Service message: new participants invited to a video chat" + }, + { + "name": "WebAppData", + "json_name": "web_app_data", + "type": { + "kind": "named", + "name": "WebAppData" + }, + "doc": "Optional. Service message: data sent by a Web App" + }, + { + "name": "ReplyMarkup", + "json_name": "reply_markup", + "type": { + "kind": "named", + "name": "InlineKeyboardMarkup" + }, + "doc": "Optional. Inline keyboard attached to the message. login_url buttons are represented as ordinary url buttons." + } + ] + }, + { + "name": "MessageId", + "doc": "This object represents a unique message identifier.", + "fields": [ + { + "name": "MessageID", + "json_name": "message_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Unique message identifier. In specific instances (e.g., message containing a video sent to a big chat), the server might automatically schedule a message instead of sending it immediately. In such cases, this field will be 0 and the relevant message will be unusable until it is actually sent" + } + ] + }, + { + "name": "InaccessibleMessage", + "doc": "This object describes a message that was deleted or is otherwise inaccessible to the bot.", + "fields": [ + { + "name": "Chat", + "json_name": "chat", + "type": { + "kind": "named", + "name": "Chat" + }, + "required": true, + "doc": "Chat the message belonged to" + }, + { + "name": "MessageID", + "json_name": "message_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Unique message identifier inside the chat" + }, + { + "name": "Date", + "json_name": "date", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Always 0. The field can be used to differentiate regular and inaccessible messages." + } + ] + }, + { + "name": "MaybeInaccessibleMessage", + "doc": "This object describes a message that can be inaccessible to the bot. It can be one of", + "one_of": [ + "Message", + "InaccessibleMessage" + ] + }, + { + "name": "MessageEntity", + "doc": "This object represents one special entity in a text message. For example, hashtags, usernames, URLs, etc.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of the entity. Currently, can be “mention” (@username), “hashtag” (#hashtag or #hashtag@chatusername), “cashtag” ($USD or $USD@chatusername), “bot_command” (/start@jobs_bot), “url” (https://telegram.org), “email” (do-not-reply@telegram.org), “phone_number” (+1-212-555-0123), “bold” (bold text), “italic” (italic text), “underline” (underlined text), “strikethrough” (strikethrough text), “spoiler” (spoiler message), “blockquote” (block quotation), “expandable_blockquote” (collapsed-by-default block quotation), “code” (monowidth string), “pre” (monowidth block), “text_link” (for clickable text URLs), “text_mention” (for users without usernames), “custom_emoji” (for inline custom emoji stickers), or “date_time” (for formatted date and time)" + }, + { + "name": "Offset", + "json_name": "offset", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Offset in UTF-16 code units to the start of the entity" + }, + { + "name": "Length", + "json_name": "length", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Length of the entity in UTF-16 code units" + }, + { + "name": "URL", + "json_name": "url", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. For “text_link” only, URL that will be opened after user taps on the text" + }, + { + "name": "User", + "json_name": "user", + "type": { + "kind": "named", + "name": "User" + }, + "doc": "Optional. For “text_mention” only, the mentioned user" + }, + { + "name": "Language", + "json_name": "language", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. For “pre” only, the programming language of the entity text" + }, + { + "name": "CustomEmojiID", + "json_name": "custom_emoji_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. For “custom_emoji” only, unique identifier of the custom emoji. Use getCustomEmojiStickers to get full information about the sticker" + }, + { + "name": "UnixTime", + "json_name": "unix_time", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. For “date_time” only, the Unix time associated with the entity" + }, + { + "name": "DateTimeFormat", + "json_name": "date_time_format", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. For “date_time” only, the string that defines the formatting of the date and time. See date-time entity formatting for more details." + } + ] + }, + { + "name": "TextQuote", + "doc": "This object contains information about the quoted part of a message that is replied to by the given message.", + "fields": [ + { + "name": "Text", + "json_name": "text", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Text of the quoted part of a message that is replied to by the given message" + }, + { + "name": "Entities", + "json_name": "entities", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "MessageEntity" + } + }, + "doc": "Optional. Special entities that appear in the quote. Currently, only bold, italic, underline, strikethrough, spoiler, custom_emoji, and date_time entities are kept in quotes." + }, + { + "name": "Position", + "json_name": "position", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Approximate quote position in the original message in UTF-16 code units as specified by the sender" + }, + { + "name": "IsManual", + "json_name": "is_manual", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the quote was chosen manually by the message sender. Otherwise, the quote was added automatically by the server." + } + ] + }, + { + "name": "ExternalReplyInfo", + "doc": "This object contains information about a message that is being replied to, which may come from another chat or forum topic.", + "fields": [ + { + "name": "Origin", + "json_name": "origin", + "type": { + "kind": "named", + "name": "MessageOrigin" + }, + "required": true, + "doc": "Origin of the message replied to by the given message" + }, + { + "name": "Chat", + "json_name": "chat", + "type": { + "kind": "named", + "name": "Chat" + }, + "doc": "Optional. Chat the original message belongs to. Available only if the chat is a supergroup or a channel." + }, + { + "name": "MessageID", + "json_name": "message_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. Unique message identifier inside the original chat. Available only if the original chat is a supergroup or a channel." + }, + { + "name": "LinkPreviewOptions", + "json_name": "link_preview_options", + "type": { + "kind": "named", + "name": "LinkPreviewOptions" + }, + "doc": "Optional. Options used for link preview generation for the original message, if it is a text message" + }, + { + "name": "Animation", + "json_name": "animation", + "type": { + "kind": "named", + "name": "Animation" + }, + "doc": "Optional. Message is an animation, information about the animation" + }, + { + "name": "Audio", + "json_name": "audio", + "type": { + "kind": "named", + "name": "Audio" + }, + "doc": "Optional. Message is an audio file, information about the file" + }, + { + "name": "Document", + "json_name": "document", + "type": { + "kind": "named", + "name": "Document" + }, + "doc": "Optional. Message is a general file, information about the file" + }, + { + "name": "LivePhoto", + "json_name": "live_photo", + "type": { + "kind": "named", + "name": "LivePhoto" + }, + "doc": "Optional. Message is a live photo, information about the live photo" + }, + { + "name": "PaidMedia", + "json_name": "paid_media", + "type": { + "kind": "named", + "name": "PaidMediaInfo" + }, + "doc": "Optional. Message contains paid media; information about the paid media" + }, + { + "name": "Photo", + "json_name": "photo", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "PhotoSize" + } + }, + "doc": "Optional. Message is a photo, available sizes of the photo" + }, + { + "name": "Sticker", + "json_name": "sticker", + "type": { + "kind": "named", + "name": "Sticker" + }, + "doc": "Optional. Message is a sticker, information about the sticker" + }, + { + "name": "Story", + "json_name": "story", + "type": { + "kind": "named", + "name": "Story" + }, + "doc": "Optional. Message is a forwarded story" + }, + { + "name": "Video", + "json_name": "video", + "type": { + "kind": "named", + "name": "Video" + }, + "doc": "Optional. Message is a video, information about the video" + }, + { + "name": "VideoNote", + "json_name": "video_note", + "type": { + "kind": "named", + "name": "VideoNote" + }, + "doc": "Optional. Message is a video note, information about the video message" + }, + { + "name": "Voice", + "json_name": "voice", + "type": { + "kind": "named", + "name": "Voice" + }, + "doc": "Optional. Message is a voice message, information about the file" + }, + { + "name": "HasMediaSpoiler", + "json_name": "has_media_spoiler", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the message media is covered by a spoiler animation" + }, + { + "name": "Checklist", + "json_name": "checklist", + "type": { + "kind": "named", + "name": "Checklist" + }, + "doc": "Optional. Message is a checklist" + }, + { + "name": "Contact", + "json_name": "contact", + "type": { + "kind": "named", + "name": "Contact" + }, + "doc": "Optional. Message is a shared contact, information about the contact" + }, + { + "name": "Dice", + "json_name": "dice", + "type": { + "kind": "named", + "name": "Dice" + }, + "doc": "Optional. Message is a dice with random value" + }, + { + "name": "Game", + "json_name": "game", + "type": { + "kind": "named", + "name": "Game" + }, + "doc": "Optional. Message is a game, information about the game. More about games »" + }, + { + "name": "Giveaway", + "json_name": "giveaway", + "type": { + "kind": "named", + "name": "Giveaway" + }, + "doc": "Optional. Message is a scheduled giveaway, information about the giveaway" + }, + { + "name": "GiveawayWinners", + "json_name": "giveaway_winners", + "type": { + "kind": "named", + "name": "GiveawayWinners" + }, + "doc": "Optional. A giveaway with public winners was completed" + }, + { + "name": "Invoice", + "json_name": "invoice", + "type": { + "kind": "named", + "name": "Invoice" + }, + "doc": "Optional. Message is an invoice for a payment, information about the invoice. More about payments »" + }, + { + "name": "Location", + "json_name": "location", + "type": { + "kind": "named", + "name": "Location" + }, + "doc": "Optional. Message is a shared location, information about the location" + }, + { + "name": "Poll", + "json_name": "poll", + "type": { + "kind": "named", + "name": "Poll" + }, + "doc": "Optional. Message is a native poll, information about the poll" + }, + { + "name": "Venue", + "json_name": "venue", + "type": { + "kind": "named", + "name": "Venue" + }, + "doc": "Optional. Message is a venue, information about the venue" + } + ] + }, + { + "name": "ReplyParameters", + "doc": "Describes reply parameters for the message that is being sent.", + "fields": [ + { + "name": "MessageID", + "json_name": "message_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Identifier of the message that will be replied to in the current chat, or in the chat chat_id if it is specified" + }, + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "doc": "Optional. If the message to be replied to is from a different chat, unique identifier for the chat or username of the bot, supergroup or channel in the format @username. Not supported for messages sent on behalf of a business account and messages from channel direct messages chats." + }, + { + "name": "AllowSendingWithoutReply", + "json_name": "allow_sending_without_reply", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. Pass True if the message should be sent even if the specified message to be replied to is not found. Always False for replies in another chat or forum topic. Always True for messages sent on behalf of a business account." + }, + { + "name": "Quote", + "json_name": "quote", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Quoted part of the message to be replied to; 0-1024 characters after entities parsing. The quote must be an exact substring of the message to be replied to, including bold, italic, underline, strikethrough, spoiler, custom_emoji, and date_time entities. The message will fail to send if the quote isn't found in the original message." + }, + { + "name": "QuoteParseMode", + "json_name": "quote_parse_mode", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Mode for parsing entities in the quote. See formatting options for more details." + }, + { + "name": "QuoteEntities", + "json_name": "quote_entities", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "MessageEntity" + } + }, + "doc": "Optional. A JSON-serialized list of special entities that appear in the quote. It can be specified instead of quote_parse_mode." + }, + { + "name": "QuotePosition", + "json_name": "quote_position", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. Position of the quote in the original message in UTF-16 code units" + }, + { + "name": "ChecklistTaskID", + "json_name": "checklist_task_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. Identifier of the specific checklist task to be replied to" + }, + { + "name": "PollOptionID", + "json_name": "poll_option_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Persistent identifier of the specific poll option to be replied to" + } + ] + }, + { + "name": "MessageOrigin", + "doc": "This object describes the origin of a message. It can be one of", + "one_of": [ + "MessageOriginUser", + "MessageOriginHiddenUser", + "MessageOriginChat", + "MessageOriginChannel" + ] + }, + { + "name": "MessageOriginUser", + "doc": "The message was originally sent by a known user.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of the message origin, always “user”" + }, + { + "name": "Date", + "json_name": "date", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Date the message was sent originally in Unix time" + }, + { + "name": "SenderUser", + "json_name": "sender_user", + "type": { + "kind": "named", + "name": "User" + }, + "required": true, + "doc": "User that sent the message originally" + } + ] + }, + { + "name": "MessageOriginHiddenUser", + "doc": "The message was originally sent by an unknown user.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of the message origin, always “hidden_user”" + }, + { + "name": "Date", + "json_name": "date", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Date the message was sent originally in Unix time" + }, + { + "name": "SenderUserName", + "json_name": "sender_user_name", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Name of the user that sent the message originally" + } + ] + }, + { + "name": "MessageOriginChat", + "doc": "The message was originally sent on behalf of a chat to a group chat.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of the message origin, always “chat”" + }, + { + "name": "Date", + "json_name": "date", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Date the message was sent originally in Unix time" + }, + { + "name": "SenderChat", + "json_name": "sender_chat", + "type": { + "kind": "named", + "name": "Chat" + }, + "required": true, + "doc": "Chat that sent the message originally" + }, + { + "name": "AuthorSignature", + "json_name": "author_signature", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. For messages originally sent by an anonymous chat administrator, original message author signature" + } + ] + }, + { + "name": "MessageOriginChannel", + "doc": "The message was originally sent to a channel chat.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of the message origin, always “channel”" + }, + { + "name": "Date", + "json_name": "date", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Date the message was sent originally in Unix time" + }, + { + "name": "Chat", + "json_name": "chat", + "type": { + "kind": "named", + "name": "Chat" + }, + "required": true, + "doc": "Channel chat to which the message was originally sent" + }, + { + "name": "MessageID", + "json_name": "message_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Unique message identifier inside the chat" + }, + { + "name": "AuthorSignature", + "json_name": "author_signature", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Signature of the original post author" + } + ] + }, + { + "name": "PhotoSize", + "doc": "This object represents one size of a photo or a file / sticker thumbnail.", + "fields": [ + { + "name": "FileID", + "json_name": "file_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Identifier for this file, which can be used to download or reuse the file" + }, + { + "name": "FileUniqueID", + "json_name": "file_unique_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file." + }, + { + "name": "Width", + "json_name": "width", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Photo width" + }, + { + "name": "Height", + "json_name": "height", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Photo height" + }, + { + "name": "FileSize", + "json_name": "file_size", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. File size in bytes" + } + ] + }, + { + "name": "Animation", + "doc": "This object represents an animation file (GIF or H.264/MPEG-4 AVC video without sound).", + "fields": [ + { + "name": "FileID", + "json_name": "file_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Identifier for this file, which can be used to download or reuse the file" + }, + { + "name": "FileUniqueID", + "json_name": "file_unique_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file." + }, + { + "name": "Width", + "json_name": "width", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Video width as defined by the sender" + }, + { + "name": "Height", + "json_name": "height", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Video height as defined by the sender" + }, + { + "name": "Duration", + "json_name": "duration", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Duration of the video in seconds as defined by the sender" + }, + { + "name": "Thumbnail", + "json_name": "thumbnail", + "type": { + "kind": "named", + "name": "PhotoSize" + }, + "doc": "Optional. Animation thumbnail as defined by the sender" + }, + { + "name": "FileName", + "json_name": "file_name", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Original animation filename as defined by the sender" + }, + { + "name": "MimeType", + "json_name": "mime_type", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. MIME type of the file as defined by the sender" + }, + { + "name": "FileSize", + "json_name": "file_size", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. File size in bytes. It can be bigger than 2^31 and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this value." + } + ] + }, + { + "name": "Audio", + "doc": "This object represents an audio file to be treated as music by the Telegram clients.", + "fields": [ + { + "name": "FileID", + "json_name": "file_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Identifier for this file, which can be used to download or reuse the file" + }, + { + "name": "FileUniqueID", + "json_name": "file_unique_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file." + }, + { + "name": "Duration", + "json_name": "duration", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Duration of the audio in seconds as defined by the sender" + }, + { + "name": "Performer", + "json_name": "performer", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Performer of the audio as defined by the sender or by audio tags" + }, + { + "name": "Title", + "json_name": "title", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Title of the audio as defined by the sender or by audio tags" + }, + { + "name": "FileName", + "json_name": "file_name", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Original filename as defined by the sender" + }, + { + "name": "MimeType", + "json_name": "mime_type", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. MIME type of the file as defined by the sender" + }, + { + "name": "FileSize", + "json_name": "file_size", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. File size in bytes. It can be bigger than 2^31 and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this value." + }, + { + "name": "Thumbnail", + "json_name": "thumbnail", + "type": { + "kind": "named", + "name": "PhotoSize" + }, + "doc": "Optional. Thumbnail of the album cover to which the music file belongs" + } + ] + }, + { + "name": "Document", + "doc": "This object represents a general file (as opposed to photos, voice messages and audio files).", + "fields": [ + { + "name": "FileID", + "json_name": "file_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Identifier for this file, which can be used to download or reuse the file" + }, + { + "name": "FileUniqueID", + "json_name": "file_unique_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file." + }, + { + "name": "Thumbnail", + "json_name": "thumbnail", + "type": { + "kind": "named", + "name": "PhotoSize" + }, + "doc": "Optional. Document thumbnail as defined by the sender" + }, + { + "name": "FileName", + "json_name": "file_name", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Original filename as defined by the sender" + }, + { + "name": "MimeType", + "json_name": "mime_type", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. MIME type of the file as defined by the sender" + }, + { + "name": "FileSize", + "json_name": "file_size", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. File size in bytes. It can be bigger than 2^31 and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this value." + } + ] + }, + { + "name": "LivePhoto", + "doc": "This object represents a live photo.", + "fields": [ + { + "name": "Photo", + "json_name": "photo", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "PhotoSize" + } + }, + "doc": "Optional. Available sizes of the corresponding static photo" + }, + { + "name": "FileID", + "json_name": "file_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Identifier for the video file which can be used to download or reuse the file" + }, + { + "name": "FileUniqueID", + "json_name": "file_unique_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique identifier for the video file which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file." + }, + { + "name": "Width", + "json_name": "width", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Video width as defined by the sender" + }, + { + "name": "Height", + "json_name": "height", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Video height as defined by the sender" + }, + { + "name": "Duration", + "json_name": "duration", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Duration of the video in seconds as defined by the sender" + }, + { + "name": "MimeType", + "json_name": "mime_type", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. MIME type of the file as defined by the sender" + }, + { + "name": "FileSize", + "json_name": "file_size", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. File size in bytes. It can be bigger than 2^31 and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this value." + } + ] + }, + { + "name": "Story", + "doc": "This object represents a story.", + "fields": [ + { + "name": "Chat", + "json_name": "chat", + "type": { + "kind": "named", + "name": "Chat" + }, + "required": true, + "doc": "Chat that posted the story" + }, + { + "name": "ID", + "json_name": "id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Unique identifier for the story in the chat" + } + ] + }, + { + "name": "VideoQuality", + "doc": "This object represents a video file of a specific quality.", + "fields": [ + { + "name": "FileID", + "json_name": "file_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Identifier for this file, which can be used to download or reuse the file" + }, + { + "name": "FileUniqueID", + "json_name": "file_unique_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file." + }, + { + "name": "Width", + "json_name": "width", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Video width" + }, + { + "name": "Height", + "json_name": "height", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Video height" + }, + { + "name": "Codec", + "json_name": "codec", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Codec that was used to encode the video, for example, “h264”, “h265”, or “av01”" + }, + { + "name": "FileSize", + "json_name": "file_size", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. File size in bytes. It can be bigger than 2^31 and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this value." + } + ] + }, + { + "name": "Video", + "doc": "This object represents a video file.", + "fields": [ + { + "name": "FileID", + "json_name": "file_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Identifier for this file, which can be used to download or reuse the file" + }, + { + "name": "FileUniqueID", + "json_name": "file_unique_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file." + }, + { + "name": "Width", + "json_name": "width", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Video width as defined by the sender" + }, + { + "name": "Height", + "json_name": "height", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Video height as defined by the sender" + }, + { + "name": "Duration", + "json_name": "duration", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Duration of the video in seconds as defined by the sender" + }, + { + "name": "Thumbnail", + "json_name": "thumbnail", + "type": { + "kind": "named", + "name": "PhotoSize" + }, + "doc": "Optional. Video thumbnail" + }, + { + "name": "Cover", + "json_name": "cover", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "PhotoSize" + } + }, + "doc": "Optional. Available sizes of the cover of the video in the message" + }, + { + "name": "StartTimestamp", + "json_name": "start_timestamp", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. Timestamp in seconds from which the video will play in the message" + }, + { + "name": "Qualities", + "json_name": "qualities", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "VideoQuality" + } + }, + "doc": "Optional. List of available qualities of the video" + }, + { + "name": "FileName", + "json_name": "file_name", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Original filename as defined by the sender" + }, + { + "name": "MimeType", + "json_name": "mime_type", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. MIME type of the file as defined by the sender" + }, + { + "name": "FileSize", + "json_name": "file_size", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. File size in bytes. It can be bigger than 2^31 and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this value." + } + ] + }, + { + "name": "VideoNote", + "doc": "This object represents a video message (available in Telegram apps as of v.4.0).", + "fields": [ + { + "name": "FileID", + "json_name": "file_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Identifier for this file, which can be used to download or reuse the file" + }, + { + "name": "FileUniqueID", + "json_name": "file_unique_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file." + }, + { + "name": "Length", + "json_name": "length", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Video width and height (diameter of the video message) as defined by the sender" + }, + { + "name": "Duration", + "json_name": "duration", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Duration of the video in seconds as defined by the sender" + }, + { + "name": "Thumbnail", + "json_name": "thumbnail", + "type": { + "kind": "named", + "name": "PhotoSize" + }, + "doc": "Optional. Video thumbnail" + }, + { + "name": "FileSize", + "json_name": "file_size", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. File size in bytes" + } + ] + }, + { + "name": "Voice", + "doc": "This object represents a voice note.", + "fields": [ + { + "name": "FileID", + "json_name": "file_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Identifier for this file, which can be used to download or reuse the file" + }, + { + "name": "FileUniqueID", + "json_name": "file_unique_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file." + }, + { + "name": "Duration", + "json_name": "duration", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Duration of the audio in seconds as defined by the sender" + }, + { + "name": "MimeType", + "json_name": "mime_type", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. MIME type of the file as defined by the sender" + }, + { + "name": "FileSize", + "json_name": "file_size", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. File size in bytes. It can be bigger than 2^31 and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this value." + } + ] + }, + { + "name": "PaidMediaInfo", + "doc": "Describes the paid media added to a message.", + "fields": [ + { + "name": "StarCount", + "json_name": "star_count", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "The number of Telegram Stars that must be paid to buy access to the media" + }, + { + "name": "PaidMedia", + "json_name": "paid_media", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "PaidMedia" + } + }, + "required": true, + "doc": "Information about the paid media" + } + ] + }, + { + "name": "PaidMedia", + "doc": "This object describes paid media. Currently, it can be one of", + "one_of": [ + "PaidMediaLivePhoto", + "PaidMediaPhoto", + "PaidMediaPreview", + "PaidMediaVideo" + ] + }, + { + "name": "PaidMediaLivePhoto", + "doc": "The paid media is a live photo.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of the paid media, always “live_photo”" + }, + { + "name": "LivePhoto", + "json_name": "live_photo", + "type": { + "kind": "named", + "name": "LivePhoto" + }, + "required": true, + "doc": "The photo" + } + ] + }, + { + "name": "PaidMediaPhoto", + "doc": "The paid media is a photo.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of the paid media, always “photo”" + }, + { + "name": "Photo", + "json_name": "photo", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "PhotoSize" + } + }, + "required": true, + "doc": "The photo" + } + ] + }, + { + "name": "PaidMediaPreview", + "doc": "The paid media isn't available before the payment.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of the paid media, always “preview”" + }, + { + "name": "Width", + "json_name": "width", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. Media width as defined by the sender" + }, + { + "name": "Height", + "json_name": "height", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. Media height as defined by the sender" + }, + { + "name": "Duration", + "json_name": "duration", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. Duration of the media in seconds as defined by the sender" + } + ] + }, + { + "name": "PaidMediaVideo", + "doc": "The paid media is a video.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of the paid media, always “video”" + }, + { + "name": "Video", + "json_name": "video", + "type": { + "kind": "named", + "name": "Video" + }, + "required": true, + "doc": "The video" + } + ] + }, + { + "name": "Contact", + "doc": "This object represents a phone contact.", + "fields": [ + { + "name": "PhoneNumber", + "json_name": "phone_number", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Contact's phone number" + }, + { + "name": "FirstName", + "json_name": "first_name", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Contact's first name" + }, + { + "name": "LastName", + "json_name": "last_name", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Contact's last name" + }, + { + "name": "UserID", + "json_name": "user_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. Contact's user identifier in Telegram. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a 64-bit integer or double-precision float type are safe for storing this identifier." + }, + { + "name": "Vcard", + "json_name": "vcard", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Additional data about the contact in the form of a vCard" + } + ] + }, + { + "name": "Dice", + "doc": "This object represents an animated emoji that displays a random value.", + "fields": [ + { + "name": "Emoji", + "json_name": "emoji", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Emoji on which the dice throw animation is based" + }, + { + "name": "Value", + "json_name": "value", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Value of the dice, 1-6 for “”, “” and “” base emoji, 1-5 for “” and “” base emoji, 1-64 for “” base emoji" + } + ] + }, + { + "name": "PollMedia", + "doc": "At most one of the optional fields can be present in any given object.", + "fields": [ + { + "name": "Animation", + "json_name": "animation", + "type": { + "kind": "named", + "name": "Animation" + }, + "doc": "Optional. Media is an animation, information about the animation" + }, + { + "name": "Audio", + "json_name": "audio", + "type": { + "kind": "named", + "name": "Audio" + }, + "doc": "Optional. Media is an audio file, information about the file; currently, can't be received in a poll option" + }, + { + "name": "Document", + "json_name": "document", + "type": { + "kind": "named", + "name": "Document" + }, + "doc": "Optional. Media is a general file, information about the file; currently, can't be received in a poll option" + }, + { + "name": "LivePhoto", + "json_name": "live_photo", + "type": { + "kind": "named", + "name": "LivePhoto" + }, + "doc": "Optional. Media is a live photo, information about the live photo" + }, + { + "name": "Location", + "json_name": "location", + "type": { + "kind": "named", + "name": "Location" + }, + "doc": "Optional. Media is a shared location, information about the location" + }, + { + "name": "Photo", + "json_name": "photo", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "PhotoSize" + } + }, + "doc": "Optional. Media is a photo, available sizes of the photo" + }, + { + "name": "Sticker", + "json_name": "sticker", + "type": { + "kind": "named", + "name": "Sticker" + }, + "doc": "Optional. Media is a sticker, information about the sticker; currently, for poll options only" + }, + { + "name": "Venue", + "json_name": "venue", + "type": { + "kind": "named", + "name": "Venue" + }, + "doc": "Optional. Media is a venue, information about the venue" + }, + { + "name": "Video", + "json_name": "video", + "type": { + "kind": "named", + "name": "Video" + }, + "doc": "Optional. Media is a video, information about the video" + } + ] + }, + { + "name": "InputPollMedia", + "doc": "This object represents the content of a poll description or a quiz explanation to be sent. It should be one of", + "one_of": [ + "InputMediaAnimation", + "InputMediaAudio", + "InputMediaDocument", + "InputMediaLivePhoto", + "InputMediaLocation", + "InputMediaPhoto", + "InputMediaVenue", + "InputMediaVideo" + ] + }, + { + "name": "InputPollOptionMedia", + "doc": "This object represents the content of a poll option to be sent. It should be one of", + "one_of": [ + "InputMediaAnimation", + "InputMediaLivePhoto", + "InputMediaLocation", + "InputMediaPhoto", + "InputMediaSticker", + "InputMediaVenue", + "InputMediaVideo" + ] + }, + { + "name": "PollOption", + "doc": "This object contains information about one answer option in a poll.", + "fields": [ + { + "name": "PersistentID", + "json_name": "persistent_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique identifier of the option, persistent on option addition and deletion" + }, + { + "name": "Text", + "json_name": "text", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Option text, 1-100 characters" + }, + { + "name": "TextEntities", + "json_name": "text_entities", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "MessageEntity" + } + }, + "doc": "Optional. Special entities that appear in the option text. Currently, only custom emoji entities are allowed in poll option texts" + }, + { + "name": "Media", + "json_name": "media", + "type": { + "kind": "named", + "name": "PollMedia" + }, + "doc": "Optional. Media added to the poll option" + }, + { + "name": "VoterCount", + "json_name": "voter_count", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Number of users who voted for this option; may be 0 if unknown" + }, + { + "name": "AddedByUser", + "json_name": "added_by_user", + "type": { + "kind": "named", + "name": "User" + }, + "doc": "Optional. User who added the option; omitted if the option wasn't added by a user after poll creation" + }, + { + "name": "AddedByChat", + "json_name": "added_by_chat", + "type": { + "kind": "named", + "name": "Chat" + }, + "doc": "Optional. Chat that added the option; omitted if the option wasn't added by a chat after poll creation" + }, + { + "name": "AdditionDate", + "json_name": "addition_date", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. Point in time (Unix timestamp) when the option was added; omitted if the option existed in the original poll" + } + ] + }, + { + "name": "InputPollOption", + "doc": "This object contains information about one answer option in a poll to be sent.", + "fields": [ + { + "name": "Text", + "json_name": "text", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Option text, 1-100 characters" + }, + { + "name": "TextParseMode", + "json_name": "text_parse_mode", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Mode for parsing entities in the text. See formatting options for more details. Currently, only custom emoji entities are allowed" + }, + { + "name": "TextEntities", + "json_name": "text_entities", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "MessageEntity" + } + }, + "doc": "Optional. A JSON-serialized list of special entities that appear in the poll option text. It can be specified instead of text_parse_mode" + }, + { + "name": "Media", + "json_name": "media", + "type": { + "kind": "named", + "name": "InputPollOptionMedia" + }, + "doc": "Optional. Media added to the poll option" + } + ] + }, + { + "name": "PollAnswer", + "doc": "This object represents an answer of a user in a non-anonymous poll.", + "fields": [ + { + "name": "PollID", + "json_name": "poll_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique poll identifier" + }, + { + "name": "VoterChat", + "json_name": "voter_chat", + "type": { + "kind": "named", + "name": "Chat" + }, + "doc": "Optional. The chat that changed the answer to the poll, if the voter is anonymous" + }, + { + "name": "User", + "json_name": "user", + "type": { + "kind": "named", + "name": "User" + }, + "doc": "Optional. The user that changed the answer to the poll, if the voter isn't anonymous" + }, + { + "name": "OptionIds", + "json_name": "option_ids", + "type": { + "kind": "array", + "elem_type": { + "kind": "primitive", + "name": "int64" + } + }, + "required": true, + "doc": "0-based identifiers of chosen answer options. May be empty if the vote was retracted." + }, + { + "name": "OptionPersistentIds", + "json_name": "option_persistent_ids", + "type": { + "kind": "array", + "elem_type": { + "kind": "primitive", + "name": "string" + } + }, + "required": true, + "doc": "Persistent identifiers of the chosen answer options. May be empty if the vote was retracted." + } + ] + }, + { + "name": "Poll", + "doc": "This object contains information about a poll.", + "fields": [ + { + "name": "ID", + "json_name": "id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique poll identifier" + }, + { + "name": "Question", + "json_name": "question", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Poll question, 1-300 characters" + }, + { + "name": "QuestionEntities", + "json_name": "question_entities", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "MessageEntity" + } + }, + "doc": "Optional. Special entities that appear in the question. Currently, only custom emoji entities are allowed in poll questions" + }, + { + "name": "Options", + "json_name": "options", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "PollOption" + } + }, + "required": true, + "doc": "List of poll options" + }, + { + "name": "TotalVoterCount", + "json_name": "total_voter_count", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Total number of users that voted in the poll" + }, + { + "name": "IsClosed", + "json_name": "is_closed", + "type": { + "kind": "primitive", + "name": "bool" + }, + "required": true, + "doc": "True, if the poll is closed" + }, + { + "name": "IsAnonymous", + "json_name": "is_anonymous", + "type": { + "kind": "primitive", + "name": "bool" + }, + "required": true, + "doc": "True, if the poll is anonymous" + }, + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Poll type, currently can be “regular” or “quiz”" + }, + { + "name": "AllowsMultipleAnswers", + "json_name": "allows_multiple_answers", + "type": { + "kind": "primitive", + "name": "bool" + }, + "required": true, + "doc": "True, if the poll allows multiple answers" + }, + { + "name": "AllowsRevoting", + "json_name": "allows_revoting", + "type": { + "kind": "primitive", + "name": "bool" + }, + "required": true, + "doc": "True, if the poll allows to change the chosen answer options" + }, + { + "name": "MembersOnly", + "json_name": "members_only", + "type": { + "kind": "primitive", + "name": "bool" + }, + "required": true, + "doc": "True if voting is limited to users who have been members of the chat where the poll was originally sent for more than 24 hours" + }, + { + "name": "CountryCodes", + "json_name": "country_codes", + "type": { + "kind": "array", + "elem_type": { + "kind": "primitive", + "name": "string" + } + }, + "doc": "Optional. A list of two-letter ISO 3166-1 alpha-2 country codes indicating the countries from which users can vote in the poll. If omitted, then users from any country can participate in the poll." + }, + { + "name": "CorrectOptionIds", + "json_name": "correct_option_ids", + "type": { + "kind": "array", + "elem_type": { + "kind": "primitive", + "name": "int64" + } + }, + "doc": "Optional. Array of 0-based identifiers of the correct answer options. Available only for polls in quiz mode which are closed or were sent (not forwarded) by the bot or to the private chat with the bot." + }, + { + "name": "Explanation", + "json_name": "explanation", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Text that is shown when a user chooses an incorrect answer or taps on the lamp icon in a quiz-style poll, 0-200 characters" + }, + { + "name": "ExplanationEntities", + "json_name": "explanation_entities", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "MessageEntity" + } + }, + "doc": "Optional. Special entities like usernames, URLs, bot commands, etc. that appear in the explanation" + }, + { + "name": "ExplanationMedia", + "json_name": "explanation_media", + "type": { + "kind": "named", + "name": "PollMedia" + }, + "doc": "Optional. Media added to the quiz explanation" + }, + { + "name": "OpenPeriod", + "json_name": "open_period", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. Amount of time in seconds the poll will be active after creation" + }, + { + "name": "CloseDate", + "json_name": "close_date", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. Point in time (Unix timestamp) when the poll will be automatically closed" + }, + { + "name": "Description", + "json_name": "description", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Description of the poll; for polls inside the Message object only" + }, + { + "name": "DescriptionEntities", + "json_name": "description_entities", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "MessageEntity" + } + }, + "doc": "Optional. Special entities like usernames, URLs, bot commands, etc. that appear in the description" + }, + { + "name": "Media", + "json_name": "media", + "type": { + "kind": "named", + "name": "PollMedia" + }, + "doc": "Optional. Media added to the poll description; for polls inside the Message object only" + } + ] + }, + { + "name": "ChecklistTask", + "doc": "Describes a task in a checklist.", + "fields": [ + { + "name": "ID", + "json_name": "id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Unique identifier of the task" + }, + { + "name": "Text", + "json_name": "text", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Text of the task" + }, + { + "name": "TextEntities", + "json_name": "text_entities", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "MessageEntity" + } + }, + "doc": "Optional. Special entities that appear in the task text" + }, + { + "name": "CompletedByUser", + "json_name": "completed_by_user", + "type": { + "kind": "named", + "name": "User" + }, + "doc": "Optional. User that completed the task; omitted if the task wasn't completed by a user" + }, + { + "name": "CompletedByChat", + "json_name": "completed_by_chat", + "type": { + "kind": "named", + "name": "Chat" + }, + "doc": "Optional. Chat that completed the task; omitted if the task wasn't completed by a chat" + }, + { + "name": "CompletionDate", + "json_name": "completion_date", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. Point in time (Unix timestamp) when the task was completed; 0 if the task wasn't completed" + } + ] + }, + { + "name": "Checklist", + "doc": "Describes a checklist.", + "fields": [ + { + "name": "Title", + "json_name": "title", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Title of the checklist" + }, + { + "name": "TitleEntities", + "json_name": "title_entities", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "MessageEntity" + } + }, + "doc": "Optional. Special entities that appear in the checklist title" + }, + { + "name": "Tasks", + "json_name": "tasks", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "ChecklistTask" + } + }, + "required": true, + "doc": "List of tasks in the checklist" + }, + { + "name": "OthersCanAddTasks", + "json_name": "others_can_add_tasks", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if users other than the creator of the list can add tasks to the list" + }, + { + "name": "OthersCanMarkTasksAsDone", + "json_name": "others_can_mark_tasks_as_done", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if users other than the creator of the list can mark tasks as done or not done" + } + ] + }, + { + "name": "InputChecklistTask", + "doc": "Describes a task to add to a checklist.", + "fields": [ + { + "name": "ID", + "json_name": "id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Unique identifier of the task; must be positive and unique among all task identifiers currently present in the checklist" + }, + { + "name": "Text", + "json_name": "text", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Text of the task; 1-100 characters after entities parsing" + }, + { + "name": "ParseMode", + "json_name": "parse_mode", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Mode for parsing entities in the text. See formatting options for more details." + }, + { + "name": "TextEntities", + "json_name": "text_entities", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "MessageEntity" + } + }, + "doc": "Optional. List of special entities that appear in the text, which can be specified instead of parse_mode. Currently, only bold, italic, underline, strikethrough, spoiler, custom_emoji, and date_time entities are allowed." + } + ] + }, + { + "name": "InputChecklist", + "doc": "Describes a checklist to create.", + "fields": [ + { + "name": "Title", + "json_name": "title", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Title of the checklist; 1-255 characters after entities parsing" + }, + { + "name": "ParseMode", + "json_name": "parse_mode", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Mode for parsing entities in the title. See formatting options for more details." + }, + { + "name": "TitleEntities", + "json_name": "title_entities", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "MessageEntity" + } + }, + "doc": "Optional. List of special entities that appear in the title, which can be specified instead of parse_mode. Currently, only bold, italic, underline, strikethrough, spoiler, custom_emoji, and date_time entities are allowed." + }, + { + "name": "Tasks", + "json_name": "tasks", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "InputChecklistTask" + } + }, + "required": true, + "doc": "List of 1-30 tasks in the checklist" + }, + { + "name": "OthersCanAddTasks", + "json_name": "others_can_add_tasks", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. Pass True if other users can add tasks to the checklist" + }, + { + "name": "OthersCanMarkTasksAsDone", + "json_name": "others_can_mark_tasks_as_done", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. Pass True if other users can mark tasks as done or not done in the checklist" + } + ] + }, + { + "name": "ChecklistTasksDone", + "doc": "Describes a service message about checklist tasks marked as done or not done.", + "fields": [ + { + "name": "ChecklistMessage", + "json_name": "checklist_message", + "type": { + "kind": "named", + "name": "Message" + }, + "doc": "Optional. Message containing the checklist whose tasks were marked as done or not done. Note that the Message object in this field will not contain the reply_to_message field even if it itself is a reply." + }, + { + "name": "MarkedAsDoneTaskIds", + "json_name": "marked_as_done_task_ids", + "type": { + "kind": "array", + "elem_type": { + "kind": "primitive", + "name": "int64" + } + }, + "doc": "Optional. Identifiers of the tasks that were marked as done" + }, + { + "name": "MarkedAsNotDoneTaskIds", + "json_name": "marked_as_not_done_task_ids", + "type": { + "kind": "array", + "elem_type": { + "kind": "primitive", + "name": "int64" + } + }, + "doc": "Optional. Identifiers of the tasks that were marked as not done" + } + ] + }, + { + "name": "ChecklistTasksAdded", + "doc": "Describes a service message about tasks added to a checklist.", + "fields": [ + { + "name": "ChecklistMessage", + "json_name": "checklist_message", + "type": { + "kind": "named", + "name": "Message" + }, + "doc": "Optional. Message containing the checklist to which the tasks were added. Note that the Message object in this field will not contain the reply_to_message field even if it itself is a reply." + }, + { + "name": "Tasks", + "json_name": "tasks", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "ChecklistTask" + } + }, + "required": true, + "doc": "List of tasks added to the checklist" + } + ] + }, + { + "name": "Location", + "doc": "This object represents a point on the map.", + "fields": [ + { + "name": "Latitude", + "json_name": "latitude", + "type": { + "kind": "primitive", + "name": "float64" + }, + "required": true, + "doc": "Latitude as defined by the sender" + }, + { + "name": "Longitude", + "json_name": "longitude", + "type": { + "kind": "primitive", + "name": "float64" + }, + "required": true, + "doc": "Longitude as defined by the sender" + }, + { + "name": "HorizontalAccuracy", + "json_name": "horizontal_accuracy", + "type": { + "kind": "primitive", + "name": "float64" + }, + "doc": "Optional. The radius of uncertainty for the location, measured in meters; 0-1500" + }, + { + "name": "LivePeriod", + "json_name": "live_period", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. Time relative to the message sending date, during which the location can be updated; in seconds. For active live locations only." + }, + { + "name": "Heading", + "json_name": "heading", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. The direction in which user is moving, in degrees; 1-360. For active live locations only." + }, + { + "name": "ProximityAlertRadius", + "json_name": "proximity_alert_radius", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. The maximum distance for proximity alerts about approaching another chat member, in meters. For sent live locations only." + } + ] + }, + { + "name": "Venue", + "doc": "This object represents a venue.", + "fields": [ + { + "name": "Location", + "json_name": "location", + "type": { + "kind": "named", + "name": "Location" + }, + "required": true, + "doc": "Venue location. Can't be a live location" + }, + { + "name": "Title", + "json_name": "title", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Name of the venue" + }, + { + "name": "Address", + "json_name": "address", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Address of the venue" + }, + { + "name": "FoursquareID", + "json_name": "foursquare_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Foursquare identifier of the venue" + }, + { + "name": "FoursquareType", + "json_name": "foursquare_type", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Foursquare type of the venue. (For example, “arts_entertainment/default”, “arts_entertainment/aquarium” or “food/icecream”.)" + }, + { + "name": "GooglePlaceID", + "json_name": "google_place_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Google Places identifier of the venue" + }, + { + "name": "GooglePlaceType", + "json_name": "google_place_type", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Google Places type of the venue. (See supported types.)" + } + ] + }, + { + "name": "WebAppData", + "doc": "Describes data sent from a Web App to the bot.", + "fields": [ + { + "name": "Data", + "json_name": "data", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "The data. Be aware that a bad client can send arbitrary data in this field." + }, + { + "name": "ButtonText", + "json_name": "button_text", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Text of the web_app keyboard button from which the Web App was opened. Be aware that a bad client can send arbitrary data in this field." + } + ] + }, + { + "name": "ProximityAlertTriggered", + "doc": "This object represents the content of a service message, sent whenever a user in the chat triggers a proximity alert set by another user.", + "fields": [ + { + "name": "Traveler", + "json_name": "traveler", + "type": { + "kind": "named", + "name": "User" + }, + "required": true, + "doc": "User that triggered the alert" + }, + { + "name": "Watcher", + "json_name": "watcher", + "type": { + "kind": "named", + "name": "User" + }, + "required": true, + "doc": "User that set the alert" + }, + { + "name": "Distance", + "json_name": "distance", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "The distance between the users" + } + ] + }, + { + "name": "MessageAutoDeleteTimerChanged", + "doc": "This object represents a service message about a change in auto-delete timer settings.", + "fields": [ + { + "name": "MessageAutoDeleteTime", + "json_name": "message_auto_delete_time", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "New auto-delete time for messages in the chat; in seconds" + } + ] + }, + { + "name": "ManagedBotCreated", + "doc": "This object contains information about the bot that was created to be managed by the current bot.", + "fields": [ + { + "name": "Bot", + "json_name": "bot", + "type": { + "kind": "named", + "name": "User" + }, + "required": true, + "doc": "Information about the bot. The bot's token can be fetched using the method getManagedBotToken." + } + ] + }, + { + "name": "ManagedBotUpdated", + "doc": "This object contains information about the creation, token update, or owner update of a bot that is managed by the current bot.", + "fields": [ + { + "name": "User", + "json_name": "user", + "type": { + "kind": "named", + "name": "User" + }, + "required": true, + "doc": "User that created the bot" + }, + { + "name": "Bot", + "json_name": "bot", + "type": { + "kind": "named", + "name": "User" + }, + "required": true, + "doc": "Information about the bot. Token of the bot can be fetched using the method getManagedBotToken." + } + ] + }, + { + "name": "PollOptionAdded", + "doc": "Describes a service message about an option added to a poll.", + "fields": [ + { + "name": "PollMessage", + "json_name": "poll_message", + "type": { + "kind": "named", + "name": "MaybeInaccessibleMessage" + }, + "doc": "Optional. Message containing the poll to which the option was added, if known. Note that the Message object in this field will not contain the reply_to_message field even if it itself is a reply." + }, + { + "name": "OptionPersistentID", + "json_name": "option_persistent_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique identifier of the added option" + }, + { + "name": "OptionText", + "json_name": "option_text", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Option text" + }, + { + "name": "OptionTextEntities", + "json_name": "option_text_entities", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "MessageEntity" + } + }, + "doc": "Optional. Special entities that appear in the option_text" + } + ] + }, + { + "name": "PollOptionDeleted", + "doc": "Describes a service message about an option deleted from a poll.", + "fields": [ + { + "name": "PollMessage", + "json_name": "poll_message", + "type": { + "kind": "named", + "name": "MaybeInaccessibleMessage" + }, + "doc": "Optional. Message containing the poll from which the option was deleted, if known. Note that the Message object in this field will not contain the reply_to_message field even if it itself is a reply." + }, + { + "name": "OptionPersistentID", + "json_name": "option_persistent_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique identifier of the deleted option" + }, + { + "name": "OptionText", + "json_name": "option_text", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Option text" + }, + { + "name": "OptionTextEntities", + "json_name": "option_text_entities", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "MessageEntity" + } + }, + "doc": "Optional. Special entities that appear in the option_text" + } + ] + }, + { + "name": "ChatBoostAdded", + "doc": "This object represents a service message about a user boosting a chat.", + "fields": [ + { + "name": "BoostCount", + "json_name": "boost_count", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Number of boosts added by the user" + } + ] + }, + { + "name": "BackgroundFill", + "doc": "This object describes the way a background is filled based on the selected colors. Currently, it can be one of", + "one_of": [ + "BackgroundFillSolid", + "BackgroundFillGradient", + "BackgroundFillFreeformGradient" + ] + }, + { + "name": "BackgroundFillSolid", + "doc": "The background is filled using the selected color.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of the background fill, always “solid”" + }, + { + "name": "Color", + "json_name": "color", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "The color of the background fill in the RGB24 format" + } + ] + }, + { + "name": "BackgroundFillGradient", + "doc": "The background is a gradient fill.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of the background fill, always “gradient”" + }, + { + "name": "TopColor", + "json_name": "top_color", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Top color of the gradient in the RGB24 format" + }, + { + "name": "BottomColor", + "json_name": "bottom_color", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Bottom color of the gradient in the RGB24 format" + }, + { + "name": "RotationAngle", + "json_name": "rotation_angle", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Clockwise rotation angle of the background fill in degrees; 0-359" + } + ] + }, + { + "name": "BackgroundFillFreeformGradient", + "doc": "The background is a freeform gradient that rotates after every message in the chat.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of the background fill, always “freeform_gradient”" + }, + { + "name": "Colors", + "json_name": "colors", + "type": { + "kind": "array", + "elem_type": { + "kind": "primitive", + "name": "int64" + } + }, + "required": true, + "doc": "A list of the 3 or 4 base colors that are used to generate the freeform gradient in the RGB24 format" + } + ] + }, + { + "name": "BackgroundType", + "doc": "This object describes the type of a background. Currently, it can be one of", + "one_of": [ + "BackgroundTypeFill", + "BackgroundTypeWallpaper", + "BackgroundTypePattern", + "BackgroundTypeChatTheme" + ] + }, + { + "name": "BackgroundTypeFill", + "doc": "The background is automatically filled based on the selected colors.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of the background, always “fill”" + }, + { + "name": "Fill", + "json_name": "fill", + "type": { + "kind": "named", + "name": "BackgroundFill" + }, + "required": true, + "doc": "The background fill" + }, + { + "name": "DarkThemeDimming", + "json_name": "dark_theme_dimming", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Dimming of the background in dark themes, as a percentage; 0-100" + } + ] + }, + { + "name": "BackgroundTypeWallpaper", + "doc": "The background is a wallpaper in the JPEG format.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of the background, always “wallpaper”" + }, + { + "name": "Document", + "json_name": "document", + "type": { + "kind": "named", + "name": "Document" + }, + "required": true, + "doc": "Document with the wallpaper" + }, + { + "name": "DarkThemeDimming", + "json_name": "dark_theme_dimming", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Dimming of the background in dark themes, as a percentage; 0-100" + }, + { + "name": "IsBlurred", + "json_name": "is_blurred", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the wallpaper is downscaled to fit in a 450x450 square and then box-blurred with radius 12" + }, + { + "name": "IsMoving", + "json_name": "is_moving", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the background moves slightly when the device is tilted" + } + ] + }, + { + "name": "BackgroundTypePattern", + "doc": "The background is a .PNG or .TGV (gzipped subset of SVG with MIME type “application/x-tgwallpattern”) pattern to be combined with the background fill chosen by the user.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of the background, always “pattern”" + }, + { + "name": "Document", + "json_name": "document", + "type": { + "kind": "named", + "name": "Document" + }, + "required": true, + "doc": "Document with the pattern" + }, + { + "name": "Fill", + "json_name": "fill", + "type": { + "kind": "named", + "name": "BackgroundFill" + }, + "required": true, + "doc": "The background fill that is combined with the pattern" + }, + { + "name": "Intensity", + "json_name": "intensity", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Intensity of the pattern when it is shown above the filled background; 0-100" + }, + { + "name": "IsInverted", + "json_name": "is_inverted", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the background fill must be applied only to the pattern itself. All other pixels are black in this case. For dark themes only" + }, + { + "name": "IsMoving", + "json_name": "is_moving", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the background moves slightly when the device is tilted" + } + ] + }, + { + "name": "BackgroundTypeChatTheme", + "doc": "The background is taken directly from a built-in chat theme.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of the background, always “chat_theme”" + }, + { + "name": "ThemeName", + "json_name": "theme_name", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Name of the chat theme, which is usually an emoji" + } + ] + }, + { + "name": "ChatBackground", + "doc": "This object represents a chat background.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "named", + "name": "BackgroundType" + }, + "required": true, + "doc": "Type of the background" + } + ] + }, + { + "name": "ForumTopicCreated", + "doc": "This object represents a service message about a new forum topic created in the chat.", + "fields": [ + { + "name": "Name", + "json_name": "name", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Name of the topic" + }, + { + "name": "IconColor", + "json_name": "icon_color", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Color of the topic icon in RGB format" + }, + { + "name": "IconCustomEmojiID", + "json_name": "icon_custom_emoji_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Unique identifier of the custom emoji shown as the topic icon" + }, + { + "name": "IsNameImplicit", + "json_name": "is_name_implicit", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the name of the topic wasn't specified explicitly by its creator and likely needs to be changed by the bot" + } + ] + }, + { + "name": "ForumTopicClosed", + "doc": "This object represents a service message about a forum topic closed in the chat. Currently holds no information." + }, + { + "name": "ForumTopicEdited", + "doc": "This object represents a service message about an edited forum topic.", + "fields": [ + { + "name": "Name", + "json_name": "name", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. New name of the topic, if it was edited" + }, + { + "name": "IconCustomEmojiID", + "json_name": "icon_custom_emoji_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. New identifier of the custom emoji shown as the topic icon, if it was edited; an empty string if the icon was removed" + } + ] + }, + { + "name": "ForumTopicReopened", + "doc": "This object represents a service message about a forum topic reopened in the chat. Currently holds no information." + }, + { + "name": "GeneralForumTopicHidden", + "doc": "This object represents a service message about General forum topic hidden in the chat. Currently holds no information." + }, + { + "name": "GeneralForumTopicUnhidden", + "doc": "This object represents a service message about General forum topic unhidden in the chat. Currently holds no information." + }, + { + "name": "SharedUser", + "doc": "This object contains information about a user that was shared with the bot using a KeyboardButtonRequestUsers button.", + "fields": [ + { + "name": "UserID", + "json_name": "user_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Identifier of the shared user. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so 64-bit integers or double-precision float types are safe for storing these identifiers. The bot may not have access to the user and could be unable to use this identifier, unless the user is already known to the bot by some other means." + }, + { + "name": "FirstName", + "json_name": "first_name", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. First name of the user, if the name was requested by the bot" + }, + { + "name": "LastName", + "json_name": "last_name", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Last name of the user, if the name was requested by the bot" + }, + { + "name": "Username", + "json_name": "username", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Username of the user, if the username was requested by the bot" + }, + { + "name": "Photo", + "json_name": "photo", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "PhotoSize" + } + }, + "doc": "Optional. Available sizes of the chat photo, if the photo was requested by the bot" + } + ] + }, + { + "name": "UsersShared", + "doc": "This object contains information about the users whose identifiers were shared with the bot using a KeyboardButtonRequestUsers button.", + "fields": [ + { + "name": "RequestID", + "json_name": "request_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Identifier of the request" + }, + { + "name": "Users", + "json_name": "users", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "SharedUser" + } + }, + "required": true, + "doc": "Information about users shared with the bot." + } + ] + }, + { + "name": "ChatShared", + "doc": "This object contains information about a chat that was shared with the bot using a KeyboardButtonRequestChat button.", + "fields": [ + { + "name": "RequestID", + "json_name": "request_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Identifier of the request" + }, + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Identifier of the shared chat. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a 64-bit integer or double-precision float type are safe for storing this identifier. The bot may not have access to the chat and could be unable to use this identifier, unless the chat is already known to the bot by some other means." + }, + { + "name": "Title", + "json_name": "title", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Title of the chat, if the title was requested by the bot." + }, + { + "name": "Username", + "json_name": "username", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Username of the chat, if the username was requested by the bot and available." + }, + { + "name": "Photo", + "json_name": "photo", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "PhotoSize" + } + }, + "doc": "Optional. Available sizes of the chat photo, if the photo was requested by the bot" + } + ] + }, + { + "name": "WriteAccessAllowed", + "doc": "This object represents a service message about a user allowing a bot to write messages after adding it to the attachment menu, launching a Web App from a link, or accepting an explicit request from a Web App sent by the method requestWriteAccess.", + "fields": [ + { + "name": "FromRequest", + "json_name": "from_request", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the access was granted after the user accepted an explicit request from a Web App sent by the method requestWriteAccess" + }, + { + "name": "WebAppName", + "json_name": "web_app_name", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Name of the Web App, if the access was granted when the Web App was launched from a link" + }, + { + "name": "FromAttachmentMenu", + "json_name": "from_attachment_menu", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the access was granted when the bot was added to the attachment or side menu" + } + ] + }, + { + "name": "VideoChatScheduled", + "doc": "This object represents a service message about a video chat scheduled in the chat.", + "fields": [ + { + "name": "StartDate", + "json_name": "start_date", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Point in time (Unix timestamp) when the video chat is supposed to be started by a chat administrator" + } + ] + }, + { + "name": "VideoChatStarted", + "doc": "This object represents a service message about a video chat started in the chat. Currently holds no information." + }, + { + "name": "VideoChatEnded", + "doc": "This object represents a service message about a video chat ended in the chat.", + "fields": [ + { + "name": "Duration", + "json_name": "duration", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Video chat duration in seconds" + } + ] + }, + { + "name": "VideoChatParticipantsInvited", + "doc": "This object represents a service message about new members invited to a video chat.", + "fields": [ + { + "name": "Users", + "json_name": "users", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "User" + } + }, + "required": true, + "doc": "New members that were invited to the video chat" + } + ] + }, + { + "name": "PaidMessagePriceChanged", + "doc": "Describes a service message about a change in the price of paid messages within a chat.", + "fields": [ + { + "name": "PaidMessageStarCount", + "json_name": "paid_message_star_count", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "The new number of Telegram Stars that must be paid by non-administrator users of the supergroup chat for each sent message" + } + ] + }, + { + "name": "DirectMessagePriceChanged", + "doc": "Describes a service message about a change in the price of direct messages sent to a channel chat.", + "fields": [ + { + "name": "AreDirectMessagesEnabled", + "json_name": "are_direct_messages_enabled", + "type": { + "kind": "primitive", + "name": "bool" + }, + "required": true, + "doc": "True, if direct messages are enabled for the channel chat; false otherwise" + }, + { + "name": "DirectMessageStarCount", + "json_name": "direct_message_star_count", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. The new number of Telegram Stars that must be paid by users for each direct message sent to the channel. Does not apply to users who have been exempted by administrators. Defaults to 0." + } + ] + }, + { + "name": "SuggestedPostApproved", + "doc": "Describes a service message about the approval of a suggested post.", + "fields": [ + { + "name": "SuggestedPostMessage", + "json_name": "suggested_post_message", + "type": { + "kind": "named", + "name": "Message" + }, + "doc": "Optional. Message containing the suggested post. Note that the Message object in this field will not contain the reply_to_message field even if it itself is a reply." + }, + { + "name": "Price", + "json_name": "price", + "type": { + "kind": "named", + "name": "SuggestedPostPrice" + }, + "doc": "Optional. Amount paid for the post" + }, + { + "name": "SendDate", + "json_name": "send_date", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Date when the post will be published" + } + ] + }, + { + "name": "SuggestedPostApprovalFailed", + "doc": "Describes a service message about the failed approval of a suggested post. Currently, only caused by insufficient user funds at the time of approval.", + "fields": [ + { + "name": "SuggestedPostMessage", + "json_name": "suggested_post_message", + "type": { + "kind": "named", + "name": "Message" + }, + "doc": "Optional. Message containing the suggested post whose approval has failed. Note that the Message object in this field will not contain the reply_to_message field even if it itself is a reply." + }, + { + "name": "Price", + "json_name": "price", + "type": { + "kind": "named", + "name": "SuggestedPostPrice" + }, + "required": true, + "doc": "Expected price of the post" + } + ] + }, + { + "name": "SuggestedPostDeclined", + "doc": "Describes a service message about the rejection of a suggested post.", + "fields": [ + { + "name": "SuggestedPostMessage", + "json_name": "suggested_post_message", + "type": { + "kind": "named", + "name": "Message" + }, + "doc": "Optional. Message containing the suggested post. Note that the Message object in this field will not contain the reply_to_message field even if it itself is a reply." + }, + { + "name": "Comment", + "json_name": "comment", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Comment with which the post was declined" + } + ] + }, + { + "name": "SuggestedPostPaid", + "doc": "Describes a service message about a successful payment for a suggested post.", + "fields": [ + { + "name": "SuggestedPostMessage", + "json_name": "suggested_post_message", + "type": { + "kind": "named", + "name": "Message" + }, + "doc": "Optional. Message containing the suggested post. Note that the Message object in this field will not contain the reply_to_message field even if it itself is a reply." + }, + { + "name": "Currency", + "json_name": "currency", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Currency in which the payment was made. Currently, one of “XTR” for Telegram Stars or “TON” for toncoins" + }, + { + "name": "Amount", + "json_name": "amount", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. The amount of the currency that was received by the channel in nanotoncoins; for payments in toncoins only" + }, + { + "name": "StarAmount", + "json_name": "star_amount", + "type": { + "kind": "named", + "name": "StarAmount" + }, + "doc": "Optional. The amount of Telegram Stars that was received by the channel; for payments in Telegram Stars only" + } + ] + }, + { + "name": "SuggestedPostRefunded", + "doc": "Describes a service message about a payment refund for a suggested post.", + "fields": [ + { + "name": "SuggestedPostMessage", + "json_name": "suggested_post_message", + "type": { + "kind": "named", + "name": "Message" + }, + "doc": "Optional. Message containing the suggested post. Note that the Message object in this field will not contain the reply_to_message field even if it itself is a reply." + }, + { + "name": "Reason", + "json_name": "reason", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Reason for the refund. Currently, one of “post_deleted” if the post was deleted within 24 hours of being posted or removed from scheduled messages without being posted, or “payment_refunded” if the payer refunded their payment." + } + ] + }, + { + "name": "GiveawayCreated", + "doc": "This object represents a service message about the creation of a scheduled giveaway.", + "fields": [ + { + "name": "PrizeStarCount", + "json_name": "prize_star_count", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. The number of Telegram Stars to be split between giveaway winners; for Telegram Star giveaways only" + } + ] + }, + { + "name": "Giveaway", + "doc": "This object represents a message about a scheduled giveaway.", + "fields": [ + { + "name": "Chats", + "json_name": "chats", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "Chat" + } + }, + "required": true, + "doc": "The list of chats which the user must join to participate in the giveaway" + }, + { + "name": "WinnersSelectionDate", + "json_name": "winners_selection_date", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Point in time (Unix timestamp) when winners of the giveaway will be selected" + }, + { + "name": "WinnerCount", + "json_name": "winner_count", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "The number of users which are supposed to be selected as winners of the giveaway" + }, + { + "name": "OnlyNewMembers", + "json_name": "only_new_members", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if only users who join the chats after the giveaway started should be eligible to win" + }, + { + "name": "HasPublicWinners", + "json_name": "has_public_winners", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the list of giveaway winners will be visible to everyone" + }, + { + "name": "PrizeDescription", + "json_name": "prize_description", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Description of additional giveaway prize" + }, + { + "name": "CountryCodes", + "json_name": "country_codes", + "type": { + "kind": "array", + "elem_type": { + "kind": "primitive", + "name": "string" + } + }, + "doc": "Optional. A list of two-letter ISO 3166-1 alpha-2 country codes indicating the countries from which eligible users for the giveaway must come. If empty, then all users can participate in the giveaway. Users with a phone number that was bought on Fragment can always participate in giveaways." + }, + { + "name": "PrizeStarCount", + "json_name": "prize_star_count", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. The number of Telegram Stars to be split between giveaway winners; for Telegram Star giveaways only" + }, + { + "name": "PremiumSubscriptionMonthCount", + "json_name": "premium_subscription_month_count", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. The number of months the Telegram Premium subscription won from the giveaway will be active for; for Telegram Premium giveaways only" + } + ] + }, + { + "name": "GiveawayWinners", + "doc": "This object represents a message about the completion of a giveaway with public winners.", + "fields": [ + { + "name": "Chat", + "json_name": "chat", + "type": { + "kind": "named", + "name": "Chat" + }, + "required": true, + "doc": "The chat that created the giveaway" + }, + { + "name": "GiveawayMessageID", + "json_name": "giveaway_message_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Identifier of the message with the giveaway in the chat" + }, + { + "name": "WinnersSelectionDate", + "json_name": "winners_selection_date", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Point in time (Unix timestamp) when winners of the giveaway were selected" + }, + { + "name": "WinnerCount", + "json_name": "winner_count", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Total number of winners in the giveaway" + }, + { + "name": "Winners", + "json_name": "winners", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "User" + } + }, + "required": true, + "doc": "List of up to 100 winners of the giveaway" + }, + { + "name": "AdditionalChatCount", + "json_name": "additional_chat_count", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. The number of other chats the user had to join in order to be eligible for the giveaway" + }, + { + "name": "PrizeStarCount", + "json_name": "prize_star_count", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. The number of Telegram Stars that were split between giveaway winners; for Telegram Star giveaways only" + }, + { + "name": "PremiumSubscriptionMonthCount", + "json_name": "premium_subscription_month_count", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. The number of months the Telegram Premium subscription won from the giveaway will be active for; for Telegram Premium giveaways only" + }, + { + "name": "UnclaimedPrizeCount", + "json_name": "unclaimed_prize_count", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. Number of undistributed prizes" + }, + { + "name": "OnlyNewMembers", + "json_name": "only_new_members", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if only users who had joined the chats after the giveaway started were eligible to win" + }, + { + "name": "WasRefunded", + "json_name": "was_refunded", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the giveaway was canceled because the payment for it was refunded" + }, + { + "name": "PrizeDescription", + "json_name": "prize_description", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Description of additional giveaway prize" + } + ] + }, + { + "name": "GiveawayCompleted", + "doc": "This object represents a service message about the completion of a giveaway without public winners.", + "fields": [ + { + "name": "WinnerCount", + "json_name": "winner_count", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Number of winners in the giveaway" + }, + { + "name": "UnclaimedPrizeCount", + "json_name": "unclaimed_prize_count", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. Number of undistributed prizes" + }, + { + "name": "GiveawayMessage", + "json_name": "giveaway_message", + "type": { + "kind": "named", + "name": "Message" + }, + "doc": "Optional. Message with the giveaway that was completed, if it wasn't deleted" + }, + { + "name": "IsStarGiveaway", + "json_name": "is_star_giveaway", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the giveaway is a Telegram Star giveaway. Otherwise, currently, the giveaway is a Telegram Premium giveaway." + } + ] + }, + { + "name": "LinkPreviewOptions", + "doc": "Describes the options used for link preview generation.", + "fields": [ + { + "name": "IsDisabled", + "json_name": "is_disabled", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the link preview is disabled" + }, + { + "name": "URL", + "json_name": "url", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. URL to use for the link preview. If empty, then the first URL found in the message text will be used" + }, + { + "name": "PreferSmallMedia", + "json_name": "prefer_small_media", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the media in the link preview is supposed to be shrunk; ignored if the URL isn't explicitly specified or media size change isn't supported for the preview" + }, + { + "name": "PreferLargeMedia", + "json_name": "prefer_large_media", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the media in the link preview is supposed to be enlarged; ignored if the URL isn't explicitly specified or media size change isn't supported for the preview" + }, + { + "name": "ShowAboveText", + "json_name": "show_above_text", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the link preview must be shown above the message text; otherwise, the link preview will be shown below the message text" + } + ] + }, + { + "name": "SuggestedPostPrice", + "doc": "Describes the price of a suggested post.", + "fields": [ + { + "name": "Currency", + "json_name": "currency", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Currency in which the post will be paid. Currently, must be one of “XTR” for Telegram Stars or “TON” for toncoins" + }, + { + "name": "Amount", + "json_name": "amount", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "The amount of the currency that will be paid for the post in the smallest units of the currency, i.e. Telegram Stars or nanotoncoins. Currently, price in Telegram Stars must be between 5 and 100000, and price in nanotoncoins must be between 10000000 and 10000000000000." + } + ] + }, + { + "name": "SuggestedPostInfo", + "doc": "Contains information about a suggested post.", + "fields": [ + { + "name": "State", + "json_name": "state", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "State of the suggested post. Currently, it can be one of “pending”, “approved”, “declined”." + }, + { + "name": "Price", + "json_name": "price", + "type": { + "kind": "named", + "name": "SuggestedPostPrice" + }, + "doc": "Optional. Proposed price of the post. If the field is omitted, then the post is unpaid." + }, + { + "name": "SendDate", + "json_name": "send_date", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. Proposed send date of the post. If the field is omitted, then the post can be published at any time within 30 days at the sole discretion of the user or administrator who approves it." + } + ] + }, + { + "name": "SuggestedPostParameters", + "doc": "Contains parameters of a post that is being suggested by the bot.", + "fields": [ + { + "name": "Price", + "json_name": "price", + "type": { + "kind": "named", + "name": "SuggestedPostPrice" + }, + "doc": "Optional. Proposed price for the post. If the field is omitted, then the post is unpaid." + }, + { + "name": "SendDate", + "json_name": "send_date", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. Proposed send date of the post. If specified, then the date must be between 300 second and 2678400 seconds (30 days) in the future. If the field is omitted, then the post can be published at any time within 30 days at the sole discretion of the user who approves it." + } + ] + }, + { + "name": "DirectMessagesTopic", + "doc": "Describes a topic of a direct messages chat.", + "fields": [ + { + "name": "TopicID", + "json_name": "topic_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Unique identifier of the topic. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a 64-bit integer or double-precision float type are safe for storing this identifier." + }, + { + "name": "User", + "json_name": "user", + "type": { + "kind": "named", + "name": "User" + }, + "doc": "Optional. Information about the user that created the topic. Currently, it is always present" + } + ] + }, + { + "name": "UserProfilePhotos", + "doc": "This object represent a user's profile pictures.", + "fields": [ + { + "name": "TotalCount", + "json_name": "total_count", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Total number of profile pictures the target user has" + }, + { + "name": "Photos", + "json_name": "photos", + "type": { + "kind": "array", + "elem_type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "PhotoSize" + } + } + }, + "required": true, + "doc": "Requested profile pictures (in up to 4 sizes each)" + } + ] + }, + { + "name": "UserProfileAudios", + "doc": "This object represents the audios displayed on a user's profile.", + "fields": [ + { + "name": "TotalCount", + "json_name": "total_count", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Total number of profile audios for the target user" + }, + { + "name": "Audios", + "json_name": "audios", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "Audio" + } + }, + "required": true, + "doc": "Requested profile audios" + } + ] + }, + { + "name": "File", + "doc": "This object represents a file ready to be downloaded. The file can be downloaded via the link https://api.telegram.org/file/bot/. It is guaranteed that the link will be valid for at least 1 hour. When the link expires, a new one can be requested by calling getFile.\nThe maximum file size to download is 20 MB", + "fields": [ + { + "name": "FileID", + "json_name": "file_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Identifier for this file, which can be used to download or reuse the file" + }, + { + "name": "FileUniqueID", + "json_name": "file_unique_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file." + }, + { + "name": "FileSize", + "json_name": "file_size", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. File size in bytes. It can be bigger than 2^31 and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this value." + }, + { + "name": "FilePath", + "json_name": "file_path", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. File path. Use https://api.telegram.org/file/bot/ to get the file." + } + ] + }, + { + "name": "WebAppInfo", + "doc": "Describes a Web App.", + "fields": [ + { + "name": "URL", + "json_name": "url", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "An HTTPS URL of a Web App to be opened with additional data as specified in Initializing Web Apps" + } + ] + }, + { + "name": "ReplyKeyboardMarkup", + "doc": "This object represents a custom keyboard with reply options (see Introduction to bots for details and examples). Not supported in channels and for messages sent on behalf of a business account.", + "fields": [ + { + "name": "Keyboard", + "json_name": "keyboard", + "type": { + "kind": "array", + "elem_type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "KeyboardButton" + } + } + }, + "required": true, + "doc": "Array of button rows, each represented by an Array of KeyboardButton objects" + }, + { + "name": "IsPersistent", + "json_name": "is_persistent", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. Requests clients to always show the keyboard when the regular keyboard is hidden. Defaults to false, in which case the custom keyboard can be hidden and opened with a keyboard icon." + }, + { + "name": "ResizeKeyboard", + "json_name": "resize_keyboard", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. Requests clients to resize the keyboard vertically for optimal fit (e.g., make the keyboard smaller if there are just two rows of buttons). Defaults to false, in which case the custom keyboard is always of the same height as the app's standard keyboard." + }, + { + "name": "OneTimeKeyboard", + "json_name": "one_time_keyboard", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. Requests clients to hide the keyboard as soon as it's been used. The keyboard will still be available, but clients will automatically display the usual letter-keyboard in the chat - the user can press a special button in the input field to see the custom keyboard again. Defaults to false." + }, + { + "name": "InputFieldPlaceholder", + "json_name": "input_field_placeholder", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. The placeholder to be shown in the input field when the keyboard is active; 1-64 characters" + }, + { + "name": "Selective", + "json_name": "selective", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. Use this parameter if you want to show the keyboard to specific users only. Targets: 1) users that are @mentioned in the text of the Message object; 2) if the bot's message is a reply to a message in the same chat and forum topic, sender of the original message.Example: A user requests to change the bot's language, bot replies to the request with a keyboard to select the new language. Other users in the group don't see the keyboard." + } + ] + }, + { + "name": "KeyboardButton", + "doc": "This object represents one button of the reply keyboard. At most one of the fields other than text, icon_custom_emoji_id, and style must be used to specify the type of the button. For simple text buttons, String can be used instead of this object to specify the button text.", + "fields": [ + { + "name": "Text", + "json_name": "text", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Text of the button. If none of the fields other than text, icon_custom_emoji_id, and style are used, it will be sent as a message when the button is pressed" + }, + { + "name": "IconCustomEmojiID", + "json_name": "icon_custom_emoji_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Unique identifier of the custom emoji shown before the text of the button. Can only be used by bots that purchased additional usernames on Fragment or in the messages directly sent by the bot to private, group and supergroup chats if the owner of the bot has a Telegram Premium subscription." + }, + { + "name": "Style", + "json_name": "style", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Style of the button. Must be one of “danger” (red), “success” (green) or “primary” (blue). If omitted, then an app-specific style is used." + }, + { + "name": "RequestUsers", + "json_name": "request_users", + "type": { + "kind": "named", + "name": "KeyboardButtonRequestUsers" + }, + "doc": "Optional. If specified, pressing the button will open a list of suitable users. Identifiers of selected users will be sent to the bot in a “users_shared” service message. Available in private chats only." + }, + { + "name": "RequestChat", + "json_name": "request_chat", + "type": { + "kind": "named", + "name": "KeyboardButtonRequestChat" + }, + "doc": "Optional. If specified, pressing the button will open a list of suitable chats. Tapping on a chat will send its identifier to the bot in a “chat_shared” service message. Available in private chats only." + }, + { + "name": "RequestManagedBot", + "json_name": "request_managed_bot", + "type": { + "kind": "named", + "name": "KeyboardButtonRequestManagedBot" + }, + "doc": "Optional. If specified, pressing the button will ask the user to create and share a bot that will be managed by the current bot. Available for bots that enabled management of other bots in the @BotFather Mini App. Available in private chats only." + }, + { + "name": "RequestContact", + "json_name": "request_contact", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. If True, the user's phone number will be sent as a contact when the button is pressed. Available in private chats only." + }, + { + "name": "RequestLocation", + "json_name": "request_location", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. If True, the user's current location will be sent when the button is pressed. Available in private chats only." + }, + { + "name": "RequestPoll", + "json_name": "request_poll", + "type": { + "kind": "named", + "name": "KeyboardButtonPollType" + }, + "doc": "Optional. If specified, the user will be asked to create a poll and send it to the bot when the button is pressed. Available in private chats only." + }, + { + "name": "WebApp", + "json_name": "web_app", + "type": { + "kind": "named", + "name": "WebAppInfo" + }, + "doc": "Optional. If specified, the described Web App will be launched when the button is pressed. The Web App will be able to send a “web_app_data” service message. Available in private chats only." + } + ] + }, + { + "name": "KeyboardButtonRequestUsers", + "doc": "This object defines the criteria used to request suitable users. Information about the selected users will be shared with the bot when the corresponding button is pressed. More about requesting users »", + "fields": [ + { + "name": "RequestID", + "json_name": "request_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Signed 32-bit identifier of the request that will be received back in the UsersShared object. Must be unique within the message" + }, + { + "name": "UserIsBot", + "json_name": "user_is_bot", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. Pass True to request bots, pass False to request regular users. If not specified, no additional restrictions are applied." + }, + { + "name": "UserIsPremium", + "json_name": "user_is_premium", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. Pass True to request premium users, pass False to request non-premium users. If not specified, no additional restrictions are applied." + }, + { + "name": "MaxQuantity", + "json_name": "max_quantity", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. The maximum number of users to be selected; 1-10. Defaults to 1." + }, + { + "name": "RequestName", + "json_name": "request_name", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. Pass True to request the users' first and last names" + }, + { + "name": "RequestUsername", + "json_name": "request_username", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. Pass True to request the users' usernames" + }, + { + "name": "RequestPhoto", + "json_name": "request_photo", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. Pass True to request the users' photos" + } + ] + }, + { + "name": "KeyboardButtonRequestChat", + "doc": "This object defines the criteria used to request a suitable chat. Information about the selected chat will be shared with the bot when the corresponding button is pressed. The bot will be granted requested rights in the chat if appropriate. More about requesting chats ».", + "fields": [ + { + "name": "RequestID", + "json_name": "request_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Signed 32-bit identifier of the request, which will be received back in the ChatShared object. Must be unique within the message" + }, + { + "name": "ChatIsChannel", + "json_name": "chat_is_channel", + "type": { + "kind": "primitive", + "name": "bool" + }, + "required": true, + "doc": "Pass True to request a channel chat, pass False to request a group or a supergroup chat." + }, + { + "name": "ChatIsForum", + "json_name": "chat_is_forum", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. Pass True to request a forum supergroup, pass False to request a non-forum chat. If not specified, no additional restrictions are applied." + }, + { + "name": "ChatHasUsername", + "json_name": "chat_has_username", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. Pass True to request a supergroup or a channel with a username, pass False to request a chat without a username. If not specified, no additional restrictions are applied." + }, + { + "name": "ChatIsCreated", + "json_name": "chat_is_created", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. Pass True to request a chat owned by the user. Otherwise, no additional restrictions are applied." + }, + { + "name": "UserAdministratorRights", + "json_name": "user_administrator_rights", + "type": { + "kind": "named", + "name": "ChatAdministratorRights" + }, + "doc": "Optional. A JSON-serialized object listing the required administrator rights of the user in the chat. The rights must be a superset of bot_administrator_rights. If not specified, no additional restrictions are applied." + }, + { + "name": "BotAdministratorRights", + "json_name": "bot_administrator_rights", + "type": { + "kind": "named", + "name": "ChatAdministratorRights" + }, + "doc": "Optional. A JSON-serialized object listing the required administrator rights of the bot in the chat. The rights must be a subset of user_administrator_rights. If not specified, no additional restrictions are applied." + }, + { + "name": "BotIsMember", + "json_name": "bot_is_member", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. Pass True to request a chat with the bot as a member. Otherwise, no additional restrictions are applied." + }, + { + "name": "RequestTitle", + "json_name": "request_title", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. Pass True to request the chat's title" + }, + { + "name": "RequestUsername", + "json_name": "request_username", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. Pass True to request the chat's username" + }, + { + "name": "RequestPhoto", + "json_name": "request_photo", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. Pass True to request the chat's photo" + } + ] + }, + { + "name": "KeyboardButtonRequestManagedBot", + "doc": "This object defines the parameters for the creation of a managed bot. Information about the created bot will be shared with the bot using the update managed_bot and a Message with the field managed_bot_created.", + "fields": [ + { + "name": "RequestID", + "json_name": "request_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Signed 32-bit identifier of the request. Must be unique within the message" + }, + { + "name": "SuggestedName", + "json_name": "suggested_name", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Suggested name for the bot" + }, + { + "name": "SuggestedUsername", + "json_name": "suggested_username", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Suggested username for the bot" + } + ] + }, + { + "name": "KeyboardButtonPollType", + "doc": "This object represents type of a poll, which is allowed to be created and sent when the corresponding button is pressed.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. If quiz is passed, the user will be allowed to create only polls in the quiz mode. If regular is passed, only regular polls will be allowed. Otherwise, the user will be allowed to create a poll of any type." + } + ] + }, + { + "name": "ReplyKeyboardRemove", + "doc": "Upon receiving a message with this object, Telegram clients will remove the current custom keyboard and display the default letter-keyboard. By default, custom keyboards are displayed until a new keyboard is sent by a bot. An exception is made for one-time keyboards that are hidden immediately after the user presses a button (see ReplyKeyboardMarkup). Not supported in channels and for messages sent on behalf of a business account.", + "fields": [ + { + "name": "RemoveKeyboard", + "json_name": "remove_keyboard", + "type": { + "kind": "primitive", + "name": "bool" + }, + "required": true, + "doc": "Requests clients to remove the custom keyboard (user will not be able to summon this keyboard; if you want to hide the keyboard from sight but keep it accessible, use one_time_keyboard in ReplyKeyboardMarkup)" + }, + { + "name": "Selective", + "json_name": "selective", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. Use this parameter if you want to remove the keyboard for specific users only. Targets: 1) users that are @mentioned in the text of the Message object; 2) if the bot's message is a reply to a message in the same chat and forum topic, sender of the original message.Example: A user votes in a poll, bot returns confirmation message in reply to the vote and removes the keyboard for that user, while still showing the keyboard with poll options to users who haven't voted yet." + } + ] + }, + { + "name": "InlineKeyboardMarkup", + "doc": "This object represents an inline keyboard that appears right next to the message it belongs to.", + "fields": [ + { + "name": "InlineKeyboard", + "json_name": "inline_keyboard", + "type": { + "kind": "array", + "elem_type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "InlineKeyboardButton" + } + } + }, + "required": true, + "doc": "Array of button rows, each represented by an Array of InlineKeyboardButton objects" + } + ] + }, + { + "name": "InlineKeyboardButton", + "doc": "This object represents one button of an inline keyboard. Exactly one of the fields other than text, icon_custom_emoji_id, and style must be used to specify the type of the button.", + "fields": [ + { + "name": "Text", + "json_name": "text", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Label text on the button" + }, + { + "name": "IconCustomEmojiID", + "json_name": "icon_custom_emoji_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Unique identifier of the custom emoji shown before the text of the button. Can only be used by bots that purchased additional usernames on Fragment or in the messages directly sent by the bot to private, group and supergroup chats if the owner of the bot has a Telegram Premium subscription." + }, + { + "name": "Style", + "json_name": "style", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Style of the button. Must be one of “danger” (red), “success” (green) or “primary” (blue). If omitted, then an app-specific style is used." + }, + { + "name": "URL", + "json_name": "url", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. HTTP or tg:// URL to be opened when the button is pressed. Links tg://user?id= can be used to mention a user by their identifier without using a username, if this is allowed by their privacy settings." + }, + { + "name": "CallbackData", + "json_name": "callback_data", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Data to be sent in a callback query to the bot when the button is pressed, 1-64 bytes" + }, + { + "name": "WebApp", + "json_name": "web_app", + "type": { + "kind": "named", + "name": "WebAppInfo" + }, + "doc": "Optional. Description of the Web App that will be launched when the user presses the button. The Web App will be able to send an arbitrary message on behalf of the user using the method answerWebAppQuery. Available only in private chats between a user and the bot. Not supported for messages sent on behalf of a business account." + }, + { + "name": "LoginURL", + "json_name": "login_url", + "type": { + "kind": "named", + "name": "LoginUrl" + }, + "doc": "Optional. An HTTPS URL used to automatically authorize the user. Can be used as a replacement for the Telegram Login Widget." + }, + { + "name": "SwitchInlineQuery", + "json_name": "switch_inline_query", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. If set, pressing the button will prompt the user to select one of their chats, open that chat and insert the bot's username and the specified inline query in the input field. May be empty, in which case just the bot's username will be inserted. Not supported for messages sent in channel direct messages chats and on behalf of a business account." + }, + { + "name": "SwitchInlineQueryCurrentChat", + "json_name": "switch_inline_query_current_chat", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. If set, pressing the button will insert the bot's username and the specified inline query in the current chat's input field. May be empty, in which case only the bot's username will be inserted.This offers a quick way for the user to open your bot in inline mode in the same chat - good for selecting something from multiple options. Not supported in channels and for messages sent in channel direct messages chats and on behalf of a business account." + }, + { + "name": "SwitchInlineQueryChosenChat", + "json_name": "switch_inline_query_chosen_chat", + "type": { + "kind": "named", + "name": "SwitchInlineQueryChosenChat" + }, + "doc": "Optional. If set, pressing the button will prompt the user to select one of their chats of the specified type, open that chat and insert the bot's username and the specified inline query in the input field. Not supported for messages sent in channel direct messages chats and on behalf of a business account." + }, + { + "name": "CopyText", + "json_name": "copy_text", + "type": { + "kind": "named", + "name": "CopyTextButton" + }, + "doc": "Optional. Description of the button that copies the specified text to the clipboard." + }, + { + "name": "CallbackGame", + "json_name": "callback_game", + "type": { + "kind": "named", + "name": "CallbackGame" + }, + "doc": "Optional. Description of the game that will be launched when the user presses the button.NOTE: This type of button must always be the first button in the first row." + }, + { + "name": "Pay", + "json_name": "pay", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. Specify True, to send a Pay button. Substrings “” and “XTR” in the buttons's text will be replaced with a Telegram Star icon.NOTE: This type of button must always be the first button in the first row and can only be used in invoice messages." + } + ] + }, + { + "name": "LoginUrl", + "doc": "This object represents a parameter of the inline keyboard button used to automatically authorize a user. Serves as a great replacement for the Telegram Login Widget when the user is coming from Telegram. All the user needs to do is tap/click a button and confirm that they want to log in:\nTelegram apps support these buttons as of version 5.7.\nSample bot: @discussbot", + "fields": [ + { + "name": "URL", + "json_name": "url", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "An HTTPS URL to be opened with user authorization data added to the query string when the button is pressed. If the user refuses to provide authorization data, the original URL without information about the user will be opened. The data added is the same as described in Receiving authorization data.NOTE: You must always check the hash of the received data to verify the authentication and the integrity of the data as described in Checking authorization." + }, + { + "name": "ForwardText", + "json_name": "forward_text", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. New text of the button in forwarded messages." + }, + { + "name": "BotUsername", + "json_name": "bot_username", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Username of a bot, which will be used for user authorization. See Setting up a bot for more details. If not specified, the current bot's username will be assumed. The url's domain must be the same as the domain linked with the bot. See Linking your domain to the bot for more details." + }, + { + "name": "RequestWriteAccess", + "json_name": "request_write_access", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. Pass True to request the permission for your bot to send messages to the user." + } + ] + }, + { + "name": "SwitchInlineQueryChosenChat", + "doc": "This object represents an inline button that switches the current user to inline mode in a chosen chat, with an optional default inline query.", + "fields": [ + { + "name": "Query", + "json_name": "query", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. The default inline query to be inserted in the input field. If left empty, only the bot's username will be inserted" + }, + { + "name": "AllowUserChats", + "json_name": "allow_user_chats", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if private chats with users can be chosen" + }, + { + "name": "AllowBotChats", + "json_name": "allow_bot_chats", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if private chats with bots can be chosen" + }, + { + "name": "AllowGroupChats", + "json_name": "allow_group_chats", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if group and supergroup chats can be chosen" + }, + { + "name": "AllowChannelChats", + "json_name": "allow_channel_chats", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if channel chats can be chosen" + } + ] + }, + { + "name": "CopyTextButton", + "doc": "This object represents an inline keyboard button that copies specified text to the clipboard.", + "fields": [ + { + "name": "Text", + "json_name": "text", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "The text to be copied to the clipboard; 1-256 characters" + } + ] + }, + { + "name": "CallbackQuery", + "doc": "This object represents an incoming callback query from a callback button in an inline keyboard. If the button that originated the query was attached to a message sent by the bot, the field message will be present. If the button was attached to a message sent via the bot (in inline mode), the field inline_message_id will be present. Exactly one of the fields data or game_short_name will be present.\nNOTE: After the user presses a callback button, Telegram clients will display a progress bar until you call answerCallbackQuery. It is, therefore, necessary to react by calling answerCallbackQuery even if no notification to the user is needed (e.g., without specifying any of the optional parameters).", + "fields": [ + { + "name": "ID", + "json_name": "id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique identifier for this query" + }, + { + "name": "From", + "json_name": "from", + "type": { + "kind": "named", + "name": "User" + }, + "required": true, + "doc": "Sender" + }, + { + "name": "Message", + "json_name": "message", + "type": { + "kind": "named", + "name": "MaybeInaccessibleMessage" + }, + "doc": "Optional. Message sent by the bot with the callback button that originated the query" + }, + { + "name": "InlineMessageID", + "json_name": "inline_message_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Identifier of the message sent via the bot in inline mode, that originated the query." + }, + { + "name": "ChatInstance", + "json_name": "chat_instance", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Global identifier, uniquely corresponding to the chat to which the message with the callback button was sent. Useful for high scores in games." + }, + { + "name": "Data", + "json_name": "data", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Data associated with the callback button. Be aware that the message originated the query can contain no callback buttons with this data." + }, + { + "name": "GameShortName", + "json_name": "game_short_name", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Short name of a Game to be returned, serves as the unique identifier for the game" + } + ] + }, + { + "name": "ForceReply", + "doc": "Upon receiving a message with this object, Telegram clients will display a reply interface to the user (act as if the user has selected the bot's message and tapped 'Reply'). This can be extremely useful if you want to create user-friendly step-by-step interfaces without having to sacrifice privacy mode. Not supported in channels and for messages sent on behalf of a user account.\nExample: A poll bot for groups runs in privacy mode (only receives commands, replies to its messages and mentions). There could be two ways to create a new poll:\nThe last option is definitely more attractive. And if you use ForceReply in your bot's questions, it will receive the user's answers even if it only receives replies, commands and mentions - without any extra work for the user.", + "fields": [ + { + "name": "ForceReply", + "json_name": "force_reply", + "type": { + "kind": "primitive", + "name": "bool" + }, + "required": true, + "doc": "Shows reply interface to the user, as if they manually selected the bot's message and tapped 'Reply'" + }, + { + "name": "InputFieldPlaceholder", + "json_name": "input_field_placeholder", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. The placeholder to be shown in the input field when the reply is active; 1-64 characters" + }, + { + "name": "Selective", + "json_name": "selective", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. Use this parameter if you want to force reply from specific users only. Targets: 1) users that are @mentioned in the text of the Message object; 2) if the bot's message is a reply to a message in the same chat and forum topic, sender of the original message." + } + ] + }, + { + "name": "ChatPhoto", + "doc": "This object represents a chat photo.", + "fields": [ + { + "name": "SmallFileID", + "json_name": "small_file_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "File identifier of small (160x160) chat photo. This file_id can be used only for photo download and only for as long as the photo is not changed." + }, + { + "name": "SmallFileUniqueID", + "json_name": "small_file_unique_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique file identifier of small (160x160) chat photo, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file." + }, + { + "name": "BigFileID", + "json_name": "big_file_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "File identifier of big (640x640) chat photo. This file_id can be used only for photo download and only for as long as the photo is not changed." + }, + { + "name": "BigFileUniqueID", + "json_name": "big_file_unique_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique file identifier of big (640x640) chat photo, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file." + } + ] + }, + { + "name": "ChatInviteLink", + "doc": "Represents an invite link for a chat.", + "fields": [ + { + "name": "InviteLink", + "json_name": "invite_link", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "The invite link. If the link was created by another chat administrator, then the second part of the link will be replaced with “…”." + }, + { + "name": "Creator", + "json_name": "creator", + "type": { + "kind": "named", + "name": "User" + }, + "required": true, + "doc": "Creator of the link" + }, + { + "name": "CreatesJoinRequest", + "json_name": "creates_join_request", + "type": { + "kind": "primitive", + "name": "bool" + }, + "required": true, + "doc": "True, if users joining the chat via the link need to be approved by chat administrators" + }, + { + "name": "IsPrimary", + "json_name": "is_primary", + "type": { + "kind": "primitive", + "name": "bool" + }, + "required": true, + "doc": "True, if the link is primary" + }, + { + "name": "IsRevoked", + "json_name": "is_revoked", + "type": { + "kind": "primitive", + "name": "bool" + }, + "required": true, + "doc": "True, if the link is revoked" + }, + { + "name": "Name", + "json_name": "name", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Invite link name" + }, + { + "name": "ExpireDate", + "json_name": "expire_date", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. Point in time (Unix timestamp) when the link will expire or has been expired" + }, + { + "name": "MemberLimit", + "json_name": "member_limit", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. The maximum number of users that can be members of the chat simultaneously after joining the chat via this invite link; 1-99999" + }, + { + "name": "PendingJoinRequestCount", + "json_name": "pending_join_request_count", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. Number of pending join requests created using this link" + }, + { + "name": "SubscriptionPeriod", + "json_name": "subscription_period", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. The number of seconds the subscription will be active for before the next payment" + }, + { + "name": "SubscriptionPrice", + "json_name": "subscription_price", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. The amount of Telegram Stars a user must pay initially and after each subsequent subscription period to be a member of the chat using the link" + } + ] + }, + { + "name": "ChatAdministratorRights", + "doc": "Represents the rights of an administrator in a chat.", + "fields": [ + { + "name": "IsAnonymous", + "json_name": "is_anonymous", + "type": { + "kind": "primitive", + "name": "bool" + }, + "required": true, + "doc": "True, if the user's presence in the chat is hidden" + }, + { + "name": "CanManageChat", + "json_name": "can_manage_chat", + "type": { + "kind": "primitive", + "name": "bool" + }, + "required": true, + "doc": "True, if the administrator can access the chat event log, get boost list, see hidden supergroup and channel members, report spam messages, ignore slow mode, and send messages to the chat without paying Telegram Stars. Implied by any other administrator privilege." + }, + { + "name": "CanDeleteMessages", + "json_name": "can_delete_messages", + "type": { + "kind": "primitive", + "name": "bool" + }, + "required": true, + "doc": "True, if the administrator can delete messages of other users" + }, + { + "name": "CanManageVideoChats", + "json_name": "can_manage_video_chats", + "type": { + "kind": "primitive", + "name": "bool" + }, + "required": true, + "doc": "True, if the administrator can manage video chats" + }, + { + "name": "CanRestrictMembers", + "json_name": "can_restrict_members", + "type": { + "kind": "primitive", + "name": "bool" + }, + "required": true, + "doc": "True, if the administrator can restrict, ban or unban chat members, or access supergroup statistics" + }, + { + "name": "CanPromoteMembers", + "json_name": "can_promote_members", + "type": { + "kind": "primitive", + "name": "bool" + }, + "required": true, + "doc": "True, if the administrator can add new administrators with a subset of their own privileges or demote administrators that they have promoted, directly or indirectly (promoted by administrators that were appointed by the user)" + }, + { + "name": "CanChangeInfo", + "json_name": "can_change_info", + "type": { + "kind": "primitive", + "name": "bool" + }, + "required": true, + "doc": "True, if the user is allowed to change the chat title, photo and other settings" + }, + { + "name": "CanInviteUsers", + "json_name": "can_invite_users", + "type": { + "kind": "primitive", + "name": "bool" + }, + "required": true, + "doc": "True, if the user is allowed to invite new users to the chat" + }, + { + "name": "CanPostStories", + "json_name": "can_post_stories", + "type": { + "kind": "primitive", + "name": "bool" + }, + "required": true, + "doc": "True, if the administrator can post stories to the chat" + }, + { + "name": "CanEditStories", + "json_name": "can_edit_stories", + "type": { + "kind": "primitive", + "name": "bool" + }, + "required": true, + "doc": "True, if the administrator can edit stories posted by other users, post stories to the chat page, pin chat stories, and access the chat's story archive" + }, + { + "name": "CanDeleteStories", + "json_name": "can_delete_stories", + "type": { + "kind": "primitive", + "name": "bool" + }, + "required": true, + "doc": "True, if the administrator can delete stories posted by other users" + }, + { + "name": "CanPostMessages", + "json_name": "can_post_messages", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the administrator can post messages in the channel, approve suggested posts, or access channel statistics; for channels only" + }, + { + "name": "CanEditMessages", + "json_name": "can_edit_messages", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the administrator can edit messages of other users and can pin messages; for channels only" + }, + { + "name": "CanPinMessages", + "json_name": "can_pin_messages", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the user is allowed to pin messages; for groups and supergroups only" + }, + { + "name": "CanManageTopics", + "json_name": "can_manage_topics", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the user is allowed to create, rename, close, and reopen forum topics; for supergroups only" + }, + { + "name": "CanManageDirectMessages", + "json_name": "can_manage_direct_messages", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the administrator can manage direct messages of the channel and decline suggested posts; for channels only" + }, + { + "name": "CanManageTags", + "json_name": "can_manage_tags", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the administrator can edit the tags of regular members; for groups and supergroups only. If omitted defaults to the value of can_pin_messages." + } + ] + }, + { + "name": "ChatMemberUpdated", + "doc": "This object represents changes in the status of a chat member.", + "fields": [ + { + "name": "Chat", + "json_name": "chat", + "type": { + "kind": "named", + "name": "Chat" + }, + "required": true, + "doc": "Chat the user belongs to" + }, + { + "name": "From", + "json_name": "from", + "type": { + "kind": "named", + "name": "User" + }, + "required": true, + "doc": "Performer of the action, which resulted in the change" + }, + { + "name": "Date", + "json_name": "date", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Date the change was done in Unix time" + }, + { + "name": "OldChatMember", + "json_name": "old_chat_member", + "type": { + "kind": "named", + "name": "ChatMember" + }, + "required": true, + "doc": "Previous information about the chat member" + }, + { + "name": "NewChatMember", + "json_name": "new_chat_member", + "type": { + "kind": "named", + "name": "ChatMember" + }, + "required": true, + "doc": "New information about the chat member" + }, + { + "name": "InviteLink", + "json_name": "invite_link", + "type": { + "kind": "named", + "name": "ChatInviteLink" + }, + "doc": "Optional. Chat invite link, which was used by the user to join the chat; for joining by invite link events only." + }, + { + "name": "ViaJoinRequest", + "json_name": "via_join_request", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the user joined the chat after sending a direct join request without using an invite link and being approved by an administrator" + }, + { + "name": "ViaChatFolderInviteLink", + "json_name": "via_chat_folder_invite_link", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the user joined the chat via a chat folder invite link" + } + ] + }, + { + "name": "ChatMember", + "doc": "This object contains information about one member of a chat. Currently, the following 6 types of chat members are supported:", + "one_of": [ + "ChatMemberOwner", + "ChatMemberAdministrator", + "ChatMemberMember", + "ChatMemberRestricted", + "ChatMemberLeft", + "ChatMemberBanned" + ] + }, + { + "name": "ChatMemberOwner", + "doc": "Represents a chat member that owns the chat and has all administrator privileges.", + "fields": [ + { + "name": "Status", + "json_name": "status", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "The member's status in the chat, always “creator”" + }, + { + "name": "User", + "json_name": "user", + "type": { + "kind": "named", + "name": "User" + }, + "required": true, + "doc": "Information about the user" + }, + { + "name": "IsAnonymous", + "json_name": "is_anonymous", + "type": { + "kind": "primitive", + "name": "bool" + }, + "required": true, + "doc": "True, if the user's presence in the chat is hidden" + }, + { + "name": "CustomTitle", + "json_name": "custom_title", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Custom title for this user" + } + ] + }, + { + "name": "ChatMemberAdministrator", + "doc": "Represents a chat member that has some additional privileges.", + "fields": [ + { + "name": "Status", + "json_name": "status", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "The member's status in the chat, always “administrator”" + }, + { + "name": "User", + "json_name": "user", + "type": { + "kind": "named", + "name": "User" + }, + "required": true, + "doc": "Information about the user" + }, + { + "name": "CanBeEdited", + "json_name": "can_be_edited", + "type": { + "kind": "primitive", + "name": "bool" + }, + "required": true, + "doc": "True, if the bot is allowed to edit administrator privileges of that user" + }, + { + "name": "IsAnonymous", + "json_name": "is_anonymous", + "type": { + "kind": "primitive", + "name": "bool" + }, + "required": true, + "doc": "True, if the user's presence in the chat is hidden" + }, + { + "name": "CanManageChat", + "json_name": "can_manage_chat", + "type": { + "kind": "primitive", + "name": "bool" + }, + "required": true, + "doc": "True, if the administrator can access the chat event log, get boost list, see hidden supergroup and channel members, report spam messages, ignore slow mode, and send messages to the chat without paying Telegram Stars. Implied by any other administrator privilege." + }, + { + "name": "CanDeleteMessages", + "json_name": "can_delete_messages", + "type": { + "kind": "primitive", + "name": "bool" + }, + "required": true, + "doc": "True, if the administrator can delete messages of other users" + }, + { + "name": "CanManageVideoChats", + "json_name": "can_manage_video_chats", + "type": { + "kind": "primitive", + "name": "bool" + }, + "required": true, + "doc": "True, if the administrator can manage video chats" + }, + { + "name": "CanRestrictMembers", + "json_name": "can_restrict_members", + "type": { + "kind": "primitive", + "name": "bool" + }, + "required": true, + "doc": "True, if the administrator can restrict, ban or unban chat members, or access supergroup statistics" + }, + { + "name": "CanPromoteMembers", + "json_name": "can_promote_members", + "type": { + "kind": "primitive", + "name": "bool" + }, + "required": true, + "doc": "True, if the administrator can add new administrators with a subset of their own privileges or demote administrators that they have promoted, directly or indirectly (promoted by administrators that were appointed by the user)" + }, + { + "name": "CanChangeInfo", + "json_name": "can_change_info", + "type": { + "kind": "primitive", + "name": "bool" + }, + "required": true, + "doc": "True, if the user is allowed to change the chat title, photo and other settings" + }, + { + "name": "CanInviteUsers", + "json_name": "can_invite_users", + "type": { + "kind": "primitive", + "name": "bool" + }, + "required": true, + "doc": "True, if the user is allowed to invite new users to the chat" + }, + { + "name": "CanPostStories", + "json_name": "can_post_stories", + "type": { + "kind": "primitive", + "name": "bool" + }, + "required": true, + "doc": "True, if the administrator can post stories to the chat" + }, + { + "name": "CanEditStories", + "json_name": "can_edit_stories", + "type": { + "kind": "primitive", + "name": "bool" + }, + "required": true, + "doc": "True, if the administrator can edit stories posted by other users, post stories to the chat page, pin chat stories, and access the chat's story archive" + }, + { + "name": "CanDeleteStories", + "json_name": "can_delete_stories", + "type": { + "kind": "primitive", + "name": "bool" + }, + "required": true, + "doc": "True, if the administrator can delete stories posted by other users" + }, + { + "name": "CanPostMessages", + "json_name": "can_post_messages", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the administrator can post messages in the channel, approve suggested posts, or access channel statistics; for channels only" + }, + { + "name": "CanEditMessages", + "json_name": "can_edit_messages", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the administrator can edit messages of other users and can pin messages; for channels only" + }, + { + "name": "CanPinMessages", + "json_name": "can_pin_messages", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the user is allowed to pin messages; for groups and supergroups only" + }, + { + "name": "CanManageTopics", + "json_name": "can_manage_topics", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the user is allowed to create, rename, close, and reopen forum topics; for supergroups only" + }, + { + "name": "CanManageDirectMessages", + "json_name": "can_manage_direct_messages", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the administrator can manage direct messages of the channel and decline suggested posts; for channels only" + }, + { + "name": "CanManageTags", + "json_name": "can_manage_tags", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the administrator can edit the tags of regular members; for groups and supergroups only. If omitted defaults to the value of can_pin_messages." + }, + { + "name": "CustomTitle", + "json_name": "custom_title", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Custom title for this user" + } + ] + }, + { + "name": "ChatMemberMember", + "doc": "Represents a chat member that has no additional privileges or restrictions.", + "fields": [ + { + "name": "Status", + "json_name": "status", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "The member's status in the chat, always “member”" + }, + { + "name": "Tag", + "json_name": "tag", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Tag of the member" + }, + { + "name": "User", + "json_name": "user", + "type": { + "kind": "named", + "name": "User" + }, + "required": true, + "doc": "Information about the user" + }, + { + "name": "UntilDate", + "json_name": "until_date", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. Date when the user's subscription will expire; Unix time" + } + ] + }, + { + "name": "ChatMemberRestricted", + "doc": "Represents a chat member that is under certain restrictions in the chat. Supergroups only.", + "fields": [ + { + "name": "Status", + "json_name": "status", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "The member's status in the chat, always “restricted”" + }, + { + "name": "Tag", + "json_name": "tag", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Tag of the member" + }, + { + "name": "User", + "json_name": "user", + "type": { + "kind": "named", + "name": "User" + }, + "required": true, + "doc": "Information about the user" + }, + { + "name": "IsMember", + "json_name": "is_member", + "type": { + "kind": "primitive", + "name": "bool" + }, + "required": true, + "doc": "True, if the user is a member of the chat at the moment of the request" + }, + { + "name": "CanSendMessages", + "json_name": "can_send_messages", + "type": { + "kind": "primitive", + "name": "bool" + }, + "required": true, + "doc": "True, if the user is allowed to send text messages, contacts, giveaways, giveaway winners, invoices, locations and venues" + }, + { + "name": "CanSendAudios", + "json_name": "can_send_audios", + "type": { + "kind": "primitive", + "name": "bool" + }, + "required": true, + "doc": "True, if the user is allowed to send audios" + }, + { + "name": "CanSendDocuments", + "json_name": "can_send_documents", + "type": { + "kind": "primitive", + "name": "bool" + }, + "required": true, + "doc": "True, if the user is allowed to send documents" + }, + { + "name": "CanSendPhotos", + "json_name": "can_send_photos", + "type": { + "kind": "primitive", + "name": "bool" + }, + "required": true, + "doc": "True, if the user is allowed to send photos" + }, + { + "name": "CanSendVideos", + "json_name": "can_send_videos", + "type": { + "kind": "primitive", + "name": "bool" + }, + "required": true, + "doc": "True, if the user is allowed to send videos" + }, + { + "name": "CanSendVideoNotes", + "json_name": "can_send_video_notes", + "type": { + "kind": "primitive", + "name": "bool" + }, + "required": true, + "doc": "True, if the user is allowed to send video notes" + }, + { + "name": "CanSendVoiceNotes", + "json_name": "can_send_voice_notes", + "type": { + "kind": "primitive", + "name": "bool" + }, + "required": true, + "doc": "True, if the user is allowed to send voice notes" + }, + { + "name": "CanSendPolls", + "json_name": "can_send_polls", + "type": { + "kind": "primitive", + "name": "bool" + }, + "required": true, + "doc": "True, if the user is allowed to send polls and checklists" + }, + { + "name": "CanSendOtherMessages", + "json_name": "can_send_other_messages", + "type": { + "kind": "primitive", + "name": "bool" + }, + "required": true, + "doc": "True, if the user is allowed to send animations, games, stickers and use inline bots" + }, + { + "name": "CanAddWebPagePreviews", + "json_name": "can_add_web_page_previews", + "type": { + "kind": "primitive", + "name": "bool" + }, + "required": true, + "doc": "True, if the user is allowed to add web page previews to their messages" + }, + { + "name": "CanReactToMessages", + "json_name": "can_react_to_messages", + "type": { + "kind": "primitive", + "name": "bool" + }, + "required": true, + "doc": "True, if the user is allowed to react to messages" + }, + { + "name": "CanEditTag", + "json_name": "can_edit_tag", + "type": { + "kind": "primitive", + "name": "bool" + }, + "required": true, + "doc": "True, if the user is allowed to edit their own tag" + }, + { + "name": "CanChangeInfo", + "json_name": "can_change_info", + "type": { + "kind": "primitive", + "name": "bool" + }, + "required": true, + "doc": "True, if the user is allowed to change the chat title, photo and other settings" + }, + { + "name": "CanInviteUsers", + "json_name": "can_invite_users", + "type": { + "kind": "primitive", + "name": "bool" + }, + "required": true, + "doc": "True, if the user is allowed to invite new users to the chat" + }, + { + "name": "CanPinMessages", + "json_name": "can_pin_messages", + "type": { + "kind": "primitive", + "name": "bool" + }, + "required": true, + "doc": "True, if the user is allowed to pin messages" + }, + { + "name": "CanManageTopics", + "json_name": "can_manage_topics", + "type": { + "kind": "primitive", + "name": "bool" + }, + "required": true, + "doc": "True, if the user is allowed to create forum topics" + }, + { + "name": "UntilDate", + "json_name": "until_date", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Date when restrictions will be lifted for this user; Unix time. If 0, then the user is restricted forever" + } + ] + }, + { + "name": "ChatMemberLeft", + "doc": "Represents a chat member that isn't currently a member of the chat, but may join it themselves.", + "fields": [ + { + "name": "Status", + "json_name": "status", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "The member's status in the chat, always “left”" + }, + { + "name": "User", + "json_name": "user", + "type": { + "kind": "named", + "name": "User" + }, + "required": true, + "doc": "Information about the user" + } + ] + }, + { + "name": "ChatMemberBanned", + "doc": "Represents a chat member that was banned in the chat and can't return to the chat or view chat messages.", + "fields": [ + { + "name": "Status", + "json_name": "status", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "The member's status in the chat, always “kicked”" + }, + { + "name": "User", + "json_name": "user", + "type": { + "kind": "named", + "name": "User" + }, + "required": true, + "doc": "Information about the user" + }, + { + "name": "UntilDate", + "json_name": "until_date", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Date when restrictions will be lifted for this user; Unix time. If 0, then the user is banned forever" + } + ] + }, + { + "name": "ChatJoinRequest", + "doc": "Represents a join request sent to a chat.", + "fields": [ + { + "name": "Chat", + "json_name": "chat", + "type": { + "kind": "named", + "name": "Chat" + }, + "required": true, + "doc": "Chat to which the request was sent" + }, + { + "name": "From", + "json_name": "from", + "type": { + "kind": "named", + "name": "User" + }, + "required": true, + "doc": "User that sent the join request" + }, + { + "name": "UserChatID", + "json_name": "user_chat_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Identifier of a private chat with the user who sent the join request. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a 64-bit integer or double-precision float type are safe for storing this identifier. The bot can use this identifier for 5 minutes to send messages until the join request is processed, assuming no other administrator contacted the user." + }, + { + "name": "Date", + "json_name": "date", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Date the request was sent in Unix time" + }, + { + "name": "Bio", + "json_name": "bio", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Bio of the user." + }, + { + "name": "InviteLink", + "json_name": "invite_link", + "type": { + "kind": "named", + "name": "ChatInviteLink" + }, + "doc": "Optional. Chat invite link that was used by the user to send the join request" + } + ] + }, + { + "name": "ChatPermissions", + "doc": "Describes actions that a non-administrator user is allowed to take in a chat.", + "fields": [ + { + "name": "CanSendMessages", + "json_name": "can_send_messages", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the user is allowed to send text messages, contacts, giveaways, giveaway winners, invoices, locations and venues" + }, + { + "name": "CanSendAudios", + "json_name": "can_send_audios", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the user is allowed to send audios" + }, + { + "name": "CanSendDocuments", + "json_name": "can_send_documents", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the user is allowed to send documents" + }, + { + "name": "CanSendPhotos", + "json_name": "can_send_photos", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the user is allowed to send photos" + }, + { + "name": "CanSendVideos", + "json_name": "can_send_videos", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the user is allowed to send videos" + }, + { + "name": "CanSendVideoNotes", + "json_name": "can_send_video_notes", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the user is allowed to send video notes" + }, + { + "name": "CanSendVoiceNotes", + "json_name": "can_send_voice_notes", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the user is allowed to send voice notes" + }, + { + "name": "CanSendPolls", + "json_name": "can_send_polls", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the user is allowed to send polls and checklists" + }, + { + "name": "CanSendOtherMessages", + "json_name": "can_send_other_messages", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the user is allowed to send animations, games, stickers and use inline bots" + }, + { + "name": "CanAddWebPagePreviews", + "json_name": "can_add_web_page_previews", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the user is allowed to add web page previews to their messages" + }, + { + "name": "CanReactToMessages", + "json_name": "can_react_to_messages", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the user is allowed to react to messages. If omitted, defaults to the value of can_send_messages." + }, + { + "name": "CanEditTag", + "json_name": "can_edit_tag", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the user is allowed to edit their own tag. If omitted, defaults to the value of can_pin_messages." + }, + { + "name": "CanChangeInfo", + "json_name": "can_change_info", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the user is allowed to change the chat title, photo and other settings. Ignored in public supergroups" + }, + { + "name": "CanInviteUsers", + "json_name": "can_invite_users", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the user is allowed to invite new users to the chat" + }, + { + "name": "CanPinMessages", + "json_name": "can_pin_messages", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the user is allowed to pin messages. Ignored in public supergroups" + }, + { + "name": "CanManageTopics", + "json_name": "can_manage_topics", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the user is allowed to create forum topics. If omitted defaults to the value of can_pin_messages" + } + ] + }, + { + "name": "Birthdate", + "doc": "Describes the birthdate of a user.", + "fields": [ + { + "name": "Day", + "json_name": "day", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Day of the user's birth; 1-31" + }, + { + "name": "Month", + "json_name": "month", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Month of the user's birth; 1-12" + }, + { + "name": "Year", + "json_name": "year", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. Year of the user's birth" + } + ] + }, + { + "name": "BusinessIntro", + "doc": "Contains information about the start page settings of a Telegram Business account.", + "fields": [ + { + "name": "Title", + "json_name": "title", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Title text of the business intro" + }, + { + "name": "Message", + "json_name": "message", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Message text of the business intro" + }, + { + "name": "Sticker", + "json_name": "sticker", + "type": { + "kind": "named", + "name": "Sticker" + }, + "doc": "Optional. Sticker of the business intro" + } + ] + }, + { + "name": "BusinessLocation", + "doc": "Contains information about the location of a Telegram Business account.", + "fields": [ + { + "name": "Address", + "json_name": "address", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Address of the business" + }, + { + "name": "Location", + "json_name": "location", + "type": { + "kind": "named", + "name": "Location" + }, + "doc": "Optional. Location of the business" + } + ] + }, + { + "name": "BusinessOpeningHoursInterval", + "doc": "Describes an interval of time during which a business is open.", + "fields": [ + { + "name": "OpeningMinute", + "json_name": "opening_minute", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "The minute's sequence number in a week, starting on Monday, marking the start of the time interval during which the business is open; 0 - 7 * 24 * 60" + }, + { + "name": "ClosingMinute", + "json_name": "closing_minute", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "The minute's sequence number in a week, starting on Monday, marking the end of the time interval during which the business is open; 0 - 8 * 24 * 60" + } + ] + }, + { + "name": "BusinessOpeningHours", + "doc": "Describes the opening hours of a business.", + "fields": [ + { + "name": "TimeZoneName", + "json_name": "time_zone_name", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique name of the time zone for which the opening hours are defined" + }, + { + "name": "OpeningHours", + "json_name": "opening_hours", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "BusinessOpeningHoursInterval" + } + }, + "required": true, + "doc": "List of time intervals describing business opening hours" + } + ] + }, + { + "name": "UserRating", + "doc": "This object describes the rating of a user based on their Telegram Star spendings.", + "fields": [ + { + "name": "Level", + "json_name": "level", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Current level of the user, indicating their reliability when purchasing digital goods and services. A higher level suggests a more trustworthy customer; a negative level is likely reason for concern." + }, + { + "name": "Rating", + "json_name": "rating", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Numerical value of the user's rating; the higher the rating, the better" + }, + { + "name": "CurrentLevelRating", + "json_name": "current_level_rating", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "The rating value required to get the current level" + }, + { + "name": "NextLevelRating", + "json_name": "next_level_rating", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. The rating value required to get to the next level; omitted if the maximum level was reached" + } + ] + }, + { + "name": "StoryAreaPosition", + "doc": "Describes the position of a clickable area within a story.", + "fields": [ + { + "name": "XPercentage", + "json_name": "x_percentage", + "type": { + "kind": "primitive", + "name": "float64" + }, + "required": true, + "doc": "The abscissa of the area's center, as a percentage of the media width" + }, + { + "name": "YPercentage", + "json_name": "y_percentage", + "type": { + "kind": "primitive", + "name": "float64" + }, + "required": true, + "doc": "The ordinate of the area's center, as a percentage of the media height" + }, + { + "name": "WidthPercentage", + "json_name": "width_percentage", + "type": { + "kind": "primitive", + "name": "float64" + }, + "required": true, + "doc": "The width of the area's rectangle, as a percentage of the media width" + }, + { + "name": "HeightPercentage", + "json_name": "height_percentage", + "type": { + "kind": "primitive", + "name": "float64" + }, + "required": true, + "doc": "The height of the area's rectangle, as a percentage of the media height" + }, + { + "name": "RotationAngle", + "json_name": "rotation_angle", + "type": { + "kind": "primitive", + "name": "float64" + }, + "required": true, + "doc": "The clockwise rotation angle of the rectangle, in degrees; 0-360" + }, + { + "name": "CornerRadiusPercentage", + "json_name": "corner_radius_percentage", + "type": { + "kind": "primitive", + "name": "float64" + }, + "required": true, + "doc": "The radius of the rectangle corner rounding, as a percentage of the media width" + } + ] + }, + { + "name": "LocationAddress", + "doc": "Describes the physical address of a location.", + "fields": [ + { + "name": "CountryCode", + "json_name": "country_code", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "The two-letter ISO 3166-1 alpha-2 country code of the country where the location is located" + }, + { + "name": "State", + "json_name": "state", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. State of the location" + }, + { + "name": "City", + "json_name": "city", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. City of the location" + }, + { + "name": "Street", + "json_name": "street", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Street address of the location" + } + ] + }, + { + "name": "StoryAreaType", + "doc": "Describes the type of a clickable area on a story. Currently, it can be one of", + "one_of": [ + "StoryAreaTypeLocation", + "StoryAreaTypeSuggestedReaction", + "StoryAreaTypeLink", + "StoryAreaTypeWeather", + "StoryAreaTypeUniqueGift" + ] + }, + { + "name": "StoryAreaTypeLocation", + "doc": "Describes a story area pointing to a location. Currently, a story can have up to 10 location areas.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of the area, always “location”" + }, + { + "name": "Latitude", + "json_name": "latitude", + "type": { + "kind": "primitive", + "name": "float64" + }, + "required": true, + "doc": "Location latitude in degrees" + }, + { + "name": "Longitude", + "json_name": "longitude", + "type": { + "kind": "primitive", + "name": "float64" + }, + "required": true, + "doc": "Location longitude in degrees" + }, + { + "name": "Address", + "json_name": "address", + "type": { + "kind": "named", + "name": "LocationAddress" + }, + "doc": "Optional. Address of the location" + } + ] + }, + { + "name": "StoryAreaTypeSuggestedReaction", + "doc": "Describes a story area pointing to a suggested reaction. Currently, a story can have up to 5 suggested reaction areas.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of the area, always “suggested_reaction”" + }, + { + "name": "ReactionType", + "json_name": "reaction_type", + "type": { + "kind": "named", + "name": "ReactionType" + }, + "required": true, + "doc": "Type of the reaction" + }, + { + "name": "IsDark", + "json_name": "is_dark", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. Pass True if the reaction area has a dark background" + }, + { + "name": "IsFlipped", + "json_name": "is_flipped", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. Pass True if reaction area corner is flipped" + } + ] + }, + { + "name": "StoryAreaTypeLink", + "doc": "Describes a story area pointing to an HTTP or tg:// link. Currently, a story can have up to 3 link areas.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of the area, always “link”" + }, + { + "name": "URL", + "json_name": "url", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "HTTP or tg:// URL to be opened when the area is clicked" + } + ] + }, + { + "name": "StoryAreaTypeWeather", + "doc": "Describes a story area containing weather information. Currently, a story can have up to 3 weather areas.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of the area, always “weather”" + }, + { + "name": "Temperature", + "json_name": "temperature", + "type": { + "kind": "primitive", + "name": "float64" + }, + "required": true, + "doc": "Temperature, in degree Celsius" + }, + { + "name": "Emoji", + "json_name": "emoji", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Emoji representing the weather" + }, + { + "name": "BackgroundColor", + "json_name": "background_color", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "A color of the area background in the ARGB format" + } + ] + }, + { + "name": "StoryAreaTypeUniqueGift", + "doc": "Describes a story area pointing to a unique gift. Currently, a story can have at most 1 unique gift area.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of the area, always “unique_gift”" + }, + { + "name": "Name", + "json_name": "name", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique name of the gift" + } + ] + }, + { + "name": "StoryArea", + "doc": "Describes a clickable area on a story media.", + "fields": [ + { + "name": "Position", + "json_name": "position", + "type": { + "kind": "named", + "name": "StoryAreaPosition" + }, + "required": true, + "doc": "Position of the area" + }, + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "named", + "name": "StoryAreaType" + }, + "required": true, + "doc": "Type of the area" + } + ] + }, + { + "name": "ChatLocation", + "doc": "Represents a location to which a chat is connected.", + "fields": [ + { + "name": "Location", + "json_name": "location", + "type": { + "kind": "named", + "name": "Location" + }, + "required": true, + "doc": "The location to which the supergroup is connected. Can't be a live location." + }, + { + "name": "Address", + "json_name": "address", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Location address; 1-64 characters, as defined by the chat owner" + } + ] + }, + { + "name": "ReactionType", + "doc": "This object describes the type of a reaction. Currently, it can be one of", + "one_of": [ + "ReactionTypeEmoji", + "ReactionTypeCustomEmoji", + "ReactionTypePaid" + ] + }, + { + "name": "ReactionTypeEmoji", + "doc": "The reaction is based on an emoji.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of the reaction, always “emoji”" + }, + { + "name": "Emoji", + "json_name": "emoji", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Reaction emoji. Currently, it can be one of \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\"" + } + ] + }, + { + "name": "ReactionTypeCustomEmoji", + "doc": "The reaction is based on a custom emoji.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of the reaction, always “custom_emoji”" + }, + { + "name": "CustomEmojiID", + "json_name": "custom_emoji_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Custom emoji identifier" + } + ] + }, + { + "name": "ReactionTypePaid", + "doc": "The reaction is paid.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of the reaction, always “paid”" + } + ] + }, + { + "name": "ReactionCount", + "doc": "Represents a reaction added to a message along with the number of times it was added.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "named", + "name": "ReactionType" + }, + "required": true, + "doc": "Type of the reaction" + }, + { + "name": "TotalCount", + "json_name": "total_count", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Number of times the reaction was added" + } + ] + }, + { + "name": "MessageReactionUpdated", + "doc": "This object represents a change of a reaction on a message performed by a user.", + "fields": [ + { + "name": "Chat", + "json_name": "chat", + "type": { + "kind": "named", + "name": "Chat" + }, + "required": true, + "doc": "The chat containing the message the user reacted to" + }, + { + "name": "MessageID", + "json_name": "message_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Unique identifier of the message inside the chat" + }, + { + "name": "User", + "json_name": "user", + "type": { + "kind": "named", + "name": "User" + }, + "doc": "Optional. The user that changed the reaction, if the user isn't anonymous" + }, + { + "name": "ActorChat", + "json_name": "actor_chat", + "type": { + "kind": "named", + "name": "Chat" + }, + "doc": "Optional. The chat on behalf of which the reaction was changed, if the user is anonymous" + }, + { + "name": "Date", + "json_name": "date", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Date of the change in Unix time" + }, + { + "name": "OldReaction", + "json_name": "old_reaction", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "ReactionType" + } + }, + "required": true, + "doc": "Previous list of reaction types that were set by the user" + }, + { + "name": "NewReaction", + "json_name": "new_reaction", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "ReactionType" + } + }, + "required": true, + "doc": "New list of reaction types that have been set by the user" + } + ] + }, + { + "name": "MessageReactionCountUpdated", + "doc": "This object represents reaction changes on a message with anonymous reactions.", + "fields": [ + { + "name": "Chat", + "json_name": "chat", + "type": { + "kind": "named", + "name": "Chat" + }, + "required": true, + "doc": "The chat containing the message" + }, + { + "name": "MessageID", + "json_name": "message_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Unique message identifier inside the chat" + }, + { + "name": "Date", + "json_name": "date", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Date of the change in Unix time" + }, + { + "name": "Reactions", + "json_name": "reactions", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "ReactionCount" + } + }, + "required": true, + "doc": "List of reactions that are present on the message" + } + ] + }, + { + "name": "ForumTopic", + "doc": "This object represents a forum topic.", + "fields": [ + { + "name": "MessageThreadID", + "json_name": "message_thread_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Unique identifier of the forum topic" + }, + { + "name": "Name", + "json_name": "name", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Name of the topic" + }, + { + "name": "IconColor", + "json_name": "icon_color", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Color of the topic icon in RGB format" + }, + { + "name": "IconCustomEmojiID", + "json_name": "icon_custom_emoji_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Unique identifier of the custom emoji shown as the topic icon" + }, + { + "name": "IsNameImplicit", + "json_name": "is_name_implicit", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the name of the topic wasn't specified explicitly by its creator and likely needs to be changed by the bot" + } + ] + }, + { + "name": "GiftBackground", + "doc": "This object describes the background of a gift.", + "fields": [ + { + "name": "CenterColor", + "json_name": "center_color", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Center color of the background in RGB format" + }, + { + "name": "EdgeColor", + "json_name": "edge_color", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Edge color of the background in RGB format" + }, + { + "name": "TextColor", + "json_name": "text_color", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Text color of the background in RGB format" + } + ] + }, + { + "name": "Gift", + "doc": "This object represents a gift that can be sent by the bot.", + "fields": [ + { + "name": "ID", + "json_name": "id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique identifier of the gift" + }, + { + "name": "Sticker", + "json_name": "sticker", + "type": { + "kind": "named", + "name": "Sticker" + }, + "required": true, + "doc": "The sticker that represents the gift" + }, + { + "name": "StarCount", + "json_name": "star_count", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "The number of Telegram Stars that must be paid to send the sticker" + }, + { + "name": "UpgradeStarCount", + "json_name": "upgrade_star_count", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. The number of Telegram Stars that must be paid to upgrade the gift to a unique one" + }, + { + "name": "IsPremium", + "json_name": "is_premium", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the gift can only be purchased by Telegram Premium subscribers" + }, + { + "name": "HasColors", + "json_name": "has_colors", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the gift can be used (after being upgraded) to customize a user's appearance" + }, + { + "name": "TotalCount", + "json_name": "total_count", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. The total number of gifts of this type that can be sent by all users; for limited gifts only" + }, + { + "name": "RemainingCount", + "json_name": "remaining_count", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. The number of remaining gifts of this type that can be sent by all users; for limited gifts only" + }, + { + "name": "PersonalTotalCount", + "json_name": "personal_total_count", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. The total number of gifts of this type that can be sent by the bot; for limited gifts only" + }, + { + "name": "PersonalRemainingCount", + "json_name": "personal_remaining_count", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. The number of remaining gifts of this type that can be sent by the bot; for limited gifts only" + }, + { + "name": "Background", + "json_name": "background", + "type": { + "kind": "named", + "name": "GiftBackground" + }, + "doc": "Optional. Background of the gift" + }, + { + "name": "UniqueGiftVariantCount", + "json_name": "unique_gift_variant_count", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. The total number of different unique gifts that can be obtained by upgrading the gift" + }, + { + "name": "PublisherChat", + "json_name": "publisher_chat", + "type": { + "kind": "named", + "name": "Chat" + }, + "doc": "Optional. Information about the chat that published the gift" + } + ] + }, + { + "name": "Gifts", + "doc": "This object represent a list of gifts.", + "fields": [ + { + "name": "Gifts", + "json_name": "gifts", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "Gift" + } + }, + "required": true, + "doc": "The list of gifts" + } + ] + }, + { + "name": "UniqueGiftModel", + "doc": "This object describes the model of a unique gift.", + "fields": [ + { + "name": "Name", + "json_name": "name", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Name of the model" + }, + { + "name": "Sticker", + "json_name": "sticker", + "type": { + "kind": "named", + "name": "Sticker" + }, + "required": true, + "doc": "The sticker that represents the unique gift" + }, + { + "name": "RarityPerMille", + "json_name": "rarity_per_mille", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "The number of unique gifts that receive this model for every 1000 gift upgrades. Always 0 for crafted gifts." + }, + { + "name": "Rarity", + "json_name": "rarity", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Rarity of the model if it is a crafted model. Currently, can be “uncommon”, “rare”, “epic”, or “legendary”." + } + ] + }, + { + "name": "UniqueGiftSymbol", + "doc": "This object describes the symbol shown on the pattern of a unique gift.", + "fields": [ + { + "name": "Name", + "json_name": "name", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Name of the symbol" + }, + { + "name": "Sticker", + "json_name": "sticker", + "type": { + "kind": "named", + "name": "Sticker" + }, + "required": true, + "doc": "The sticker that represents the unique gift" + }, + { + "name": "RarityPerMille", + "json_name": "rarity_per_mille", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "The number of unique gifts that receive this model for every 1000 gifts upgraded" + } + ] + }, + { + "name": "UniqueGiftBackdropColors", + "doc": "This object describes the colors of the backdrop of a unique gift.", + "fields": [ + { + "name": "CenterColor", + "json_name": "center_color", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "The color in the center of the backdrop in RGB format" + }, + { + "name": "EdgeColor", + "json_name": "edge_color", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "The color on the edges of the backdrop in RGB format" + }, + { + "name": "SymbolColor", + "json_name": "symbol_color", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "The color to be applied to the symbol in RGB format" + }, + { + "name": "TextColor", + "json_name": "text_color", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "The color for the text on the backdrop in RGB format" + } + ] + }, + { + "name": "UniqueGiftBackdrop", + "doc": "This object describes the backdrop of a unique gift.", + "fields": [ + { + "name": "Name", + "json_name": "name", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Name of the backdrop" + }, + { + "name": "Colors", + "json_name": "colors", + "type": { + "kind": "named", + "name": "UniqueGiftBackdropColors" + }, + "required": true, + "doc": "Colors of the backdrop" + }, + { + "name": "RarityPerMille", + "json_name": "rarity_per_mille", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "The number of unique gifts that receive this backdrop for every 1000 gifts upgraded" + } + ] + }, + { + "name": "UniqueGiftColors", + "doc": "This object contains information about the color scheme for a user's name, message replies and link previews based on a unique gift.", + "fields": [ + { + "name": "ModelCustomEmojiID", + "json_name": "model_custom_emoji_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Custom emoji identifier of the unique gift's model" + }, + { + "name": "SymbolCustomEmojiID", + "json_name": "symbol_custom_emoji_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Custom emoji identifier of the unique gift's symbol" + }, + { + "name": "LightThemeMainColor", + "json_name": "light_theme_main_color", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Main color used in light themes; RGB format" + }, + { + "name": "LightThemeOtherColors", + "json_name": "light_theme_other_colors", + "type": { + "kind": "array", + "elem_type": { + "kind": "primitive", + "name": "int64" + } + }, + "required": true, + "doc": "List of 1-3 additional colors used in light themes; RGB format" + }, + { + "name": "DarkThemeMainColor", + "json_name": "dark_theme_main_color", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Main color used in dark themes; RGB format" + }, + { + "name": "DarkThemeOtherColors", + "json_name": "dark_theme_other_colors", + "type": { + "kind": "array", + "elem_type": { + "kind": "primitive", + "name": "int64" + } + }, + "required": true, + "doc": "List of 1-3 additional colors used in dark themes; RGB format" + } + ] + }, + { + "name": "UniqueGift", + "doc": "This object describes a unique gift that was upgraded from a regular gift.", + "fields": [ + { + "name": "GiftID", + "json_name": "gift_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Identifier of the regular gift from which the gift was upgraded" + }, + { + "name": "BaseName", + "json_name": "base_name", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Human-readable name of the regular gift from which this unique gift was upgraded" + }, + { + "name": "Name", + "json_name": "name", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique name of the gift. This name can be used in https://t.me/nft/... links and story areas" + }, + { + "name": "Number", + "json_name": "number", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Unique number of the upgraded gift among gifts upgraded from the same regular gift" + }, + { + "name": "Model", + "json_name": "model", + "type": { + "kind": "named", + "name": "UniqueGiftModel" + }, + "required": true, + "doc": "Model of the gift" + }, + { + "name": "Symbol", + "json_name": "symbol", + "type": { + "kind": "named", + "name": "UniqueGiftSymbol" + }, + "required": true, + "doc": "Symbol of the gift" + }, + { + "name": "Backdrop", + "json_name": "backdrop", + "type": { + "kind": "named", + "name": "UniqueGiftBackdrop" + }, + "required": true, + "doc": "Backdrop of the gift" + }, + { + "name": "IsPremium", + "json_name": "is_premium", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the original regular gift was exclusively purchaseable by Telegram Premium subscribers" + }, + { + "name": "IsBurned", + "json_name": "is_burned", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the gift was used to craft another gift and isn't available anymore" + }, + { + "name": "IsFromBlockchain", + "json_name": "is_from_blockchain", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the gift is assigned from the TON blockchain and can't be resold or transferred in Telegram" + }, + { + "name": "Colors", + "json_name": "colors", + "type": { + "kind": "named", + "name": "UniqueGiftColors" + }, + "doc": "Optional. The color scheme that can be used by the gift's owner for the chat's name, replies to messages and link previews; for business account gifts and gifts that are currently on sale only" + }, + { + "name": "PublisherChat", + "json_name": "publisher_chat", + "type": { + "kind": "named", + "name": "Chat" + }, + "doc": "Optional. Information about the chat that published the gift" + } + ] + }, + { + "name": "GiftInfo", + "doc": "Describes a service message about a regular gift that was sent or received.", + "fields": [ + { + "name": "Gift", + "json_name": "gift", + "type": { + "kind": "named", + "name": "Gift" + }, + "required": true, + "doc": "Information about the gift" + }, + { + "name": "OwnedGiftID", + "json_name": "owned_gift_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Unique identifier of the received gift for the bot; only present for gifts received on behalf of business accounts" + }, + { + "name": "ConvertStarCount", + "json_name": "convert_star_count", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. Number of Telegram Stars that can be claimed by the receiver by converting the gift; omitted if conversion to Telegram Stars is impossible" + }, + { + "name": "PrepaidUpgradeStarCount", + "json_name": "prepaid_upgrade_star_count", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. Number of Telegram Stars that were prepaid for the ability to upgrade the gift" + }, + { + "name": "IsUpgradeSeparate", + "json_name": "is_upgrade_separate", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the gift's upgrade was purchased after the gift was sent" + }, + { + "name": "CanBeUpgraded", + "json_name": "can_be_upgraded", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the gift can be upgraded to a unique gift" + }, + { + "name": "Text", + "json_name": "text", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Text of the message that was added to the gift" + }, + { + "name": "Entities", + "json_name": "entities", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "MessageEntity" + } + }, + "doc": "Optional. Special entities that appear in the text" + }, + { + "name": "IsPrivate", + "json_name": "is_private", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the sender and gift text are shown only to the gift receiver; otherwise, everyone will be able to see them" + }, + { + "name": "UniqueGiftNumber", + "json_name": "unique_gift_number", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. Unique number reserved for this gift when upgraded. See the number field in UniqueGift" + } + ] + }, + { + "name": "UniqueGiftInfo", + "doc": "Describes a service message about a unique gift that was sent or received.", + "fields": [ + { + "name": "Gift", + "json_name": "gift", + "type": { + "kind": "named", + "name": "UniqueGift" + }, + "required": true, + "doc": "Information about the gift" + }, + { + "name": "Origin", + "json_name": "origin", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Origin of the gift. Currently, either “upgrade” for gifts upgraded from regular gifts, “transfer” for gifts transferred from other users or channels, “resale” for gifts bought from other users, “gifted_upgrade” for upgrades purchased after the gift was sent, or “offer” for gifts bought or sold through gift purchase offers" + }, + { + "name": "LastResaleCurrency", + "json_name": "last_resale_currency", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. For gifts bought from other users, the currency in which the payment for the gift was done. Currently, one of “XTR” for Telegram Stars or “TON” for toncoins." + }, + { + "name": "LastResaleAmount", + "json_name": "last_resale_amount", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. For gifts bought from other users, the price paid for the gift in either Telegram Stars or nanotoncoins" + }, + { + "name": "OwnedGiftID", + "json_name": "owned_gift_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Unique identifier of the received gift for the bot; only present for gifts received on behalf of business accounts" + }, + { + "name": "TransferStarCount", + "json_name": "transfer_star_count", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. Number of Telegram Stars that must be paid to transfer the gift; omitted if the bot cannot transfer the gift" + }, + { + "name": "NextTransferDate", + "json_name": "next_transfer_date", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. Point in time (Unix timestamp) when the gift can be transferred. If it is in the past, then the gift can be transferred now" + } + ] + }, + { + "name": "OwnedGift", + "doc": "This object describes a gift received and owned by a user or a chat. Currently, it can be one of", + "one_of": [ + "OwnedGiftRegular", + "OwnedGiftUnique" + ] + }, + { + "name": "OwnedGiftRegular", + "doc": "Describes a regular gift owned by a user or a chat.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of the gift, always “regular”" + }, + { + "name": "Gift", + "json_name": "gift", + "type": { + "kind": "named", + "name": "Gift" + }, + "required": true, + "doc": "Information about the regular gift" + }, + { + "name": "OwnedGiftID", + "json_name": "owned_gift_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Unique identifier of the gift for the bot; for gifts received on behalf of business accounts only" + }, + { + "name": "SenderUser", + "json_name": "sender_user", + "type": { + "kind": "named", + "name": "User" + }, + "doc": "Optional. Sender of the gift if it is a known user" + }, + { + "name": "SendDate", + "json_name": "send_date", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Date the gift was sent in Unix time" + }, + { + "name": "Text", + "json_name": "text", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Text of the message that was added to the gift" + }, + { + "name": "Entities", + "json_name": "entities", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "MessageEntity" + } + }, + "doc": "Optional. Special entities that appear in the text" + }, + { + "name": "IsPrivate", + "json_name": "is_private", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the sender and gift text are shown only to the gift receiver; otherwise, everyone will be able to see them" + }, + { + "name": "IsSaved", + "json_name": "is_saved", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the gift is displayed on the account's profile page; for gifts received on behalf of business accounts only" + }, + { + "name": "CanBeUpgraded", + "json_name": "can_be_upgraded", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the gift can be upgraded to a unique gift; for gifts received on behalf of business accounts only" + }, + { + "name": "WasRefunded", + "json_name": "was_refunded", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the gift was refunded and isn't available anymore" + }, + { + "name": "ConvertStarCount", + "json_name": "convert_star_count", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. Number of Telegram Stars that can be claimed by the receiver instead of the gift; omitted if the gift cannot be converted to Telegram Stars; for gifts received on behalf of business accounts only" + }, + { + "name": "PrepaidUpgradeStarCount", + "json_name": "prepaid_upgrade_star_count", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. Number of Telegram Stars that were paid for the ability to upgrade the gift" + }, + { + "name": "IsUpgradeSeparate", + "json_name": "is_upgrade_separate", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the gift's upgrade was purchased after the gift was sent; for gifts received on behalf of business accounts only" + }, + { + "name": "UniqueGiftNumber", + "json_name": "unique_gift_number", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. Unique number reserved for this gift when upgraded. See the number field in UniqueGift" + } + ] + }, + { + "name": "OwnedGiftUnique", + "doc": "Describes a unique gift received and owned by a user or a chat.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of the gift, always “unique”" + }, + { + "name": "Gift", + "json_name": "gift", + "type": { + "kind": "named", + "name": "UniqueGift" + }, + "required": true, + "doc": "Information about the unique gift" + }, + { + "name": "OwnedGiftID", + "json_name": "owned_gift_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Unique identifier of the received gift for the bot; for gifts received on behalf of business accounts only" + }, + { + "name": "SenderUser", + "json_name": "sender_user", + "type": { + "kind": "named", + "name": "User" + }, + "doc": "Optional. Sender of the gift if it is a known user" + }, + { + "name": "SendDate", + "json_name": "send_date", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Date the gift was sent in Unix time" + }, + { + "name": "IsSaved", + "json_name": "is_saved", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the gift is displayed on the account's profile page; for gifts received on behalf of business accounts only" + }, + { + "name": "CanBeTransferred", + "json_name": "can_be_transferred", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the gift can be transferred to another owner; for gifts received on behalf of business accounts only" + }, + { + "name": "TransferStarCount", + "json_name": "transfer_star_count", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. Number of Telegram Stars that must be paid to transfer the gift; omitted if the bot cannot transfer the gift" + }, + { + "name": "NextTransferDate", + "json_name": "next_transfer_date", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. Point in time (Unix timestamp) when the gift can be transferred. If it is in the past, then the gift can be transferred now" + } + ] + }, + { + "name": "OwnedGifts", + "doc": "Contains the list of gifts received and owned by a user or a chat.", + "fields": [ + { + "name": "TotalCount", + "json_name": "total_count", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "The total number of gifts owned by the user or the chat" + }, + { + "name": "Gifts", + "json_name": "gifts", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "OwnedGift" + } + }, + "required": true, + "doc": "The list of gifts" + }, + { + "name": "NextOffset", + "json_name": "next_offset", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Offset for the next request. If empty, then there are no more results" + } + ] + }, + { + "name": "BotAccessSettings", + "doc": "This object describes the access settings of a bot.", + "fields": [ + { + "name": "IsAccessRestricted", + "json_name": "is_access_restricted", + "type": { + "kind": "primitive", + "name": "bool" + }, + "required": true, + "doc": "True, if only selected users can access the bot. The bot's owner can always access it." + }, + { + "name": "AddedUsers", + "json_name": "added_users", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "User" + } + }, + "doc": "Optional. The list of other users who have access to the bot if the access is restricted" + } + ] + }, + { + "name": "AcceptedGiftTypes", + "doc": "This object describes the types of gifts that can be gifted to a user or a chat.", + "fields": [ + { + "name": "UnlimitedGifts", + "json_name": "unlimited_gifts", + "type": { + "kind": "primitive", + "name": "bool" + }, + "required": true, + "doc": "True, if unlimited regular gifts are accepted" + }, + { + "name": "LimitedGifts", + "json_name": "limited_gifts", + "type": { + "kind": "primitive", + "name": "bool" + }, + "required": true, + "doc": "True, if limited regular gifts are accepted" + }, + { + "name": "UniqueGifts", + "json_name": "unique_gifts", + "type": { + "kind": "primitive", + "name": "bool" + }, + "required": true, + "doc": "True, if unique gifts or gifts that can be upgraded to unique for free are accepted" + }, + { + "name": "PremiumSubscription", + "json_name": "premium_subscription", + "type": { + "kind": "primitive", + "name": "bool" + }, + "required": true, + "doc": "True, if a Telegram Premium subscription is accepted" + }, + { + "name": "GiftsFromChannels", + "json_name": "gifts_from_channels", + "type": { + "kind": "primitive", + "name": "bool" + }, + "required": true, + "doc": "True, if transfers of unique gifts from channels are accepted" + } + ] + }, + { + "name": "StarAmount", + "doc": "Describes an amount of Telegram Stars.", + "fields": [ + { + "name": "Amount", + "json_name": "amount", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Integer amount of Telegram Stars, rounded to 0; can be negative" + }, + { + "name": "NanostarAmount", + "json_name": "nanostar_amount", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. The number of 1/1000000000 shares of Telegram Stars; from -999999999 to 999999999; can be negative if and only if amount is non-positive" + } + ] + }, + { + "name": "BotCommand", + "doc": "This object represents a bot command.", + "fields": [ + { + "name": "Command", + "json_name": "command", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Text of the command; 1-32 characters. Can contain only lowercase English letters, digits and underscores." + }, + { + "name": "Description", + "json_name": "description", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Description of the command; 1-256 characters." + } + ] + }, + { + "name": "BotCommandScope", + "doc": "This object represents the scope to which bot commands are applied. Currently, the following 7 scopes are supported:", + "one_of": [ + "BotCommandScopeDefault", + "BotCommandScopeAllPrivateChats", + "BotCommandScopeAllGroupChats", + "BotCommandScopeAllChatAdministrators", + "BotCommandScopeChat", + "BotCommandScopeChatAdministrators", + "BotCommandScopeChatMember" + ] + }, + { + "name": "BotCommandScopeDefault", + "doc": "Represents the default scope of bot commands. Default commands are used if no commands with a narrower scope are specified for the user.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Scope type, must be default" + } + ] + }, + { + "name": "BotCommandScopeAllPrivateChats", + "doc": "Represents the scope of bot commands, covering all private chats.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Scope type, must be all_private_chats" + } + ] + }, + { + "name": "BotCommandScopeAllGroupChats", + "doc": "Represents the scope of bot commands, covering all group and supergroup chats.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Scope type, must be all_group_chats" + } + ] + }, + { + "name": "BotCommandScopeAllChatAdministrators", + "doc": "Represents the scope of bot commands, covering all group and supergroup chat administrators.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Scope type, must be all_chat_administrators" + } + ] + }, + { + "name": "BotCommandScopeChat", + "doc": "Represents the scope of bot commands, covering a specific chat.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Scope type, must be chat" + }, + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the target chat or username of the target supergroup in the format @username. Channel direct messages chats and channel chats aren't supported." + } + ] + }, + { + "name": "BotCommandScopeChatAdministrators", + "doc": "Represents the scope of bot commands, covering all administrators of a specific group or supergroup chat.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Scope type, must be chat_administrators" + }, + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the target chat or username of the target supergroup in the format @username. Channel direct messages chats and channel chats aren't supported." + } + ] + }, + { + "name": "BotCommandScopeChatMember", + "doc": "Represents the scope of bot commands, covering a specific member of a group or supergroup chat.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Scope type, must be chat_member" + }, + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the target chat or username of the target supergroup in the format @username. Channel direct messages chats and channel chats aren't supported." + }, + { + "name": "UserID", + "json_name": "user_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Unique identifier of the target user" + } + ] + }, + { + "name": "BotName", + "doc": "This object represents the bot's name.", + "fields": [ + { + "name": "Name", + "json_name": "name", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "The bot's name" + } + ] + }, + { + "name": "BotDescription", + "doc": "This object represents the bot's description.", + "fields": [ + { + "name": "Description", + "json_name": "description", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "The bot's description" + } + ] + }, + { + "name": "BotShortDescription", + "doc": "This object represents the bot's short description.", + "fields": [ + { + "name": "ShortDescription", + "json_name": "short_description", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "The bot's short description" + } + ] + }, + { + "name": "MenuButton", + "doc": "This object describes the bot's menu button in a private chat. It should be one of\nIf a menu button other than MenuButtonDefault is set for a private chat, then it is applied in the chat. Otherwise the default menu button is applied. By default, the menu button opens the list of bot commands.", + "one_of": [ + "MenuButtonCommands", + "MenuButtonWebApp", + "MenuButtonDefault" + ] + }, + { + "name": "MenuButtonCommands", + "doc": "Represents a menu button, which opens the bot's list of commands.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of the button, must be commands" + } + ] + }, + { + "name": "MenuButtonWebApp", + "doc": "Represents a menu button, which launches a Web App.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of the button, must be web_app" + }, + { + "name": "Text", + "json_name": "text", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Text on the button" + }, + { + "name": "WebApp", + "json_name": "web_app", + "type": { + "kind": "named", + "name": "WebAppInfo" + }, + "required": true, + "doc": "Description of the Web App that will be launched when the user presses the button. The Web App will be able to send an arbitrary message on behalf of the user using the method answerWebAppQuery. Alternatively, a t.me link to a Web App of the bot can be specified in the object instead of the Web App's URL, in which case the Web App will be opened as if the user pressed the link." + } + ] + }, + { + "name": "MenuButtonDefault", + "doc": "Describes that no specific value for the menu button was set.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of the button, must be default" + } + ] + }, + { + "name": "ChatBoostSource", + "doc": "This object describes the source of a chat boost. It can be one of", + "one_of": [ + "ChatBoostSourcePremium", + "ChatBoostSourceGiftCode", + "ChatBoostSourceGiveaway" + ] + }, + { + "name": "ChatBoostSourcePremium", + "doc": "The boost was obtained by subscribing to Telegram Premium or by gifting a Telegram Premium subscription to another user.", + "fields": [ + { + "name": "Source", + "json_name": "source", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Source of the boost, always “premium”" + }, + { + "name": "User", + "json_name": "user", + "type": { + "kind": "named", + "name": "User" + }, + "required": true, + "doc": "User that boosted the chat" + } + ] + }, + { + "name": "ChatBoostSourceGiftCode", + "doc": "The boost was obtained by the creation of Telegram Premium gift codes to boost a chat. Each such code boosts the chat 4 times for the duration of the corresponding Telegram Premium subscription.", + "fields": [ + { + "name": "Source", + "json_name": "source", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Source of the boost, always “gift_code”" + }, + { + "name": "User", + "json_name": "user", + "type": { + "kind": "named", + "name": "User" + }, + "required": true, + "doc": "User for which the gift code was created" + } + ] + }, + { + "name": "ChatBoostSourceGiveaway", + "doc": "The boost was obtained by the creation of a Telegram Premium or a Telegram Star giveaway. This boosts the chat 4 times for the duration of the corresponding Telegram Premium subscription for Telegram Premium giveaways and prize_star_count / 500 times for one year for Telegram Star giveaways.", + "fields": [ + { + "name": "Source", + "json_name": "source", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Source of the boost, always “giveaway”" + }, + { + "name": "GiveawayMessageID", + "json_name": "giveaway_message_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Identifier of a message in the chat with the giveaway; the message could have been deleted already. May be 0 if the message isn't sent yet." + }, + { + "name": "User", + "json_name": "user", + "type": { + "kind": "named", + "name": "User" + }, + "doc": "Optional. User that won the prize in the giveaway if any; for Telegram Premium giveaways only" + }, + { + "name": "PrizeStarCount", + "json_name": "prize_star_count", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. The number of Telegram Stars to be split between giveaway winners; for Telegram Star giveaways only" + }, + { + "name": "IsUnclaimed", + "json_name": "is_unclaimed", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the giveaway was completed, but there was no user to win the prize" + } + ] + }, + { + "name": "ChatBoost", + "doc": "This object contains information about a chat boost.", + "fields": [ + { + "name": "BoostID", + "json_name": "boost_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique identifier of the boost" + }, + { + "name": "AddDate", + "json_name": "add_date", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Point in time (Unix timestamp) when the chat was boosted" + }, + { + "name": "ExpirationDate", + "json_name": "expiration_date", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Point in time (Unix timestamp) when the boost will automatically expire, unless the booster's Telegram Premium subscription is prolonged" + }, + { + "name": "Source", + "json_name": "source", + "type": { + "kind": "named", + "name": "ChatBoostSource" + }, + "required": true, + "doc": "Source of the added boost" + } + ] + }, + { + "name": "ChatBoostUpdated", + "doc": "This object represents a boost added to a chat or changed.", + "fields": [ + { + "name": "Chat", + "json_name": "chat", + "type": { + "kind": "named", + "name": "Chat" + }, + "required": true, + "doc": "Chat which was boosted" + }, + { + "name": "Boost", + "json_name": "boost", + "type": { + "kind": "named", + "name": "ChatBoost" + }, + "required": true, + "doc": "Information about the chat boost" + } + ] + }, + { + "name": "ChatBoostRemoved", + "doc": "This object represents a boost removed from a chat.", + "fields": [ + { + "name": "Chat", + "json_name": "chat", + "type": { + "kind": "named", + "name": "Chat" + }, + "required": true, + "doc": "Chat which was boosted" + }, + { + "name": "BoostID", + "json_name": "boost_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique identifier of the boost" + }, + { + "name": "RemoveDate", + "json_name": "remove_date", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Point in time (Unix timestamp) when the boost was removed" + }, + { + "name": "Source", + "json_name": "source", + "type": { + "kind": "named", + "name": "ChatBoostSource" + }, + "required": true, + "doc": "Source of the removed boost" + } + ] + }, + { + "name": "ChatOwnerLeft", + "doc": "Describes a service message about the chat owner leaving the chat.", + "fields": [ + { + "name": "NewOwner", + "json_name": "new_owner", + "type": { + "kind": "named", + "name": "User" + }, + "doc": "Optional. The user who will become the new owner of the chat if the previous owner does not return to the chat" + } + ] + }, + { + "name": "ChatOwnerChanged", + "doc": "Describes a service message about an ownership change in the chat.", + "fields": [ + { + "name": "NewOwner", + "json_name": "new_owner", + "type": { + "kind": "named", + "name": "User" + }, + "required": true, + "doc": "The new owner of the chat" + } + ] + }, + { + "name": "UserChatBoosts", + "doc": "This object represents a list of boosts added to a chat by a user.", + "fields": [ + { + "name": "Boosts", + "json_name": "boosts", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "ChatBoost" + } + }, + "required": true, + "doc": "The list of boosts added to the chat by the user" + } + ] + }, + { + "name": "BusinessBotRights", + "doc": "Represents the rights of a business bot.", + "fields": [ + { + "name": "CanReply", + "json_name": "can_reply", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the bot can send and edit messages in the private chats that had incoming messages in the last 24 hours" + }, + { + "name": "CanReadMessages", + "json_name": "can_read_messages", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the bot can mark incoming private messages as read" + }, + { + "name": "CanDeleteSentMessages", + "json_name": "can_delete_sent_messages", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the bot can delete messages sent by the bot" + }, + { + "name": "CanDeleteAllMessages", + "json_name": "can_delete_all_messages", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the bot can delete all private messages in managed chats" + }, + { + "name": "CanEditName", + "json_name": "can_edit_name", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the bot can edit the first and last name of the business account" + }, + { + "name": "CanEditBio", + "json_name": "can_edit_bio", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the bot can edit the bio of the business account" + }, + { + "name": "CanEditProfilePhoto", + "json_name": "can_edit_profile_photo", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the bot can edit the profile photo of the business account" + }, + { + "name": "CanEditUsername", + "json_name": "can_edit_username", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the bot can edit the username of the business account" + }, + { + "name": "CanChangeGiftSettings", + "json_name": "can_change_gift_settings", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the bot can change the privacy settings pertaining to gifts for the business account" + }, + { + "name": "CanViewGiftsAndStars", + "json_name": "can_view_gifts_and_stars", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the bot can view gifts and the amount of Telegram Stars owned by the business account" + }, + { + "name": "CanConvertGiftsToStars", + "json_name": "can_convert_gifts_to_stars", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the bot can convert regular gifts owned by the business account to Telegram Stars" + }, + { + "name": "CanTransferAndUpgradeGifts", + "json_name": "can_transfer_and_upgrade_gifts", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the bot can transfer and upgrade gifts owned by the business account" + }, + { + "name": "CanTransferStars", + "json_name": "can_transfer_stars", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the bot can transfer Telegram Stars received by the business account to its own account, or use them to upgrade and transfer gifts" + }, + { + "name": "CanManageStories", + "json_name": "can_manage_stories", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the bot can post, edit and delete stories on behalf of the business account" + } + ] + }, + { + "name": "BusinessConnection", + "doc": "Describes the connection of the bot with a business account.", + "fields": [ + { + "name": "ID", + "json_name": "id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique identifier of the business connection" + }, + { + "name": "User", + "json_name": "user", + "type": { + "kind": "named", + "name": "User" + }, + "required": true, + "doc": "Business account user that created the business connection" + }, + { + "name": "UserChatID", + "json_name": "user_chat_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Identifier of a private chat with the user who created the business connection. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a 64-bit integer or double-precision float type are safe for storing this identifier." + }, + { + "name": "Date", + "json_name": "date", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Date the connection was established in Unix time" + }, + { + "name": "Rights", + "json_name": "rights", + "type": { + "kind": "named", + "name": "BusinessBotRights" + }, + "doc": "Optional. Rights of the business bot" + }, + { + "name": "IsEnabled", + "json_name": "is_enabled", + "type": { + "kind": "primitive", + "name": "bool" + }, + "required": true, + "doc": "True, if the connection is active" + } + ] + }, + { + "name": "BusinessMessagesDeleted", + "doc": "This object is received when messages are deleted from a connected business account.", + "fields": [ + { + "name": "BusinessConnectionID", + "json_name": "business_connection_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique identifier of the business connection" + }, + { + "name": "Chat", + "json_name": "chat", + "type": { + "kind": "named", + "name": "Chat" + }, + "required": true, + "doc": "Information about a chat in the business account. The bot may not have access to the chat or the corresponding user." + }, + { + "name": "MessageIds", + "json_name": "message_ids", + "type": { + "kind": "array", + "elem_type": { + "kind": "primitive", + "name": "int64" + } + }, + "required": true, + "doc": "The list of identifiers of deleted messages in the chat of the business account" + } + ] + }, + { + "name": "SentWebAppMessage", + "doc": "Describes an inline message sent by a Web App on behalf of a user.", + "fields": [ + { + "name": "InlineMessageID", + "json_name": "inline_message_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Identifier of the sent inline message. Available only if there is an inline keyboard attached to the message." + } + ] + }, + { + "name": "SentGuestMessage", + "doc": "Describes an inline message sent by a guest bot.", + "fields": [ + { + "name": "InlineMessageID", + "json_name": "inline_message_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Identifier of the sent inline message" + } + ] + }, + { + "name": "PreparedInlineMessage", + "doc": "Describes an inline message to be sent by a user of a Mini App.", + "fields": [ + { + "name": "ID", + "json_name": "id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique identifier of the prepared message" + }, + { + "name": "ExpirationDate", + "json_name": "expiration_date", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Expiration date of the prepared message, in Unix time. Expired prepared messages can no longer be used" + } + ] + }, + { + "name": "PreparedKeyboardButton", + "doc": "Describes a keyboard button to be used by a user of a Mini App.", + "fields": [ + { + "name": "ID", + "json_name": "id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique identifier of the keyboard button" + } + ] + }, + { + "name": "ResponseParameters", + "doc": "Describes why a request was unsuccessful.", + "fields": [ + { + "name": "MigrateToChatID", + "json_name": "migrate_to_chat_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. The group has been migrated to a supergroup with the specified identifier. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this identifier." + }, + { + "name": "RetryAfter", + "json_name": "retry_after", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. In case of exceeding flood control, the number of seconds left to wait before the request can be repeated" + } + ] + }, + { + "name": "InputMedia", + "doc": "This object represents the content of a media message to be sent. It should be one of", + "one_of": [ + "InputMediaAnimation", + "InputMediaAudio", + "InputMediaDocument", + "InputMediaLivePhoto", + "InputMediaPhoto", + "InputMediaVideo" + ] + }, + { + "name": "InputMediaAnimation", + "doc": "Represents an animation file (GIF or H.264/MPEG-4 AVC video without sound) to be sent.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of the result, must be animation" + }, + { + "name": "Media", + "json_name": "media", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "File to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet, or pass “attach://” to upload a new one using multipart/form-data under name. More information on Sending Files »" + }, + { + "name": "Thumbnail", + "json_name": "thumbnail", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://” if the thumbnail was uploaded using multipart/form-data under . More information on Sending Files »" + }, + { + "name": "Caption", + "json_name": "caption", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Caption of the animation to be sent, 0-1024 characters after entities parsing" + }, + { + "name": "ParseMode", + "json_name": "parse_mode", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Mode for parsing entities in the animation caption. See formatting options for more details." + }, + { + "name": "CaptionEntities", + "json_name": "caption_entities", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "MessageEntity" + } + }, + "doc": "Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode" + }, + { + "name": "ShowCaptionAboveMedia", + "json_name": "show_caption_above_media", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. Pass True, if the caption must be shown above the message media" + }, + { + "name": "Width", + "json_name": "width", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. Animation width" + }, + { + "name": "Height", + "json_name": "height", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. Animation height" + }, + { + "name": "Duration", + "json_name": "duration", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. Animation duration in seconds" + }, + { + "name": "HasSpoiler", + "json_name": "has_spoiler", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. Pass True if the animation needs to be covered with a spoiler animation" + } + ] + }, + { + "name": "InputMediaAudio", + "doc": "Represents an audio file to be treated as music to be sent.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of the result, must be audio" + }, + { + "name": "Media", + "json_name": "media", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "File to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet, or pass “attach://” to upload a new one using multipart/form-data under name. More information on Sending Files »" + }, + { + "name": "Thumbnail", + "json_name": "thumbnail", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://” if the thumbnail was uploaded using multipart/form-data under . More information on Sending Files »" + }, + { + "name": "Caption", + "json_name": "caption", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Caption of the audio to be sent, 0-1024 characters after entities parsing" + }, + { + "name": "ParseMode", + "json_name": "parse_mode", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Mode for parsing entities in the audio caption. See formatting options for more details." + }, + { + "name": "CaptionEntities", + "json_name": "caption_entities", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "MessageEntity" + } + }, + "doc": "Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode" + }, + { + "name": "Duration", + "json_name": "duration", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. Duration of the audio in seconds" + }, + { + "name": "Performer", + "json_name": "performer", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Performer of the audio" + }, + { + "name": "Title", + "json_name": "title", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Title of the audio" + } + ] + }, + { + "name": "InputMediaDocument", + "doc": "Represents a general file to be sent.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of the result, must be document" + }, + { + "name": "Media", + "json_name": "media", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "File to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet, or pass “attach://” to upload a new one using multipart/form-data under name. More information on Sending Files »" + }, + { + "name": "Thumbnail", + "json_name": "thumbnail", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://” if the thumbnail was uploaded using multipart/form-data under . More information on Sending Files »" + }, + { + "name": "Caption", + "json_name": "caption", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Caption of the document to be sent, 0-1024 characters after entities parsing" + }, + { + "name": "ParseMode", + "json_name": "parse_mode", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Mode for parsing entities in the document caption. See formatting options for more details." + }, + { + "name": "CaptionEntities", + "json_name": "caption_entities", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "MessageEntity" + } + }, + "doc": "Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode" + }, + { + "name": "DisableContentTypeDetection", + "json_name": "disable_content_type_detection", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. Disables automatic server-side content type detection for files uploaded using multipart/form-data. Always True, if the document is sent as part of an album." + } + ] + }, + { + "name": "InputMediaLivePhoto", + "doc": "Represents a live photo to be sent.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of the result, must be live_photo" + }, + { + "name": "Media", + "json_name": "media", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Video of the live photo to send. Pass a file_id to send a file that exists on the Telegram servers (recommended) or pass “attach://” to upload a new one using multipart/form-data under name. More information on Sending Files ». Sending live photos by a URL is currently unsupported." + }, + { + "name": "Photo", + "json_name": "photo", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "The static photo to send. Pass a file_id to send a file that exists on the Telegram servers (recommended) or pass “attach://” to upload a new one using multipart/form-data under name. More information on Sending Files ». Sending live photos by a URL is currently unsupported." + }, + { + "name": "Caption", + "json_name": "caption", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Caption of the live photo to be sent, 0-1024 characters after entities parsing" + }, + { + "name": "ParseMode", + "json_name": "parse_mode", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Mode for parsing entities in the live photo caption. See formatting options for more details." + }, + { + "name": "CaptionEntities", + "json_name": "caption_entities", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "MessageEntity" + } + }, + "doc": "Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode" + }, + { + "name": "ShowCaptionAboveMedia", + "json_name": "show_caption_above_media", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. Pass True, if the caption must be shown above the message media" + }, + { + "name": "HasSpoiler", + "json_name": "has_spoiler", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. Pass True if the live photo needs to be covered with a spoiler animation" + } + ] + }, + { + "name": "InputMediaLocation", + "doc": "Represents a location to be sent.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of the result, must be location" + }, + { + "name": "Latitude", + "json_name": "latitude", + "type": { + "kind": "primitive", + "name": "float64" + }, + "required": true, + "doc": "Latitude of the location" + }, + { + "name": "Longitude", + "json_name": "longitude", + "type": { + "kind": "primitive", + "name": "float64" + }, + "required": true, + "doc": "Longitude of the location" + }, + { + "name": "HorizontalAccuracy", + "json_name": "horizontal_accuracy", + "type": { + "kind": "primitive", + "name": "float64" + }, + "doc": "Optional. The radius of uncertainty for the location, measured in meters; 0-1500" + } + ] + }, + { + "name": "InputMediaPhoto", + "doc": "Represents a photo to be sent.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of the result, must be photo" + }, + { + "name": "Media", + "json_name": "media", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "File to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet, or pass “attach://” to upload a new one using multipart/form-data under name. More information on Sending Files »" + }, + { + "name": "Caption", + "json_name": "caption", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Caption of the photo to be sent, 0-1024 characters after entities parsing" + }, + { + "name": "ParseMode", + "json_name": "parse_mode", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Mode for parsing entities in the photo caption. See formatting options for more details." + }, + { + "name": "CaptionEntities", + "json_name": "caption_entities", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "MessageEntity" + } + }, + "doc": "Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode" + }, + { + "name": "ShowCaptionAboveMedia", + "json_name": "show_caption_above_media", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. Pass True, if the caption must be shown above the message media" + }, + { + "name": "HasSpoiler", + "json_name": "has_spoiler", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. Pass True if the photo needs to be covered with a spoiler animation" + } + ] + }, + { + "name": "InputMediaSticker", + "doc": "Represents a sticker file to be sent.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of the result, must be sticker" + }, + { + "name": "Media", + "json_name": "media", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "File to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for Telegram to get a .WEBP sticker from the Internet, or pass “attach://” to upload a new .WEBP, .TGS, or .WEBM sticker using multipart/form-data under name. More information on Sending Files »" + }, + { + "name": "Emoji", + "json_name": "emoji", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Emoji associated with the sticker; only for just uploaded stickers" + } + ] + }, + { + "name": "InputMediaVenue", + "doc": "Represents a venue to be sent.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of the result, must be venue" + }, + { + "name": "Latitude", + "json_name": "latitude", + "type": { + "kind": "primitive", + "name": "float64" + }, + "required": true, + "doc": "Latitude of the location" + }, + { + "name": "Longitude", + "json_name": "longitude", + "type": { + "kind": "primitive", + "name": "float64" + }, + "required": true, + "doc": "Longitude of the location" + }, + { + "name": "Title", + "json_name": "title", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Name of the venue" + }, + { + "name": "Address", + "json_name": "address", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Address of the venue" + }, + { + "name": "FoursquareID", + "json_name": "foursquare_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Foursquare identifier of the venue" + }, + { + "name": "FoursquareType", + "json_name": "foursquare_type", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Foursquare type of the venue, if known. (For example, “arts_entertainment/default”, “arts_entertainment/aquarium” or “food/icecream”.)" + }, + { + "name": "GooglePlaceID", + "json_name": "google_place_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Google Places identifier of the venue" + }, + { + "name": "GooglePlaceType", + "json_name": "google_place_type", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Google Places type of the venue. (See supported types.)" + } + ] + }, + { + "name": "InputMediaVideo", + "doc": "Represents a video to be sent.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of the result, must be video" + }, + { + "name": "Media", + "json_name": "media", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "File to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet, or pass “attach://” to upload a new one using multipart/form-data under name. More information on Sending Files »" + }, + { + "name": "Thumbnail", + "json_name": "thumbnail", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://” if the thumbnail was uploaded using multipart/form-data under . More information on Sending Files »" + }, + { + "name": "Cover", + "json_name": "cover", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Cover for the video in the message. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet, or pass “attach://” to upload a new one using multipart/form-data under name. More information on Sending Files »" + }, + { + "name": "StartTimestamp", + "json_name": "start_timestamp", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. Start timestamp for the video in the message" + }, + { + "name": "Caption", + "json_name": "caption", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Caption of the video to be sent, 0-1024 characters after entities parsing" + }, + { + "name": "ParseMode", + "json_name": "parse_mode", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Mode for parsing entities in the video caption. See formatting options for more details." + }, + { + "name": "CaptionEntities", + "json_name": "caption_entities", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "MessageEntity" + } + }, + "doc": "Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode" + }, + { + "name": "ShowCaptionAboveMedia", + "json_name": "show_caption_above_media", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. Pass True, if the caption must be shown above the message media" + }, + { + "name": "Width", + "json_name": "width", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. Video width" + }, + { + "name": "Height", + "json_name": "height", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. Video height" + }, + { + "name": "Duration", + "json_name": "duration", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. Video duration in seconds" + }, + { + "name": "SupportsStreaming", + "json_name": "supports_streaming", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. Pass True if the uploaded video is suitable for streaming" + }, + { + "name": "HasSpoiler", + "json_name": "has_spoiler", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. Pass True if the video needs to be covered with a spoiler animation" + } + ] + }, + { + "name": "InputFile", + "doc": "This object represents the contents of a file to be uploaded. Must be posted using multipart/form-data in the usual way that files are uploaded via the browser." + }, + { + "name": "InputPaidMedia", + "doc": "This object describes the paid media to be sent. Currently, it can be one of", + "one_of": [ + "InputPaidMediaLivePhoto", + "InputPaidMediaPhoto", + "InputPaidMediaVideo" + ] + }, + { + "name": "InputPaidMediaLivePhoto", + "doc": "The paid media to send is a live photo.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of the media, must be live_photo" + }, + { + "name": "Media", + "json_name": "media", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Video of the live photo to send. Pass a file_id to send a file that exists on the Telegram servers (recommended) or pass “attach://” to upload a new one using multipart/form-data under name. More information on Sending Files ». Sending live photos by a URL is currently unsupported." + }, + { + "name": "Photo", + "json_name": "photo", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "The static photo to send. Pass a file_id to send a file that exists on the Telegram servers (recommended) or pass “attach://” to upload a new one using multipart/form-data under name. More information on Sending Files ». Sending live photos by a URL is currently unsupported." + } + ] + }, + { + "name": "InputPaidMediaPhoto", + "doc": "The paid media to send is a photo.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of the media, must be photo" + }, + { + "name": "Media", + "json_name": "media", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "File to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet, or pass “attach://” to upload a new one using multipart/form-data under name. More information on Sending Files »" + } + ] + }, + { + "name": "InputPaidMediaVideo", + "doc": "The paid media to send is a video.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of the media, must be video" + }, + { + "name": "Media", + "json_name": "media", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "File to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet, or pass “attach://” to upload a new one using multipart/form-data under name. More information on Sending Files »" + }, + { + "name": "Thumbnail", + "json_name": "thumbnail", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://” if the thumbnail was uploaded using multipart/form-data under . More information on Sending Files »" + }, + { + "name": "Cover", + "json_name": "cover", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Cover for the video in the message. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet, or pass “attach://” to upload a new one using multipart/form-data under name. More information on Sending Files »" + }, + { + "name": "StartTimestamp", + "json_name": "start_timestamp", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. Start timestamp for the video in the message" + }, + { + "name": "Width", + "json_name": "width", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. Video width" + }, + { + "name": "Height", + "json_name": "height", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. Video height" + }, + { + "name": "Duration", + "json_name": "duration", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. Video duration in seconds" + }, + { + "name": "SupportsStreaming", + "json_name": "supports_streaming", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. Pass True if the uploaded video is suitable for streaming" + } + ] + }, + { + "name": "InputProfilePhoto", + "doc": "This object describes a profile photo to set. Currently, it can be one of", + "one_of": [ + "InputProfilePhotoStatic", + "InputProfilePhotoAnimated" + ] + }, + { + "name": "InputProfilePhotoStatic", + "doc": "A static profile photo in the .JPG format.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of the profile photo, must be static" + }, + { + "name": "Photo", + "json_name": "photo", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "The static profile photo. Profile photos can't be reused and can only be uploaded as a new file, so you can pass “attach://” if the photo was uploaded using multipart/form-data under . More information on Sending Files »" + } + ] + }, + { + "name": "InputProfilePhotoAnimated", + "doc": "An animated profile photo in the MPEG4 format.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of the profile photo, must be animated" + }, + { + "name": "Animation", + "json_name": "animation", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "The animated profile photo. Profile photos can't be reused and can only be uploaded as a new file, so you can pass “attach://” if the photo was uploaded using multipart/form-data under . More information on Sending Files »" + }, + { + "name": "MainFrameTimestamp", + "json_name": "main_frame_timestamp", + "type": { + "kind": "primitive", + "name": "float64" + }, + "doc": "Optional. Timestamp in seconds of the frame that will be used as the static profile photo. Defaults to 0.0." + } + ] + }, + { + "name": "InputStoryContent", + "doc": "This object describes the content of a story to post. Currently, it can be one of", + "one_of": [ + "InputStoryContentPhoto", + "InputStoryContentVideo" + ] + }, + { + "name": "InputStoryContentPhoto", + "doc": "Describes a photo to post as a story.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of the content, must be photo" + }, + { + "name": "Photo", + "json_name": "photo", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "The photo to post as a story. The photo must be of the size 1080x1920 and must not exceed 10 MB. The photo can't be reused and can only be uploaded as a new file, so you can pass “attach://” if the photo was uploaded using multipart/form-data under . More information on Sending Files »" + } + ] + }, + { + "name": "InputStoryContentVideo", + "doc": "Describes a video to post as a story.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of the content, must be video" + }, + { + "name": "Video", + "json_name": "video", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "The video to post as a story. The video must be of the size 720x1280, streamable, encoded with H.265 codec, with key frames added each second in the MPEG4 format, and must not exceed 30 MB. The video can't be reused and can only be uploaded as a new file, so you can pass “attach://” if the video was uploaded using multipart/form-data under . More information on Sending Files »" + }, + { + "name": "Duration", + "json_name": "duration", + "type": { + "kind": "primitive", + "name": "float64" + }, + "doc": "Optional. Precise duration of the video in seconds; 0-60" + }, + { + "name": "CoverFrameTimestamp", + "json_name": "cover_frame_timestamp", + "type": { + "kind": "primitive", + "name": "float64" + }, + "doc": "Optional. Timestamp in seconds of the frame that will be used as the static cover for the story. Defaults to 0.0." + }, + { + "name": "IsAnimation", + "json_name": "is_animation", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. Pass True if the video has no sound" + } + ] + }, + { + "name": "Sticker", + "doc": "This object represents a sticker.", + "fields": [ + { + "name": "FileID", + "json_name": "file_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Identifier for this file, which can be used to download or reuse the file" + }, + { + "name": "FileUniqueID", + "json_name": "file_unique_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file." + }, + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of the sticker, currently one of “regular”, “mask”, “custom_emoji”. The type of the sticker is independent from its format, which is determined by the fields is_animated and is_video." + }, + { + "name": "Width", + "json_name": "width", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Sticker width" + }, + { + "name": "Height", + "json_name": "height", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Sticker height" + }, + { + "name": "IsAnimated", + "json_name": "is_animated", + "type": { + "kind": "primitive", + "name": "bool" + }, + "required": true, + "doc": "True, if the sticker is animated" + }, + { + "name": "IsVideo", + "json_name": "is_video", + "type": { + "kind": "primitive", + "name": "bool" + }, + "required": true, + "doc": "True, if the sticker is a video sticker" + }, + { + "name": "Thumbnail", + "json_name": "thumbnail", + "type": { + "kind": "named", + "name": "PhotoSize" + }, + "doc": "Optional. Sticker thumbnail in the .WEBP or .JPG format" + }, + { + "name": "Emoji", + "json_name": "emoji", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Emoji associated with the sticker" + }, + { + "name": "SetName", + "json_name": "set_name", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Name of the sticker set to which the sticker belongs" + }, + { + "name": "PremiumAnimation", + "json_name": "premium_animation", + "type": { + "kind": "named", + "name": "File" + }, + "doc": "Optional. For premium regular stickers, premium animation for the sticker" + }, + { + "name": "MaskPosition", + "json_name": "mask_position", + "type": { + "kind": "named", + "name": "MaskPosition" + }, + "doc": "Optional. For mask stickers, the position where the mask should be placed" + }, + { + "name": "CustomEmojiID", + "json_name": "custom_emoji_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. For custom emoji stickers, unique identifier of the custom emoji" + }, + { + "name": "NeedsRepainting", + "json_name": "needs_repainting", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the sticker must be repainted to a text color in messages, the color of the Telegram Premium badge in emoji status, white color on chat photos, or another appropriate color in other places" + }, + { + "name": "FileSize", + "json_name": "file_size", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. File size in bytes" + } + ] + }, + { + "name": "StickerSet", + "doc": "This object represents a sticker set.", + "fields": [ + { + "name": "Name", + "json_name": "name", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Sticker set name" + }, + { + "name": "Title", + "json_name": "title", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Sticker set title" + }, + { + "name": "StickerType", + "json_name": "sticker_type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of stickers in the set, currently one of “regular”, “mask”, “custom_emoji”" + }, + { + "name": "Stickers", + "json_name": "stickers", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "Sticker" + } + }, + "required": true, + "doc": "List of all set stickers" + }, + { + "name": "Thumbnail", + "json_name": "thumbnail", + "type": { + "kind": "named", + "name": "PhotoSize" + }, + "doc": "Optional. Sticker set thumbnail in the .WEBP, .TGS, or .WEBM format" + } + ] + }, + { + "name": "MaskPosition", + "doc": "This object describes the position on faces where a mask should be placed by default.", + "fields": [ + { + "name": "Point", + "json_name": "point", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "The part of the face relative to which the mask should be placed. One of “forehead”, “eyes”, “mouth”, or “chin”." + }, + { + "name": "XShift", + "json_name": "x_shift", + "type": { + "kind": "primitive", + "name": "float64" + }, + "required": true, + "doc": "Shift by X-axis measured in widths of the mask scaled to the face size, from left to right. For example, choosing -1.0 will place mask just to the left of the default mask position." + }, + { + "name": "YShift", + "json_name": "y_shift", + "type": { + "kind": "primitive", + "name": "float64" + }, + "required": true, + "doc": "Shift by Y-axis measured in heights of the mask scaled to the face size, from top to bottom. For example, 1.0 will place the mask just below the default mask position." + }, + { + "name": "Scale", + "json_name": "scale", + "type": { + "kind": "primitive", + "name": "float64" + }, + "required": true, + "doc": "Mask scaling coefficient. For example, 2.0 means double size." + } + ] + }, + { + "name": "InputSticker", + "doc": "This object describes a sticker to be added to a sticker set.", + "fields": [ + { + "name": "Sticker", + "json_name": "sticker", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "The added sticker. Pass a file_id as a String to send a file that already exists on the Telegram servers, pass an HTTP URL as a String for Telegram to get a file from the Internet, or pass “attach://” to upload a new file using multipart/form-data under name. Animated and video stickers can't be uploaded via HTTP URL. More information on Sending Files »" + }, + { + "name": "Format", + "json_name": "format", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Format of the added sticker, must be one of “static” for a .WEBP or .PNG image, “animated” for a .TGS animation, “video” for a .WEBM video" + }, + { + "name": "EmojiList", + "json_name": "emoji_list", + "type": { + "kind": "array", + "elem_type": { + "kind": "primitive", + "name": "string" + } + }, + "required": true, + "doc": "List of 1-20 emoji associated with the sticker" + }, + { + "name": "MaskPosition", + "json_name": "mask_position", + "type": { + "kind": "named", + "name": "MaskPosition" + }, + "doc": "Optional. Position where the mask should be placed on faces. For “mask” stickers only." + }, + { + "name": "Keywords", + "json_name": "keywords", + "type": { + "kind": "array", + "elem_type": { + "kind": "primitive", + "name": "string" + } + }, + "doc": "Optional. List of 0-20 search keywords for the sticker with total length of up to 64 characters. For “regular” and “custom_emoji” stickers only." + } + ] + }, + { + "name": "InlineQuery", + "doc": "This object represents an incoming inline query. When the user sends an empty query, your bot could return some default or trending results.", + "fields": [ + { + "name": "ID", + "json_name": "id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique identifier for this query" + }, + { + "name": "From", + "json_name": "from", + "type": { + "kind": "named", + "name": "User" + }, + "required": true, + "doc": "Sender" + }, + { + "name": "Query", + "json_name": "query", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Text of the query (up to 256 characters)" + }, + { + "name": "Offset", + "json_name": "offset", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Offset of the results to be returned, can be controlled by the bot" + }, + { + "name": "ChatType", + "json_name": "chat_type", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Type of the chat from which the inline query was sent. Can be either “sender” for a private chat with the inline query sender, “private”, “group”, “supergroup”, or “channel”. The chat type should be always known for requests sent from official clients and most third-party clients, unless the request was sent from a secret chat" + }, + { + "name": "Location", + "json_name": "location", + "type": { + "kind": "named", + "name": "Location" + }, + "doc": "Optional. Sender location, only for bots that request user location" + } + ] + }, + { + "name": "InlineQueryResultsButton", + "doc": "This object represents a button to be shown above inline query results. You must use exactly one of the optional fields.", + "fields": [ + { + "name": "Text", + "json_name": "text", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Label text on the button" + }, + { + "name": "WebApp", + "json_name": "web_app", + "type": { + "kind": "named", + "name": "WebAppInfo" + }, + "doc": "Optional. Description of the Web App that will be launched when the user presses the button. The Web App will be able to switch back to the inline mode using the method switchInlineQuery inside the Web App." + }, + { + "name": "StartParameter", + "json_name": "start_parameter", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Deep-linking parameter for the /start message sent to the bot when a user presses the button. 1-64 characters, only A-Z, a-z, 0-9, _ and - are allowed.Example: An inline bot that sends YouTube videos can ask the user to connect the bot to their YouTube account to adapt search results accordingly. To do this, it displays a 'Connect your YouTube account' button above the results, or even before showing any. The user presses the button, switches to a private chat with the bot and, in doing so, passes a start parameter that instructs the bot to return an OAuth link. Once done, the bot can offer a switch_inline button so that the user can easily return to the chat where they wanted to use the bot's inline capabilities." + } + ] + }, + { + "name": "InlineQueryResult", + "doc": "This object represents one result of an inline query. Telegram clients currently support results of the following 20 types:\nNote: All URLs passed in inline query results will be available to end users and therefore must be assumed to be public.", + "one_of": [ + "InlineQueryResultCachedAudio", + "InlineQueryResultCachedDocument", + "InlineQueryResultCachedGif", + "InlineQueryResultCachedMpeg4Gif", + "InlineQueryResultCachedPhoto", + "InlineQueryResultCachedSticker", + "InlineQueryResultCachedVideo", + "InlineQueryResultCachedVoice", + "InlineQueryResultArticle", + "InlineQueryResultAudio", + "InlineQueryResultContact", + "InlineQueryResultGame", + "InlineQueryResultDocument", + "InlineQueryResultGif", + "InlineQueryResultLocation", + "InlineQueryResultMpeg4Gif", + "InlineQueryResultPhoto", + "InlineQueryResultVenue", + "InlineQueryResultVideo", + "InlineQueryResultVoice" + ] + }, + { + "name": "InlineQueryResultArticle", + "doc": "Represents a link to an article or web page.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of the result, must be article" + }, + { + "name": "ID", + "json_name": "id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique identifier for this result, 1-64 Bytes" + }, + { + "name": "Title", + "json_name": "title", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Title of the result" + }, + { + "name": "InputMessageContent", + "json_name": "input_message_content", + "type": { + "kind": "named", + "name": "InputMessageContent" + }, + "required": true, + "doc": "Content of the message to be sent" + }, + { + "name": "ReplyMarkup", + "json_name": "reply_markup", + "type": { + "kind": "named", + "name": "InlineKeyboardMarkup" + }, + "doc": "Optional. Inline keyboard attached to the message" + }, + { + "name": "URL", + "json_name": "url", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. URL of the result" + }, + { + "name": "Description", + "json_name": "description", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Short description of the result" + }, + { + "name": "ThumbnailURL", + "json_name": "thumbnail_url", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Url of the thumbnail for the result" + }, + { + "name": "ThumbnailWidth", + "json_name": "thumbnail_width", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. Thumbnail width" + }, + { + "name": "ThumbnailHeight", + "json_name": "thumbnail_height", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. Thumbnail height" + } + ] + }, + { + "name": "InlineQueryResultPhoto", + "doc": "Represents a link to a photo. By default, this photo will be sent by the user with optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the photo.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of the result, must be photo" + }, + { + "name": "ID", + "json_name": "id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique identifier for this result, 1-64 bytes" + }, + { + "name": "PhotoURL", + "json_name": "photo_url", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "A valid URL of the photo. Photo must be in JPEG format. Photo size must not exceed 5MB" + }, + { + "name": "ThumbnailURL", + "json_name": "thumbnail_url", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "URL of the thumbnail for the photo" + }, + { + "name": "PhotoWidth", + "json_name": "photo_width", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. Width of the photo" + }, + { + "name": "PhotoHeight", + "json_name": "photo_height", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. Height of the photo" + }, + { + "name": "Title", + "json_name": "title", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Title for the result" + }, + { + "name": "Description", + "json_name": "description", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Short description of the result" + }, + { + "name": "Caption", + "json_name": "caption", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Caption of the photo to be sent, 0-1024 characters after entities parsing" + }, + { + "name": "ParseMode", + "json_name": "parse_mode", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Mode for parsing entities in the photo caption. See formatting options for more details." + }, + { + "name": "CaptionEntities", + "json_name": "caption_entities", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "MessageEntity" + } + }, + "doc": "Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode" + }, + { + "name": "ShowCaptionAboveMedia", + "json_name": "show_caption_above_media", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. Pass True, if the caption must be shown above the message media" + }, + { + "name": "ReplyMarkup", + "json_name": "reply_markup", + "type": { + "kind": "named", + "name": "InlineKeyboardMarkup" + }, + "doc": "Optional. Inline keyboard attached to the message" + }, + { + "name": "InputMessageContent", + "json_name": "input_message_content", + "type": { + "kind": "named", + "name": "InputMessageContent" + }, + "doc": "Optional. Content of the message to be sent instead of the photo" + } + ] + }, + { + "name": "InlineQueryResultGif", + "doc": "Represents a link to an animated GIF file. By default, this animated GIF file will be sent by the user with optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the animation.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of the result, must be gif" + }, + { + "name": "ID", + "json_name": "id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique identifier for this result, 1-64 bytes" + }, + { + "name": "GifURL", + "json_name": "gif_url", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "A valid URL for the GIF file" + }, + { + "name": "GifWidth", + "json_name": "gif_width", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. Width of the GIF" + }, + { + "name": "GifHeight", + "json_name": "gif_height", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. Height of the GIF" + }, + { + "name": "GifDuration", + "json_name": "gif_duration", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. Duration of the GIF in seconds" + }, + { + "name": "ThumbnailURL", + "json_name": "thumbnail_url", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "URL of the static (JPEG or GIF) or animated (MPEG4) thumbnail for the result" + }, + { + "name": "ThumbnailMimeType", + "json_name": "thumbnail_mime_type", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. MIME type of the thumbnail, must be one of “image/jpeg”, “image/gif”, or “video/mp4”. Defaults to “image/jpeg”" + }, + { + "name": "Title", + "json_name": "title", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Title for the result" + }, + { + "name": "Caption", + "json_name": "caption", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Caption of the GIF file to be sent, 0-1024 characters after entities parsing" + }, + { + "name": "ParseMode", + "json_name": "parse_mode", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Mode for parsing entities in the caption. See formatting options for more details." + }, + { + "name": "CaptionEntities", + "json_name": "caption_entities", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "MessageEntity" + } + }, + "doc": "Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode" + }, + { + "name": "ShowCaptionAboveMedia", + "json_name": "show_caption_above_media", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. Pass True, if the caption must be shown above the message media" + }, + { + "name": "ReplyMarkup", + "json_name": "reply_markup", + "type": { + "kind": "named", + "name": "InlineKeyboardMarkup" + }, + "doc": "Optional. Inline keyboard attached to the message" + }, + { + "name": "InputMessageContent", + "json_name": "input_message_content", + "type": { + "kind": "named", + "name": "InputMessageContent" + }, + "doc": "Optional. Content of the message to be sent instead of the GIF animation" + } + ] + }, + { + "name": "InlineQueryResultMpeg4Gif", + "doc": "Represents a link to a video animation (H.264/MPEG-4 AVC video without sound). By default, this animated MPEG-4 file will be sent by the user with optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the animation.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of the result, must be mpeg4_gif" + }, + { + "name": "ID", + "json_name": "id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique identifier for this result, 1-64 bytes" + }, + { + "name": "Mpeg4URL", + "json_name": "mpeg4_url", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "A valid URL for the MPEG4 file" + }, + { + "name": "Mpeg4Width", + "json_name": "mpeg4_width", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. Video width" + }, + { + "name": "Mpeg4Height", + "json_name": "mpeg4_height", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. Video height" + }, + { + "name": "Mpeg4Duration", + "json_name": "mpeg4_duration", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. Video duration in seconds" + }, + { + "name": "ThumbnailURL", + "json_name": "thumbnail_url", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "URL of the static (JPEG or GIF) or animated (MPEG4) thumbnail for the result" + }, + { + "name": "ThumbnailMimeType", + "json_name": "thumbnail_mime_type", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. MIME type of the thumbnail, must be one of “image/jpeg”, “image/gif”, or “video/mp4”. Defaults to “image/jpeg”" + }, + { + "name": "Title", + "json_name": "title", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Title for the result" + }, + { + "name": "Caption", + "json_name": "caption", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Caption of the MPEG-4 file to be sent, 0-1024 characters after entities parsing" + }, + { + "name": "ParseMode", + "json_name": "parse_mode", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Mode for parsing entities in the caption. See formatting options for more details." + }, + { + "name": "CaptionEntities", + "json_name": "caption_entities", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "MessageEntity" + } + }, + "doc": "Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode" + }, + { + "name": "ShowCaptionAboveMedia", + "json_name": "show_caption_above_media", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. Pass True, if the caption must be shown above the message media" + }, + { + "name": "ReplyMarkup", + "json_name": "reply_markup", + "type": { + "kind": "named", + "name": "InlineKeyboardMarkup" + }, + "doc": "Optional. Inline keyboard attached to the message" + }, + { + "name": "InputMessageContent", + "json_name": "input_message_content", + "type": { + "kind": "named", + "name": "InputMessageContent" + }, + "doc": "Optional. Content of the message to be sent instead of the video animation" + } + ] + }, + { + "name": "InlineQueryResultVideo", + "doc": "Represents a link to a page containing an embedded video player or a video file. By default, this video file will be sent by the user with an optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the video.\nIf an InlineQueryResultVideo message contains an embedded video (e.g., YouTube), you must replace its content using input_message_content.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of the result, must be video" + }, + { + "name": "ID", + "json_name": "id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique identifier for this result, 1-64 bytes" + }, + { + "name": "VideoURL", + "json_name": "video_url", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "A valid URL for the embedded video player or video file" + }, + { + "name": "MimeType", + "json_name": "mime_type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "MIME type of the content of the video URL, “text/html” or “video/mp4”" + }, + { + "name": "ThumbnailURL", + "json_name": "thumbnail_url", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "URL of the thumbnail (JPEG only) for the video" + }, + { + "name": "Title", + "json_name": "title", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Title for the result" + }, + { + "name": "Caption", + "json_name": "caption", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Caption of the video to be sent, 0-1024 characters after entities parsing" + }, + { + "name": "ParseMode", + "json_name": "parse_mode", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Mode for parsing entities in the video caption. See formatting options for more details." + }, + { + "name": "CaptionEntities", + "json_name": "caption_entities", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "MessageEntity" + } + }, + "doc": "Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode" + }, + { + "name": "ShowCaptionAboveMedia", + "json_name": "show_caption_above_media", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. Pass True, if the caption must be shown above the message media" + }, + { + "name": "VideoWidth", + "json_name": "video_width", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. Video width" + }, + { + "name": "VideoHeight", + "json_name": "video_height", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. Video height" + }, + { + "name": "VideoDuration", + "json_name": "video_duration", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. Video duration in seconds" + }, + { + "name": "Description", + "json_name": "description", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Short description of the result" + }, + { + "name": "ReplyMarkup", + "json_name": "reply_markup", + "type": { + "kind": "named", + "name": "InlineKeyboardMarkup" + }, + "doc": "Optional. Inline keyboard attached to the message" + }, + { + "name": "InputMessageContent", + "json_name": "input_message_content", + "type": { + "kind": "named", + "name": "InputMessageContent" + }, + "doc": "Optional. Content of the message to be sent instead of the video. This field is required if InlineQueryResultVideo is used to send an HTML-page as a result (e.g., a YouTube video)." + } + ] + }, + { + "name": "InlineQueryResultAudio", + "doc": "Represents a link to an MP3 audio file. By default, this audio file will be sent by the user. Alternatively, you can use input_message_content to send a message with the specified content instead of the audio.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of the result, must be audio" + }, + { + "name": "ID", + "json_name": "id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique identifier for this result, 1-64 bytes" + }, + { + "name": "AudioURL", + "json_name": "audio_url", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "A valid URL for the audio file" + }, + { + "name": "Title", + "json_name": "title", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Title" + }, + { + "name": "Caption", + "json_name": "caption", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Caption, 0-1024 characters after entities parsing" + }, + { + "name": "ParseMode", + "json_name": "parse_mode", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Mode for parsing entities in the audio caption. See formatting options for more details." + }, + { + "name": "CaptionEntities", + "json_name": "caption_entities", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "MessageEntity" + } + }, + "doc": "Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode" + }, + { + "name": "Performer", + "json_name": "performer", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Performer" + }, + { + "name": "AudioDuration", + "json_name": "audio_duration", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. Audio duration in seconds" + }, + { + "name": "ReplyMarkup", + "json_name": "reply_markup", + "type": { + "kind": "named", + "name": "InlineKeyboardMarkup" + }, + "doc": "Optional. Inline keyboard attached to the message" + }, + { + "name": "InputMessageContent", + "json_name": "input_message_content", + "type": { + "kind": "named", + "name": "InputMessageContent" + }, + "doc": "Optional. Content of the message to be sent instead of the audio" + } + ] + }, + { + "name": "InlineQueryResultVoice", + "doc": "Represents a link to a voice recording in an .OGG container encoded with OPUS. By default, this voice recording will be sent by the user. Alternatively, you can use input_message_content to send a message with the specified content instead of the the voice message.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of the result, must be voice" + }, + { + "name": "ID", + "json_name": "id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique identifier for this result, 1-64 bytes" + }, + { + "name": "VoiceURL", + "json_name": "voice_url", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "A valid URL for the voice recording" + }, + { + "name": "Title", + "json_name": "title", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Recording title" + }, + { + "name": "Caption", + "json_name": "caption", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Caption, 0-1024 characters after entities parsing" + }, + { + "name": "ParseMode", + "json_name": "parse_mode", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Mode for parsing entities in the voice message caption. See formatting options for more details." + }, + { + "name": "CaptionEntities", + "json_name": "caption_entities", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "MessageEntity" + } + }, + "doc": "Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode" + }, + { + "name": "VoiceDuration", + "json_name": "voice_duration", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. Recording duration in seconds" + }, + { + "name": "ReplyMarkup", + "json_name": "reply_markup", + "type": { + "kind": "named", + "name": "InlineKeyboardMarkup" + }, + "doc": "Optional. Inline keyboard attached to the message" + }, + { + "name": "InputMessageContent", + "json_name": "input_message_content", + "type": { + "kind": "named", + "name": "InputMessageContent" + }, + "doc": "Optional. Content of the message to be sent instead of the voice recording" + } + ] + }, + { + "name": "InlineQueryResultDocument", + "doc": "Represents a link to a file. By default, this file will be sent by the user with an optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the file. Currently, only .PDF and .ZIP files can be sent using this method.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of the result, must be document" + }, + { + "name": "ID", + "json_name": "id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique identifier for this result, 1-64 bytes" + }, + { + "name": "Title", + "json_name": "title", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Title for the result" + }, + { + "name": "Caption", + "json_name": "caption", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Caption of the document to be sent, 0-1024 characters after entities parsing" + }, + { + "name": "ParseMode", + "json_name": "parse_mode", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Mode for parsing entities in the document caption. See formatting options for more details." + }, + { + "name": "CaptionEntities", + "json_name": "caption_entities", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "MessageEntity" + } + }, + "doc": "Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode" + }, + { + "name": "DocumentURL", + "json_name": "document_url", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "A valid URL for the file" + }, + { + "name": "MimeType", + "json_name": "mime_type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "MIME type of the content of the file, either “application/pdf” or “application/zip”" + }, + { + "name": "Description", + "json_name": "description", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Short description of the result" + }, + { + "name": "ReplyMarkup", + "json_name": "reply_markup", + "type": { + "kind": "named", + "name": "InlineKeyboardMarkup" + }, + "doc": "Optional. Inline keyboard attached to the message" + }, + { + "name": "InputMessageContent", + "json_name": "input_message_content", + "type": { + "kind": "named", + "name": "InputMessageContent" + }, + "doc": "Optional. Content of the message to be sent instead of the file" + }, + { + "name": "ThumbnailURL", + "json_name": "thumbnail_url", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. URL of the thumbnail (JPEG only) for the file" + }, + { + "name": "ThumbnailWidth", + "json_name": "thumbnail_width", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. Thumbnail width" + }, + { + "name": "ThumbnailHeight", + "json_name": "thumbnail_height", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. Thumbnail height" + } + ] + }, + { + "name": "InlineQueryResultLocation", + "doc": "Represents a location on a map. By default, the location will be sent by the user. Alternatively, you can use input_message_content to send a message with the specified content instead of the location.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of the result, must be location" + }, + { + "name": "ID", + "json_name": "id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique identifier for this result, 1-64 Bytes" + }, + { + "name": "Latitude", + "json_name": "latitude", + "type": { + "kind": "primitive", + "name": "float64" + }, + "required": true, + "doc": "Location latitude in degrees" + }, + { + "name": "Longitude", + "json_name": "longitude", + "type": { + "kind": "primitive", + "name": "float64" + }, + "required": true, + "doc": "Location longitude in degrees" + }, + { + "name": "Title", + "json_name": "title", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Location title" + }, + { + "name": "HorizontalAccuracy", + "json_name": "horizontal_accuracy", + "type": { + "kind": "primitive", + "name": "float64" + }, + "doc": "Optional. The radius of uncertainty for the location, measured in meters; 0-1500" + }, + { + "name": "LivePeriod", + "json_name": "live_period", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. Period in seconds during which the location can be updated, should be between 60 and 86400, or 0x7FFFFFFF for live locations that can be edited indefinitely." + }, + { + "name": "Heading", + "json_name": "heading", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. For live locations, a direction in which the user is moving, in degrees. Must be between 1 and 360 if specified." + }, + { + "name": "ProximityAlertRadius", + "json_name": "proximity_alert_radius", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. For live locations, a maximum distance for proximity alerts about approaching another chat member, in meters. Must be between 1 and 100000 if specified." + }, + { + "name": "ReplyMarkup", + "json_name": "reply_markup", + "type": { + "kind": "named", + "name": "InlineKeyboardMarkup" + }, + "doc": "Optional. Inline keyboard attached to the message" + }, + { + "name": "InputMessageContent", + "json_name": "input_message_content", + "type": { + "kind": "named", + "name": "InputMessageContent" + }, + "doc": "Optional. Content of the message to be sent instead of the location" + }, + { + "name": "ThumbnailURL", + "json_name": "thumbnail_url", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Url of the thumbnail for the result" + }, + { + "name": "ThumbnailWidth", + "json_name": "thumbnail_width", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. Thumbnail width" + }, + { + "name": "ThumbnailHeight", + "json_name": "thumbnail_height", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. Thumbnail height" + } + ] + }, + { + "name": "InlineQueryResultVenue", + "doc": "Represents a venue. By default, the venue will be sent by the user. Alternatively, you can use input_message_content to send a message with the specified content instead of the venue.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of the result, must be venue" + }, + { + "name": "ID", + "json_name": "id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique identifier for this result, 1-64 Bytes" + }, + { + "name": "Latitude", + "json_name": "latitude", + "type": { + "kind": "primitive", + "name": "float64" + }, + "required": true, + "doc": "Latitude of the venue location in degrees" + }, + { + "name": "Longitude", + "json_name": "longitude", + "type": { + "kind": "primitive", + "name": "float64" + }, + "required": true, + "doc": "Longitude of the venue location in degrees" + }, + { + "name": "Title", + "json_name": "title", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Title of the venue" + }, + { + "name": "Address", + "json_name": "address", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Address of the venue" + }, + { + "name": "FoursquareID", + "json_name": "foursquare_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Foursquare identifier of the venue if known" + }, + { + "name": "FoursquareType", + "json_name": "foursquare_type", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Foursquare type of the venue, if known. (For example, “arts_entertainment/default”, “arts_entertainment/aquarium” or “food/icecream”.)" + }, + { + "name": "GooglePlaceID", + "json_name": "google_place_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Google Places identifier of the venue" + }, + { + "name": "GooglePlaceType", + "json_name": "google_place_type", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Google Places type of the venue. (See supported types.)" + }, + { + "name": "ReplyMarkup", + "json_name": "reply_markup", + "type": { + "kind": "named", + "name": "InlineKeyboardMarkup" + }, + "doc": "Optional. Inline keyboard attached to the message" + }, + { + "name": "InputMessageContent", + "json_name": "input_message_content", + "type": { + "kind": "named", + "name": "InputMessageContent" + }, + "doc": "Optional. Content of the message to be sent instead of the venue" + }, + { + "name": "ThumbnailURL", + "json_name": "thumbnail_url", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Url of the thumbnail for the result" + }, + { + "name": "ThumbnailWidth", + "json_name": "thumbnail_width", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. Thumbnail width" + }, + { + "name": "ThumbnailHeight", + "json_name": "thumbnail_height", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. Thumbnail height" + } + ] + }, + { + "name": "InlineQueryResultContact", + "doc": "Represents a contact with a phone number. By default, this contact will be sent by the user. Alternatively, you can use input_message_content to send a message with the specified content instead of the contact.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of the result, must be contact" + }, + { + "name": "ID", + "json_name": "id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique identifier for this result, 1-64 Bytes" + }, + { + "name": "PhoneNumber", + "json_name": "phone_number", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Contact's phone number" + }, + { + "name": "FirstName", + "json_name": "first_name", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Contact's first name" + }, + { + "name": "LastName", + "json_name": "last_name", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Contact's last name" + }, + { + "name": "Vcard", + "json_name": "vcard", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Additional data about the contact in the form of a vCard, 0-2048 bytes" + }, + { + "name": "ReplyMarkup", + "json_name": "reply_markup", + "type": { + "kind": "named", + "name": "InlineKeyboardMarkup" + }, + "doc": "Optional. Inline keyboard attached to the message" + }, + { + "name": "InputMessageContent", + "json_name": "input_message_content", + "type": { + "kind": "named", + "name": "InputMessageContent" + }, + "doc": "Optional. Content of the message to be sent instead of the contact" + }, + { + "name": "ThumbnailURL", + "json_name": "thumbnail_url", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Url of the thumbnail for the result" + }, + { + "name": "ThumbnailWidth", + "json_name": "thumbnail_width", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. Thumbnail width" + }, + { + "name": "ThumbnailHeight", + "json_name": "thumbnail_height", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. Thumbnail height" + } + ] + }, + { + "name": "InlineQueryResultGame", + "doc": "Represents a Game.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of the result, must be game" + }, + { + "name": "ID", + "json_name": "id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique identifier for this result, 1-64 bytes" + }, + { + "name": "GameShortName", + "json_name": "game_short_name", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Short name of the game" + }, + { + "name": "ReplyMarkup", + "json_name": "reply_markup", + "type": { + "kind": "named", + "name": "InlineKeyboardMarkup" + }, + "doc": "Optional. Inline keyboard attached to the message" + } + ] + }, + { + "name": "InlineQueryResultCachedPhoto", + "doc": "Represents a link to a photo stored on the Telegram servers. By default, this photo will be sent by the user with an optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the photo.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of the result, must be photo" + }, + { + "name": "ID", + "json_name": "id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique identifier for this result, 1-64 bytes" + }, + { + "name": "PhotoFileID", + "json_name": "photo_file_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "A valid file identifier of the photo" + }, + { + "name": "Title", + "json_name": "title", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Title for the result" + }, + { + "name": "Description", + "json_name": "description", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Short description of the result" + }, + { + "name": "Caption", + "json_name": "caption", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Caption of the photo to be sent, 0-1024 characters after entities parsing" + }, + { + "name": "ParseMode", + "json_name": "parse_mode", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Mode for parsing entities in the photo caption. See formatting options for more details." + }, + { + "name": "CaptionEntities", + "json_name": "caption_entities", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "MessageEntity" + } + }, + "doc": "Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode" + }, + { + "name": "ShowCaptionAboveMedia", + "json_name": "show_caption_above_media", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. Pass True, if the caption must be shown above the message media" + }, + { + "name": "ReplyMarkup", + "json_name": "reply_markup", + "type": { + "kind": "named", + "name": "InlineKeyboardMarkup" + }, + "doc": "Optional. Inline keyboard attached to the message" + }, + { + "name": "InputMessageContent", + "json_name": "input_message_content", + "type": { + "kind": "named", + "name": "InputMessageContent" + }, + "doc": "Optional. Content of the message to be sent instead of the photo" + } + ] + }, + { + "name": "InlineQueryResultCachedGif", + "doc": "Represents a link to an animated GIF file stored on the Telegram servers. By default, this animated GIF file will be sent by the user with an optional caption. Alternatively, you can use input_message_content to send a message with specified content instead of the animation.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of the result, must be gif" + }, + { + "name": "ID", + "json_name": "id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique identifier for this result, 1-64 bytes" + }, + { + "name": "GifFileID", + "json_name": "gif_file_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "A valid file identifier for the GIF file" + }, + { + "name": "Title", + "json_name": "title", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Title for the result" + }, + { + "name": "Caption", + "json_name": "caption", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Caption of the GIF file to be sent, 0-1024 characters after entities parsing" + }, + { + "name": "ParseMode", + "json_name": "parse_mode", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Mode for parsing entities in the caption. See formatting options for more details." + }, + { + "name": "CaptionEntities", + "json_name": "caption_entities", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "MessageEntity" + } + }, + "doc": "Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode" + }, + { + "name": "ShowCaptionAboveMedia", + "json_name": "show_caption_above_media", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. Pass True, if the caption must be shown above the message media" + }, + { + "name": "ReplyMarkup", + "json_name": "reply_markup", + "type": { + "kind": "named", + "name": "InlineKeyboardMarkup" + }, + "doc": "Optional. Inline keyboard attached to the message" + }, + { + "name": "InputMessageContent", + "json_name": "input_message_content", + "type": { + "kind": "named", + "name": "InputMessageContent" + }, + "doc": "Optional. Content of the message to be sent instead of the GIF animation" + } + ] + }, + { + "name": "InlineQueryResultCachedMpeg4Gif", + "doc": "Represents a link to a video animation (H.264/MPEG-4 AVC video without sound) stored on the Telegram servers. By default, this animated MPEG-4 file will be sent by the user with an optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the animation.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of the result, must be mpeg4_gif" + }, + { + "name": "ID", + "json_name": "id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique identifier for this result, 1-64 bytes" + }, + { + "name": "Mpeg4FileID", + "json_name": "mpeg4_file_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "A valid file identifier for the MPEG4 file" + }, + { + "name": "Title", + "json_name": "title", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Title for the result" + }, + { + "name": "Caption", + "json_name": "caption", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Caption of the MPEG-4 file to be sent, 0-1024 characters after entities parsing" + }, + { + "name": "ParseMode", + "json_name": "parse_mode", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Mode for parsing entities in the caption. See formatting options for more details." + }, + { + "name": "CaptionEntities", + "json_name": "caption_entities", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "MessageEntity" + } + }, + "doc": "Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode" + }, + { + "name": "ShowCaptionAboveMedia", + "json_name": "show_caption_above_media", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. Pass True, if the caption must be shown above the message media" + }, + { + "name": "ReplyMarkup", + "json_name": "reply_markup", + "type": { + "kind": "named", + "name": "InlineKeyboardMarkup" + }, + "doc": "Optional. Inline keyboard attached to the message" + }, + { + "name": "InputMessageContent", + "json_name": "input_message_content", + "type": { + "kind": "named", + "name": "InputMessageContent" + }, + "doc": "Optional. Content of the message to be sent instead of the video animation" + } + ] + }, + { + "name": "InlineQueryResultCachedSticker", + "doc": "Represents a link to a sticker stored on the Telegram servers. By default, this sticker will be sent by the user. Alternatively, you can use input_message_content to send a message with the specified content instead of the sticker.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of the result, must be sticker" + }, + { + "name": "ID", + "json_name": "id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique identifier for this result, 1-64 bytes" + }, + { + "name": "StickerFileID", + "json_name": "sticker_file_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "A valid file identifier of the sticker" + }, + { + "name": "ReplyMarkup", + "json_name": "reply_markup", + "type": { + "kind": "named", + "name": "InlineKeyboardMarkup" + }, + "doc": "Optional. Inline keyboard attached to the message" + }, + { + "name": "InputMessageContent", + "json_name": "input_message_content", + "type": { + "kind": "named", + "name": "InputMessageContent" + }, + "doc": "Optional. Content of the message to be sent instead of the sticker" + } + ] + }, + { + "name": "InlineQueryResultCachedDocument", + "doc": "Represents a link to a file stored on the Telegram servers. By default, this file will be sent by the user with an optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the file.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of the result, must be document" + }, + { + "name": "ID", + "json_name": "id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique identifier for this result, 1-64 bytes" + }, + { + "name": "Title", + "json_name": "title", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Title for the result" + }, + { + "name": "DocumentFileID", + "json_name": "document_file_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "A valid file identifier for the file" + }, + { + "name": "Description", + "json_name": "description", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Short description of the result" + }, + { + "name": "Caption", + "json_name": "caption", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Caption of the document to be sent, 0-1024 characters after entities parsing" + }, + { + "name": "ParseMode", + "json_name": "parse_mode", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Mode for parsing entities in the document caption. See formatting options for more details." + }, + { + "name": "CaptionEntities", + "json_name": "caption_entities", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "MessageEntity" + } + }, + "doc": "Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode" + }, + { + "name": "ReplyMarkup", + "json_name": "reply_markup", + "type": { + "kind": "named", + "name": "InlineKeyboardMarkup" + }, + "doc": "Optional. Inline keyboard attached to the message" + }, + { + "name": "InputMessageContent", + "json_name": "input_message_content", + "type": { + "kind": "named", + "name": "InputMessageContent" + }, + "doc": "Optional. Content of the message to be sent instead of the file" + } + ] + }, + { + "name": "InlineQueryResultCachedVideo", + "doc": "Represents a link to a video file stored on the Telegram servers. By default, this video file will be sent by the user with an optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the video.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of the result, must be video" + }, + { + "name": "ID", + "json_name": "id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique identifier for this result, 1-64 bytes" + }, + { + "name": "VideoFileID", + "json_name": "video_file_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "A valid file identifier for the video file" + }, + { + "name": "Title", + "json_name": "title", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Title for the result" + }, + { + "name": "Description", + "json_name": "description", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Short description of the result" + }, + { + "name": "Caption", + "json_name": "caption", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Caption of the video to be sent, 0-1024 characters after entities parsing" + }, + { + "name": "ParseMode", + "json_name": "parse_mode", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Mode for parsing entities in the video caption. See formatting options for more details." + }, + { + "name": "CaptionEntities", + "json_name": "caption_entities", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "MessageEntity" + } + }, + "doc": "Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode" + }, + { + "name": "ShowCaptionAboveMedia", + "json_name": "show_caption_above_media", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. Pass True, if the caption must be shown above the message media" + }, + { + "name": "ReplyMarkup", + "json_name": "reply_markup", + "type": { + "kind": "named", + "name": "InlineKeyboardMarkup" + }, + "doc": "Optional. Inline keyboard attached to the message" + }, + { + "name": "InputMessageContent", + "json_name": "input_message_content", + "type": { + "kind": "named", + "name": "InputMessageContent" + }, + "doc": "Optional. Content of the message to be sent instead of the video" + } + ] + }, + { + "name": "InlineQueryResultCachedVoice", + "doc": "Represents a link to a voice message stored on the Telegram servers. By default, this voice message will be sent by the user. Alternatively, you can use input_message_content to send a message with the specified content instead of the voice message.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of the result, must be voice" + }, + { + "name": "ID", + "json_name": "id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique identifier for this result, 1-64 bytes" + }, + { + "name": "VoiceFileID", + "json_name": "voice_file_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "A valid file identifier for the voice message" + }, + { + "name": "Title", + "json_name": "title", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Voice message title" + }, + { + "name": "Caption", + "json_name": "caption", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Caption, 0-1024 characters after entities parsing" + }, + { + "name": "ParseMode", + "json_name": "parse_mode", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Mode for parsing entities in the voice message caption. See formatting options for more details." + }, + { + "name": "CaptionEntities", + "json_name": "caption_entities", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "MessageEntity" + } + }, + "doc": "Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode" + }, + { + "name": "ReplyMarkup", + "json_name": "reply_markup", + "type": { + "kind": "named", + "name": "InlineKeyboardMarkup" + }, + "doc": "Optional. Inline keyboard attached to the message" + }, + { + "name": "InputMessageContent", + "json_name": "input_message_content", + "type": { + "kind": "named", + "name": "InputMessageContent" + }, + "doc": "Optional. Content of the message to be sent instead of the voice message" + } + ] + }, + { + "name": "InlineQueryResultCachedAudio", + "doc": "Represents a link to an MP3 audio file stored on the Telegram servers. By default, this audio file will be sent by the user. Alternatively, you can use input_message_content to send a message with the specified content instead of the audio.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of the result, must be audio" + }, + { + "name": "ID", + "json_name": "id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique identifier for this result, 1-64 bytes" + }, + { + "name": "AudioFileID", + "json_name": "audio_file_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "A valid file identifier for the audio file" + }, + { + "name": "Caption", + "json_name": "caption", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Caption, 0-1024 characters after entities parsing" + }, + { + "name": "ParseMode", + "json_name": "parse_mode", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Mode for parsing entities in the audio caption. See formatting options for more details." + }, + { + "name": "CaptionEntities", + "json_name": "caption_entities", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "MessageEntity" + } + }, + "doc": "Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode" + }, + { + "name": "ReplyMarkup", + "json_name": "reply_markup", + "type": { + "kind": "named", + "name": "InlineKeyboardMarkup" + }, + "doc": "Optional. Inline keyboard attached to the message" + }, + { + "name": "InputMessageContent", + "json_name": "input_message_content", + "type": { + "kind": "named", + "name": "InputMessageContent" + }, + "doc": "Optional. Content of the message to be sent instead of the audio" + } + ] + }, + { + "name": "InputMessageContent", + "doc": "This object represents the content of a message to be sent as a result of an inline query. Telegram clients currently support the following 5 types:", + "one_of": [ + "InputTextMessageContent", + "InputLocationMessageContent", + "InputVenueMessageContent", + "InputContactMessageContent", + "InputInvoiceMessageContent" + ] + }, + { + "name": "InputTextMessageContent", + "doc": "Represents the content of a text message to be sent as the result of an inline query.", + "fields": [ + { + "name": "MessageText", + "json_name": "message_text", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Text of the message to be sent, 1-4096 characters" + }, + { + "name": "ParseMode", + "json_name": "parse_mode", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Mode for parsing entities in the message text. See formatting options for more details." + }, + { + "name": "Entities", + "json_name": "entities", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "MessageEntity" + } + }, + "doc": "Optional. List of special entities that appear in message text, which can be specified instead of parse_mode" + }, + { + "name": "LinkPreviewOptions", + "json_name": "link_preview_options", + "type": { + "kind": "named", + "name": "LinkPreviewOptions" + }, + "doc": "Optional. Link preview generation options for the message" + } + ] + }, + { + "name": "InputLocationMessageContent", + "doc": "Represents the content of a location message to be sent as the result of an inline query.", + "fields": [ + { + "name": "Latitude", + "json_name": "latitude", + "type": { + "kind": "primitive", + "name": "float64" + }, + "required": true, + "doc": "Latitude of the location in degrees" + }, + { + "name": "Longitude", + "json_name": "longitude", + "type": { + "kind": "primitive", + "name": "float64" + }, + "required": true, + "doc": "Longitude of the location in degrees" + }, + { + "name": "HorizontalAccuracy", + "json_name": "horizontal_accuracy", + "type": { + "kind": "primitive", + "name": "float64" + }, + "doc": "Optional. The radius of uncertainty for the location, measured in meters; 0-1500" + }, + { + "name": "LivePeriod", + "json_name": "live_period", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. Period in seconds during which the location can be updated, should be between 60 and 86400, or 0x7FFFFFFF for live locations that can be edited indefinitely." + }, + { + "name": "Heading", + "json_name": "heading", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. For live locations, a direction in which the user is moving, in degrees. Must be between 1 and 360 if specified." + }, + { + "name": "ProximityAlertRadius", + "json_name": "proximity_alert_radius", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. For live locations, a maximum distance for proximity alerts about approaching another chat member, in meters. Must be between 1 and 100000 if specified." + } + ] + }, + { + "name": "InputVenueMessageContent", + "doc": "Represents the content of a venue message to be sent as the result of an inline query.", + "fields": [ + { + "name": "Latitude", + "json_name": "latitude", + "type": { + "kind": "primitive", + "name": "float64" + }, + "required": true, + "doc": "Latitude of the venue in degrees" + }, + { + "name": "Longitude", + "json_name": "longitude", + "type": { + "kind": "primitive", + "name": "float64" + }, + "required": true, + "doc": "Longitude of the venue in degrees" + }, + { + "name": "Title", + "json_name": "title", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Name of the venue" + }, + { + "name": "Address", + "json_name": "address", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Address of the venue" + }, + { + "name": "FoursquareID", + "json_name": "foursquare_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Foursquare identifier of the venue, if known" + }, + { + "name": "FoursquareType", + "json_name": "foursquare_type", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Foursquare type of the venue, if known. (For example, “arts_entertainment/default”, “arts_entertainment/aquarium” or “food/icecream”.)" + }, + { + "name": "GooglePlaceID", + "json_name": "google_place_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Google Places identifier of the venue" + }, + { + "name": "GooglePlaceType", + "json_name": "google_place_type", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Google Places type of the venue. (See supported types.)" + } + ] + }, + { + "name": "InputContactMessageContent", + "doc": "Represents the content of a contact message to be sent as the result of an inline query.", + "fields": [ + { + "name": "PhoneNumber", + "json_name": "phone_number", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Contact's phone number" + }, + { + "name": "FirstName", + "json_name": "first_name", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Contact's first name" + }, + { + "name": "LastName", + "json_name": "last_name", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Contact's last name" + }, + { + "name": "Vcard", + "json_name": "vcard", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Additional data about the contact in the form of a vCard, 0-2048 bytes" + } + ] + }, + { + "name": "InputInvoiceMessageContent", + "doc": "Represents the content of an invoice message to be sent as the result of an inline query.", + "fields": [ + { + "name": "Title", + "json_name": "title", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Product name, 1-32 characters" + }, + { + "name": "Description", + "json_name": "description", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Product description, 1-255 characters" + }, + { + "name": "Payload", + "json_name": "payload", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Bot-defined invoice payload, 1-128 bytes. This will not be displayed to the user, use it for your internal processes." + }, + { + "name": "ProviderToken", + "json_name": "provider_token", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Payment provider token, obtained via @BotFather. Pass an empty string for payments in Telegram Stars." + }, + { + "name": "Currency", + "json_name": "currency", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Three-letter ISO 4217 currency code, see more on currencies. Pass “XTR” for payments in Telegram Stars." + }, + { + "name": "Prices", + "json_name": "prices", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "LabeledPrice" + } + }, + "required": true, + "doc": "Price breakdown, a JSON-serialized list of components (e.g. product price, tax, discount, delivery cost, delivery tax, bonus, etc.). Must contain exactly one item for payments in Telegram Stars." + }, + { + "name": "MaxTipAmount", + "json_name": "max_tip_amount", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. The maximum accepted amount for tips in the smallest units of the currency (integer, not float/double). For example, for a maximum tip of US$ 1.45 pass max_tip_amount = 145. See the exp parameter in currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies). Defaults to 0. Not supported for payments in Telegram Stars." + }, + { + "name": "SuggestedTipAmounts", + "json_name": "suggested_tip_amounts", + "type": { + "kind": "array", + "elem_type": { + "kind": "primitive", + "name": "int64" + } + }, + "doc": "Optional. A JSON-serialized array of suggested amounts of tip in the smallest units of the currency (integer, not float/double). At most 4 suggested tip amounts can be specified. The suggested tip amounts must be positive, passed in a strictly increased order and must not exceed max_tip_amount." + }, + { + "name": "ProviderData", + "json_name": "provider_data", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. A JSON-serialized object for data about the invoice, which will be shared with the payment provider. A detailed description of the required fields should be provided by the payment provider." + }, + { + "name": "PhotoURL", + "json_name": "photo_url", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. URL of the product photo for the invoice. Can be a photo of the goods or a marketing image for a service." + }, + { + "name": "PhotoSize", + "json_name": "photo_size", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. Photo size in bytes" + }, + { + "name": "PhotoWidth", + "json_name": "photo_width", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. Photo width" + }, + { + "name": "PhotoHeight", + "json_name": "photo_height", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. Photo height" + }, + { + "name": "NeedName", + "json_name": "need_name", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. Pass True if you require the user's full name to complete the order. Ignored for payments in Telegram Stars." + }, + { + "name": "NeedPhoneNumber", + "json_name": "need_phone_number", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. Pass True if you require the user's phone number to complete the order. Ignored for payments in Telegram Stars." + }, + { + "name": "NeedEmail", + "json_name": "need_email", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. Pass True if you require the user's email address to complete the order. Ignored for payments in Telegram Stars." + }, + { + "name": "NeedShippingAddress", + "json_name": "need_shipping_address", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. Pass True if you require the user's shipping address to complete the order. Ignored for payments in Telegram Stars." + }, + { + "name": "SendPhoneNumberToProvider", + "json_name": "send_phone_number_to_provider", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. Pass True if the user's phone number should be sent to the provider. Ignored for payments in Telegram Stars." + }, + { + "name": "SendEmailToProvider", + "json_name": "send_email_to_provider", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. Pass True if the user's email address should be sent to the provider. Ignored for payments in Telegram Stars." + }, + { + "name": "IsFlexible", + "json_name": "is_flexible", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. Pass True if the final price depends on the shipping method. Ignored for payments in Telegram Stars." + } + ] + }, + { + "name": "ChosenInlineResult", + "doc": "Represents a result of an inline query that was chosen by the user and sent to their chat partner.\nNote: It is necessary to enable inline feedback via @BotFather in order to receive these objects in updates.", + "fields": [ + { + "name": "ResultID", + "json_name": "result_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "The unique identifier for the result that was chosen" + }, + { + "name": "From", + "json_name": "from", + "type": { + "kind": "named", + "name": "User" + }, + "required": true, + "doc": "The user that chose the result" + }, + { + "name": "Location", + "json_name": "location", + "type": { + "kind": "named", + "name": "Location" + }, + "doc": "Optional. Sender location, only for bots that require user location" + }, + { + "name": "InlineMessageID", + "json_name": "inline_message_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Identifier of the sent inline message. Available only if there is an inline keyboard attached to the message. Will be also received in callback queries and can be used to edit the message." + }, + { + "name": "Query", + "json_name": "query", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "The query that was used to obtain the result" + } + ] + }, + { + "name": "LabeledPrice", + "doc": "This object represents a portion of the price for goods or services.", + "fields": [ + { + "name": "Label", + "json_name": "label", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Portion label" + }, + { + "name": "Amount", + "json_name": "amount", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Price of the product in the smallest units of the currency (integer, not float/double). For example, for a price of US$ 1.45 pass amount = 145. See the exp parameter in currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies)." + } + ] + }, + { + "name": "Invoice", + "doc": "This object contains basic information about an invoice.", + "fields": [ + { + "name": "Title", + "json_name": "title", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Product name" + }, + { + "name": "Description", + "json_name": "description", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Product description" + }, + { + "name": "StartParameter", + "json_name": "start_parameter", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique bot deep-linking parameter that can be used to generate this invoice" + }, + { + "name": "Currency", + "json_name": "currency", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Three-letter ISO 4217 currency code, or “XTR” for payments in Telegram Stars" + }, + { + "name": "TotalAmount", + "json_name": "total_amount", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Total price in the smallest units of the currency (integer, not float/double). For example, for a price of US$ 1.45 pass amount = 145. See the exp parameter in currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies)." + } + ] + }, + { + "name": "ShippingAddress", + "doc": "This object represents a shipping address.", + "fields": [ + { + "name": "CountryCode", + "json_name": "country_code", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Two-letter ISO 3166-1 alpha-2 country code" + }, + { + "name": "State", + "json_name": "state", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "State, if applicable" + }, + { + "name": "City", + "json_name": "city", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "City" + }, + { + "name": "StreetLine1", + "json_name": "street_line1", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "First line for the address" + }, + { + "name": "StreetLine2", + "json_name": "street_line2", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Second line for the address" + }, + { + "name": "PostCode", + "json_name": "post_code", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Address post code" + } + ] + }, + { + "name": "OrderInfo", + "doc": "This object represents information about an order.", + "fields": [ + { + "name": "Name", + "json_name": "name", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. User name" + }, + { + "name": "PhoneNumber", + "json_name": "phone_number", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. User's phone number" + }, + { + "name": "Email", + "json_name": "email", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. User email" + }, + { + "name": "ShippingAddress", + "json_name": "shipping_address", + "type": { + "kind": "named", + "name": "ShippingAddress" + }, + "doc": "Optional. User shipping address" + } + ] + }, + { + "name": "ShippingOption", + "doc": "This object represents one shipping option.", + "fields": [ + { + "name": "ID", + "json_name": "id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Shipping option identifier" + }, + { + "name": "Title", + "json_name": "title", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Option title" + }, + { + "name": "Prices", + "json_name": "prices", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "LabeledPrice" + } + }, + "required": true, + "doc": "List of price portions" + } + ] + }, + { + "name": "SuccessfulPayment", + "doc": "This object contains basic information about a successful payment. Note that if the buyer initiates a chargeback with the relevant payment provider following this transaction, the funds may be debited from your balance. This is outside of Telegram's control.", + "fields": [ + { + "name": "Currency", + "json_name": "currency", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Three-letter ISO 4217 currency code, or “XTR” for payments in Telegram Stars" + }, + { + "name": "TotalAmount", + "json_name": "total_amount", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Total price in the smallest units of the currency (integer, not float/double). For example, for a price of US$ 1.45 pass amount = 145. See the exp parameter in currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies)." + }, + { + "name": "InvoicePayload", + "json_name": "invoice_payload", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Bot-specified invoice payload" + }, + { + "name": "SubscriptionExpirationDate", + "json_name": "subscription_expiration_date", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. Expiration date of the subscription, in Unix time; for recurring payments only" + }, + { + "name": "IsRecurring", + "json_name": "is_recurring", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the payment is a recurring payment for a subscription" + }, + { + "name": "IsFirstRecurring", + "json_name": "is_first_recurring", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Optional. True, if the payment is the first payment for a subscription" + }, + { + "name": "ShippingOptionID", + "json_name": "shipping_option_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Identifier of the shipping option chosen by the user" + }, + { + "name": "OrderInfo", + "json_name": "order_info", + "type": { + "kind": "named", + "name": "OrderInfo" + }, + "doc": "Optional. Order information provided by the user" + }, + { + "name": "TelegramPaymentChargeID", + "json_name": "telegram_payment_charge_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Telegram payment identifier" + }, + { + "name": "ProviderPaymentChargeID", + "json_name": "provider_payment_charge_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Provider payment identifier" + } + ] + }, + { + "name": "RefundedPayment", + "doc": "This object contains basic information about a refunded payment.", + "fields": [ + { + "name": "Currency", + "json_name": "currency", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Three-letter ISO 4217 currency code, or “XTR” for payments in Telegram Stars. Currently, always “XTR”" + }, + { + "name": "TotalAmount", + "json_name": "total_amount", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Total refunded price in the smallest units of the currency (integer, not float/double). For example, for a price of US$ 1.45, total_amount = 145. See the exp parameter in currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies)." + }, + { + "name": "InvoicePayload", + "json_name": "invoice_payload", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Bot-specified invoice payload" + }, + { + "name": "TelegramPaymentChargeID", + "json_name": "telegram_payment_charge_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Telegram payment identifier" + }, + { + "name": "ProviderPaymentChargeID", + "json_name": "provider_payment_charge_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Provider payment identifier" + } + ] + }, + { + "name": "ShippingQuery", + "doc": "This object contains information about an incoming shipping query.", + "fields": [ + { + "name": "ID", + "json_name": "id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique query identifier" + }, + { + "name": "From", + "json_name": "from", + "type": { + "kind": "named", + "name": "User" + }, + "required": true, + "doc": "User who sent the query" + }, + { + "name": "InvoicePayload", + "json_name": "invoice_payload", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Bot-specified invoice payload" + }, + { + "name": "ShippingAddress", + "json_name": "shipping_address", + "type": { + "kind": "named", + "name": "ShippingAddress" + }, + "required": true, + "doc": "User specified shipping address" + } + ] + }, + { + "name": "PreCheckoutQuery", + "doc": "This object contains information about an incoming pre-checkout query.", + "fields": [ + { + "name": "ID", + "json_name": "id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique query identifier" + }, + { + "name": "From", + "json_name": "from", + "type": { + "kind": "named", + "name": "User" + }, + "required": true, + "doc": "User who sent the query" + }, + { + "name": "Currency", + "json_name": "currency", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Three-letter ISO 4217 currency code, or “XTR” for payments in Telegram Stars" + }, + { + "name": "TotalAmount", + "json_name": "total_amount", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Total price in the smallest units of the currency (integer, not float/double). For example, for a price of US$ 1.45 pass amount = 145. See the exp parameter in currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies)." + }, + { + "name": "InvoicePayload", + "json_name": "invoice_payload", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Bot-specified invoice payload" + }, + { + "name": "ShippingOptionID", + "json_name": "shipping_option_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Identifier of the shipping option chosen by the user" + }, + { + "name": "OrderInfo", + "json_name": "order_info", + "type": { + "kind": "named", + "name": "OrderInfo" + }, + "doc": "Optional. Order information provided by the user" + } + ] + }, + { + "name": "PaidMediaPurchased", + "doc": "This object contains information about a paid media purchase.", + "fields": [ + { + "name": "From", + "json_name": "from", + "type": { + "kind": "named", + "name": "User" + }, + "required": true, + "doc": "User who purchased the media" + }, + { + "name": "PaidMediaPayload", + "json_name": "paid_media_payload", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Bot-specified paid media payload" + } + ] + }, + { + "name": "RevenueWithdrawalState", + "doc": "This object describes the state of a revenue withdrawal operation. Currently, it can be one of", + "one_of": [ + "RevenueWithdrawalStatePending", + "RevenueWithdrawalStateSucceeded", + "RevenueWithdrawalStateFailed" + ] + }, + { + "name": "RevenueWithdrawalStatePending", + "doc": "The withdrawal is in progress.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of the state, always “pending”" + } + ] + }, + { + "name": "RevenueWithdrawalStateSucceeded", + "doc": "The withdrawal succeeded.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of the state, always “succeeded”" + }, + { + "name": "Date", + "json_name": "date", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Date the withdrawal was completed in Unix time" + }, + { + "name": "URL", + "json_name": "url", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "An HTTPS URL that can be used to see transaction details" + } + ] + }, + { + "name": "RevenueWithdrawalStateFailed", + "doc": "The withdrawal failed and the transaction was refunded.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of the state, always “failed”" + } + ] + }, + { + "name": "AffiliateInfo", + "doc": "Contains information about the affiliate that received a commission via this transaction.", + "fields": [ + { + "name": "AffiliateUser", + "json_name": "affiliate_user", + "type": { + "kind": "named", + "name": "User" + }, + "doc": "Optional. The bot or the user that received an affiliate commission if it was received by a bot or a user" + }, + { + "name": "AffiliateChat", + "json_name": "affiliate_chat", + "type": { + "kind": "named", + "name": "Chat" + }, + "doc": "Optional. The chat that received an affiliate commission if it was received by a chat" + }, + { + "name": "CommissionPerMille", + "json_name": "commission_per_mille", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "The number of Telegram Stars received by the affiliate for each 1000 Telegram Stars received by the bot from referred users" + }, + { + "name": "Amount", + "json_name": "amount", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Integer amount of Telegram Stars received by the affiliate from the transaction, rounded to 0; can be negative for refunds" + }, + { + "name": "NanostarAmount", + "json_name": "nanostar_amount", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. The number of 1/1000000000 shares of Telegram Stars received by the affiliate; from -999999999 to 999999999; can be negative for refunds" + } + ] + }, + { + "name": "TransactionPartner", + "doc": "This object describes the source of a transaction, or its recipient for outgoing transactions. Currently, it can be one of", + "one_of": [ + "TransactionPartnerUser", + "TransactionPartnerChat", + "TransactionPartnerAffiliateProgram", + "TransactionPartnerFragment", + "TransactionPartnerTelegramAds", + "TransactionPartnerTelegramApi", + "TransactionPartnerOther" + ] + }, + { + "name": "TransactionPartnerUser", + "doc": "Describes a transaction with a user.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of the transaction partner, always “user”" + }, + { + "name": "TransactionType", + "json_name": "transaction_type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of the transaction, currently one of “invoice_payment” for payments via invoices, “paid_media_payment” for payments for paid media, “gift_purchase” for gifts sent by the bot, “premium_purchase” for Telegram Premium subscriptions gifted by the bot, “business_account_transfer” for direct transfers from managed business accounts" + }, + { + "name": "User", + "json_name": "user", + "type": { + "kind": "named", + "name": "User" + }, + "required": true, + "doc": "Information about the user" + }, + { + "name": "Affiliate", + "json_name": "affiliate", + "type": { + "kind": "named", + "name": "AffiliateInfo" + }, + "doc": "Optional. Information about the affiliate that received a commission via this transaction. Can be available only for “invoice_payment” and “paid_media_payment” transactions." + }, + { + "name": "InvoicePayload", + "json_name": "invoice_payload", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Bot-specified invoice payload. Can be available only for “invoice_payment” transactions." + }, + { + "name": "SubscriptionPeriod", + "json_name": "subscription_period", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. The duration of the paid subscription. Can be available only for “invoice_payment” transactions." + }, + { + "name": "PaidMedia", + "json_name": "paid_media", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "PaidMedia" + } + }, + "doc": "Optional. Information about the paid media bought by the user; for “paid_media_payment” transactions only" + }, + { + "name": "PaidMediaPayload", + "json_name": "paid_media_payload", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Bot-specified paid media payload. Can be available only for “paid_media_payment” transactions." + }, + { + "name": "Gift", + "json_name": "gift", + "type": { + "kind": "named", + "name": "Gift" + }, + "doc": "Optional. The gift sent to the user by the bot; for “gift_purchase” transactions only" + }, + { + "name": "PremiumSubscriptionDuration", + "json_name": "premium_subscription_duration", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. Number of months the gifted Telegram Premium subscription will be active for; for “premium_purchase” transactions only" + } + ] + }, + { + "name": "TransactionPartnerChat", + "doc": "Describes a transaction with a chat.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of the transaction partner, always “chat”" + }, + { + "name": "Chat", + "json_name": "chat", + "type": { + "kind": "named", + "name": "Chat" + }, + "required": true, + "doc": "Information about the chat" + }, + { + "name": "Gift", + "json_name": "gift", + "type": { + "kind": "named", + "name": "Gift" + }, + "doc": "Optional. The gift sent to the chat by the bot" + } + ] + }, + { + "name": "TransactionPartnerAffiliateProgram", + "doc": "Describes the affiliate program that issued the affiliate commission received via this transaction.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of the transaction partner, always “affiliate_program”" + }, + { + "name": "SponsorUser", + "json_name": "sponsor_user", + "type": { + "kind": "named", + "name": "User" + }, + "doc": "Optional. Information about the bot that sponsored the affiliate program" + }, + { + "name": "CommissionPerMille", + "json_name": "commission_per_mille", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "The number of Telegram Stars received by the bot for each 1000 Telegram Stars received by the affiliate program sponsor from referred users" + } + ] + }, + { + "name": "TransactionPartnerFragment", + "doc": "Describes a withdrawal transaction with Fragment.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of the transaction partner, always “fragment”" + }, + { + "name": "WithdrawalState", + "json_name": "withdrawal_state", + "type": { + "kind": "named", + "name": "RevenueWithdrawalState" + }, + "doc": "Optional. State of the transaction if the transaction is outgoing" + } + ] + }, + { + "name": "TransactionPartnerTelegramAds", + "doc": "Describes a withdrawal transaction to the Telegram Ads platform.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of the transaction partner, always “telegram_ads”" + } + ] + }, + { + "name": "TransactionPartnerTelegramApi", + "doc": "Describes a transaction with payment for paid broadcasting.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of the transaction partner, always “telegram_api”" + }, + { + "name": "RequestCount", + "json_name": "request_count", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "The number of successful requests that exceeded regular limits and were therefore billed" + } + ] + }, + { + "name": "TransactionPartnerOther", + "doc": "Describes a transaction with an unknown source or recipient.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of the transaction partner, always “other”" + } + ] + }, + { + "name": "StarTransaction", + "doc": "Describes a Telegram Star transaction. Note that if the buyer initiates a chargeback with the payment provider from whom they acquired Stars (e.g., Apple, Google) following this transaction, the refunded Stars will be deducted from the bot's balance. This is outside of Telegram's control.", + "fields": [ + { + "name": "ID", + "json_name": "id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique identifier of the transaction. Coincides with the identifier of the original transaction for refund transactions. Coincides with SuccessfulPayment.telegram_payment_charge_id for successful incoming payments from users." + }, + { + "name": "Amount", + "json_name": "amount", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Integer amount of Telegram Stars transferred by the transaction" + }, + { + "name": "NanostarAmount", + "json_name": "nanostar_amount", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Optional. The number of 1/1000000000 shares of Telegram Stars transferred by the transaction; from 0 to 999999999" + }, + { + "name": "Date", + "json_name": "date", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Date the transaction was created in Unix time" + }, + { + "name": "Source", + "json_name": "source", + "type": { + "kind": "named", + "name": "TransactionPartner" + }, + "doc": "Optional. Source of an incoming transaction (e.g., a user purchasing goods or services, Fragment refunding a failed withdrawal). Only for incoming transactions" + }, + { + "name": "Receiver", + "json_name": "receiver", + "type": { + "kind": "named", + "name": "TransactionPartner" + }, + "doc": "Optional. Receiver of an outgoing transaction (e.g., a user for a purchase refund, Fragment for a withdrawal). Only for outgoing transactions" + } + ] + }, + { + "name": "StarTransactions", + "doc": "Contains a list of Telegram Star transactions.", + "fields": [ + { + "name": "Transactions", + "json_name": "transactions", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "StarTransaction" + } + }, + "required": true, + "doc": "The list of transactions" + } + ] + }, + { + "name": "PassportData", + "doc": "Describes Telegram Passport data shared with the bot by the user.", + "fields": [ + { + "name": "Data", + "json_name": "data", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "EncryptedPassportElement" + } + }, + "required": true, + "doc": "Array with information about documents and other Telegram Passport elements that was shared with the bot" + }, + { + "name": "Credentials", + "json_name": "credentials", + "type": { + "kind": "named", + "name": "EncryptedCredentials" + }, + "required": true, + "doc": "Encrypted credentials required to decrypt the data" + } + ] + }, + { + "name": "PassportFile", + "doc": "This object represents a file uploaded to Telegram Passport. Currently all Telegram Passport files are in JPEG format when decrypted and don't exceed 10MB.", + "fields": [ + { + "name": "FileID", + "json_name": "file_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Identifier for this file, which can be used to download or reuse the file" + }, + { + "name": "FileUniqueID", + "json_name": "file_unique_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file." + }, + { + "name": "FileSize", + "json_name": "file_size", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "File size in bytes" + }, + { + "name": "FileDate", + "json_name": "file_date", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Unix time when the file was uploaded" + } + ] + }, + { + "name": "EncryptedPassportElement", + "doc": "Describes documents or other Telegram Passport elements shared with the bot by the user.", + "fields": [ + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Element type. One of “personal_details”, “passport”, “driver_license”, “identity_card”, “internal_passport”, “address”, “utility_bill”, “bank_statement”, “rental_agreement”, “passport_registration”, “temporary_registration”, “phone_number”, “email”." + }, + { + "name": "Data", + "json_name": "data", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Base64-encoded encrypted Telegram Passport element data provided by the user; available only for “personal_details”, “passport”, “driver_license”, “identity_card”, “internal_passport” and “address” types. Can be decrypted and verified using the accompanying EncryptedCredentials." + }, + { + "name": "PhoneNumber", + "json_name": "phone_number", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. User's verified phone number; available only for “phone_number” type" + }, + { + "name": "Email", + "json_name": "email", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. User's verified email address; available only for “email” type" + }, + { + "name": "Files", + "json_name": "files", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "PassportFile" + } + }, + "doc": "Optional. Array of encrypted files with documents provided by the user; available only for “utility_bill”, “bank_statement”, “rental_agreement”, “passport_registration” and “temporary_registration” types. Files can be decrypted and verified using the accompanying EncryptedCredentials." + }, + { + "name": "FrontSide", + "json_name": "front_side", + "type": { + "kind": "named", + "name": "PassportFile" + }, + "doc": "Optional. Encrypted file with the front side of the document, provided by the user; available only for “passport”, “driver_license”, “identity_card” and “internal_passport”. The file can be decrypted and verified using the accompanying EncryptedCredentials." + }, + { + "name": "ReverseSide", + "json_name": "reverse_side", + "type": { + "kind": "named", + "name": "PassportFile" + }, + "doc": "Optional. Encrypted file with the reverse side of the document, provided by the user; available only for “driver_license” and “identity_card”. The file can be decrypted and verified using the accompanying EncryptedCredentials." + }, + { + "name": "Selfie", + "json_name": "selfie", + "type": { + "kind": "named", + "name": "PassportFile" + }, + "doc": "Optional. Encrypted file with the selfie of the user holding a document, provided by the user; available if requested for “passport”, “driver_license”, “identity_card” and “internal_passport”. The file can be decrypted and verified using the accompanying EncryptedCredentials." + }, + { + "name": "Translation", + "json_name": "translation", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "PassportFile" + } + }, + "doc": "Optional. Array of encrypted files with translated versions of documents provided by the user; available if requested for “passport”, “driver_license”, “identity_card”, “internal_passport”, “utility_bill”, “bank_statement”, “rental_agreement”, “passport_registration” and “temporary_registration” types. Files can be decrypted and verified using the accompanying EncryptedCredentials." + }, + { + "name": "Hash", + "json_name": "hash", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Base64-encoded element hash for using in PassportElementErrorUnspecified" + } + ] + }, + { + "name": "EncryptedCredentials", + "doc": "Describes data required for decrypting and authenticating EncryptedPassportElement. See the Telegram Passport Documentation for a complete description of the data decryption and authentication processes.", + "fields": [ + { + "name": "Data", + "json_name": "data", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Base64-encoded encrypted JSON-serialized data with unique user's payload, data hashes and secrets required for EncryptedPassportElement decryption and authentication" + }, + { + "name": "Hash", + "json_name": "hash", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Base64-encoded data hash for data authentication" + }, + { + "name": "Secret", + "json_name": "secret", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Base64-encoded secret, encrypted with the bot's public RSA key, required for data decryption" + } + ] + }, + { + "name": "PassportElementError", + "doc": "This object represents an error in the Telegram Passport element which was submitted that should be resolved by the user. It should be one of:", + "one_of": [ + "PassportElementErrorDataField", + "PassportElementErrorFrontSide", + "PassportElementErrorReverseSide", + "PassportElementErrorSelfie", + "PassportElementErrorFile", + "PassportElementErrorFiles", + "PassportElementErrorTranslationFile", + "PassportElementErrorTranslationFiles", + "PassportElementErrorUnspecified" + ] + }, + { + "name": "PassportElementErrorDataField", + "doc": "Represents an issue in one of the data fields that was provided by the user. The error is considered resolved when the field's value changes.", + "fields": [ + { + "name": "Source", + "json_name": "source", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Error source, must be data" + }, + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "The section of the user's Telegram Passport which has the error, one of “personal_details”, “passport”, “driver_license”, “identity_card”, “internal_passport”, “address”" + }, + { + "name": "FieldName", + "json_name": "field_name", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Name of the data field which has the error" + }, + { + "name": "DataHash", + "json_name": "data_hash", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Base64-encoded data hash" + }, + { + "name": "Message", + "json_name": "message", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Error message" + } + ] + }, + { + "name": "PassportElementErrorFrontSide", + "doc": "Represents an issue with the front side of a document. The error is considered resolved when the file with the front side of the document changes.", + "fields": [ + { + "name": "Source", + "json_name": "source", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Error source, must be front_side" + }, + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "The section of the user's Telegram Passport which has the issue, one of “passport”, “driver_license”, “identity_card”, “internal_passport”" + }, + { + "name": "FileHash", + "json_name": "file_hash", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Base64-encoded hash of the file with the front side of the document" + }, + { + "name": "Message", + "json_name": "message", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Error message" + } + ] + }, + { + "name": "PassportElementErrorReverseSide", + "doc": "Represents an issue with the reverse side of a document. The error is considered resolved when the file with reverse side of the document changes.", + "fields": [ + { + "name": "Source", + "json_name": "source", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Error source, must be reverse_side" + }, + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "The section of the user's Telegram Passport which has the issue, one of “driver_license”, “identity_card”" + }, + { + "name": "FileHash", + "json_name": "file_hash", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Base64-encoded hash of the file with the reverse side of the document" + }, + { + "name": "Message", + "json_name": "message", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Error message" + } + ] + }, + { + "name": "PassportElementErrorSelfie", + "doc": "Represents an issue with the selfie with a document. The error is considered resolved when the file with the selfie changes.", + "fields": [ + { + "name": "Source", + "json_name": "source", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Error source, must be selfie" + }, + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "The section of the user's Telegram Passport which has the issue, one of “passport”, “driver_license”, “identity_card”, “internal_passport”" + }, + { + "name": "FileHash", + "json_name": "file_hash", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Base64-encoded hash of the file with the selfie" + }, + { + "name": "Message", + "json_name": "message", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Error message" + } + ] + }, + { + "name": "PassportElementErrorFile", + "doc": "Represents an issue with a document scan. The error is considered resolved when the file with the document scan changes.", + "fields": [ + { + "name": "Source", + "json_name": "source", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Error source, must be file" + }, + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "The section of the user's Telegram Passport which has the issue, one of “utility_bill”, “bank_statement”, “rental_agreement”, “passport_registration”, “temporary_registration”" + }, + { + "name": "FileHash", + "json_name": "file_hash", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Base64-encoded file hash" + }, + { + "name": "Message", + "json_name": "message", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Error message" + } + ] + }, + { + "name": "PassportElementErrorFiles", + "doc": "Represents an issue with a list of scans. The error is considered resolved when the list of files containing the scans changes.", + "fields": [ + { + "name": "Source", + "json_name": "source", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Error source, must be files" + }, + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "The section of the user's Telegram Passport which has the issue, one of “utility_bill”, “bank_statement”, “rental_agreement”, “passport_registration”, “temporary_registration”" + }, + { + "name": "FileHashes", + "json_name": "file_hashes", + "type": { + "kind": "array", + "elem_type": { + "kind": "primitive", + "name": "string" + } + }, + "required": true, + "doc": "List of base64-encoded file hashes" + }, + { + "name": "Message", + "json_name": "message", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Error message" + } + ] + }, + { + "name": "PassportElementErrorTranslationFile", + "doc": "Represents an issue with one of the files that constitute the translation of a document. The error is considered resolved when the file changes.", + "fields": [ + { + "name": "Source", + "json_name": "source", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Error source, must be translation_file" + }, + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of element of the user's Telegram Passport which has the issue, one of “passport”, “driver_license”, “identity_card”, “internal_passport”, “utility_bill”, “bank_statement”, “rental_agreement”, “passport_registration”, “temporary_registration”" + }, + { + "name": "FileHash", + "json_name": "file_hash", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Base64-encoded file hash" + }, + { + "name": "Message", + "json_name": "message", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Error message" + } + ] + }, + { + "name": "PassportElementErrorTranslationFiles", + "doc": "Represents an issue with the translated version of a document. The error is considered resolved when a file with the document translation change.", + "fields": [ + { + "name": "Source", + "json_name": "source", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Error source, must be translation_files" + }, + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of element of the user's Telegram Passport which has the issue, one of “passport”, “driver_license”, “identity_card”, “internal_passport”, “utility_bill”, “bank_statement”, “rental_agreement”, “passport_registration”, “temporary_registration”" + }, + { + "name": "FileHashes", + "json_name": "file_hashes", + "type": { + "kind": "array", + "elem_type": { + "kind": "primitive", + "name": "string" + } + }, + "required": true, + "doc": "List of base64-encoded file hashes" + }, + { + "name": "Message", + "json_name": "message", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Error message" + } + ] + }, + { + "name": "PassportElementErrorUnspecified", + "doc": "Represents an issue in an unspecified place. The error is considered resolved when new data is added.", + "fields": [ + { + "name": "Source", + "json_name": "source", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Error source, must be unspecified" + }, + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of element of the user's Telegram Passport which has the issue" + }, + { + "name": "ElementHash", + "json_name": "element_hash", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Base64-encoded element hash" + }, + { + "name": "Message", + "json_name": "message", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Error message" + } + ] + }, + { + "name": "Game", + "doc": "This object represents a game. Use BotFather to create and edit games, their short names will act as unique identifiers.", + "fields": [ + { + "name": "Title", + "json_name": "title", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Title of the game" + }, + { + "name": "Description", + "json_name": "description", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Description of the game" + }, + { + "name": "Photo", + "json_name": "photo", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "PhotoSize" + } + }, + "required": true, + "doc": "Photo that will be displayed in the game message in chats." + }, + { + "name": "Text", + "json_name": "text", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. Brief description of the game or high scores included in the game message. Can be automatically edited to include current high scores for the game when the bot calls setGameScore, or manually edited using editMessageText. 0-4096 characters." + }, + { + "name": "TextEntities", + "json_name": "text_entities", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "MessageEntity" + } + }, + "doc": "Optional. Special entities that appear in text, such as usernames, URLs, bot commands, etc." + }, + { + "name": "Animation", + "json_name": "animation", + "type": { + "kind": "named", + "name": "Animation" + }, + "doc": "Optional. Animation that will be displayed in the game message in chats. Upload via BotFather" + } + ] + }, + { + "name": "CallbackGame", + "doc": "A placeholder, currently holds no information. Use BotFather to set up your game." + }, + { + "name": "GameHighScore", + "doc": "This object represents one row of the high scores table for a game.\nAnd that's about all we've got for now.If you've got any questions, please check out our Bot FAQ »", + "fields": [ + { + "name": "Position", + "json_name": "position", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Position in high score table for the game" + }, + { + "name": "User", + "json_name": "user", + "type": { + "kind": "named", + "name": "User" + }, + "required": true, + "doc": "User" + }, + { + "name": "Score", + "json_name": "score", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Score" + } + ] + } + ], + "methods": [ + { + "name": "getUpdates", + "doc": "Use this method to receive incoming updates using long polling (wiki). Returns an Array of Update objects.\nNotes1. This method will not work if an outgoing webhook is set up.2. In order to avoid getting duplicate updates, recalculate offset after each server response.", + "params": [ + { + "name": "Offset", + "json_name": "offset", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Identifier of the first update to be returned. Must be greater by one than the highest among the identifiers of previously received updates. By default, updates starting with the earliest unconfirmed update are returned. An update is considered confirmed as soon as getUpdates is called with an offset higher than its update_id. The negative offset can be specified to retrieve updates starting from -offset update from the end of the updates queue. All previous updates will be forgotten." + }, + { + "name": "Limit", + "json_name": "limit", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Limits the number of updates to be retrieved. Values between 1-100 are accepted. Defaults to 100." + }, + { + "name": "Timeout", + "json_name": "timeout", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Timeout in seconds for long polling. Defaults to 0, i.e. usual short polling. Should be positive, short polling should be used for testing purposes only." + }, + { + "name": "AllowedUpdates", + "json_name": "allowed_updates", + "type": { + "kind": "array", + "elem_type": { + "kind": "primitive", + "name": "string" + } + }, + "doc": "A JSON-serialized list of the update types you want your bot to receive. For example, specify [\"message\", \"edited_channel_post\", \"callback_query\"] to only receive updates of these types. See Update for a complete list of available update types. Specify an empty list to receive all update types except chat_member, message_reaction, and message_reaction_count (default). If not specified, the previous setting will be used.Please note that this parameter doesn't affect updates created before the call to getUpdates, so unwanted updates may be received for a short period of time." + } + ], + "returns": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "Update" + } + } + }, + { + "name": "setWebhook", + "doc": "Use this method to specify a URL and receive incoming updates via an outgoing webhook. Whenever there is an update for the bot, we will send an HTTPS POST request to the specified URL, containing a JSON-serialized Update. In case of an unsuccessful request (a request with response HTTP status code different from 2XY), we will repeat the request and give up after a reasonable amount of attempts. Returns True on success.\nIf you'd like to make sure that the webhook was set by you, you can specify secret data in the parameter secret_token. If specified, the request will contain a header “X-Telegram-Bot-Api-Secret-Token” with the secret token as content.\nNotes1. You will not be able to receive updates using getUpdates for as long as an outgoing webhook is set up.2. To use a self-signed certificate, you need to upload your public key certificate using certificate parameter. Please upload as InputFile, sending a String will not work.3. Ports currently supported for webhooks: 443, 80, 88, 8443.\nIf you're having any trouble setting up webhooks, please check out this amazing guide to webhooks.", + "params": [ + { + "name": "URL", + "json_name": "url", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "HTTPS URL to send updates to. Use an empty string to remove webhook integration" + }, + { + "name": "Certificate", + "json_name": "certificate", + "type": { + "kind": "named", + "name": "InputFile" + }, + "doc": "Upload your public key certificate so that the root certificate in use can be checked. See our self-signed guide for details." + }, + { + "name": "IPAddress", + "json_name": "ip_address", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "The fixed IP address which will be used to send webhook requests instead of the IP address resolved through DNS" + }, + { + "name": "MaxConnections", + "json_name": "max_connections", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "The maximum allowed number of simultaneous HTTPS connections to the webhook for update delivery, 1-100. Defaults to 40. Use lower values to limit the load on your bot's server, and higher values to increase your bot's throughput." + }, + { + "name": "AllowedUpdates", + "json_name": "allowed_updates", + "type": { + "kind": "array", + "elem_type": { + "kind": "primitive", + "name": "string" + } + }, + "doc": "A JSON-serialized list of the update types you want your bot to receive. For example, specify [\"message\", \"edited_channel_post\", \"callback_query\"] to only receive updates of these types. See Update for a complete list of available update types. Specify an empty list to receive all update types except chat_member, message_reaction, and message_reaction_count (default). If not specified, the previous setting will be used.Please note that this parameter doesn't affect updates created before the call to the setWebhook, so unwanted updates may be received for a short period of time." + }, + { + "name": "DropPendingUpdates", + "json_name": "drop_pending_updates", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True to drop all pending updates" + }, + { + "name": "SecretToken", + "json_name": "secret_token", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "A secret token to be sent in a header “X-Telegram-Bot-Api-Secret-Token” in every webhook request, 1-256 characters. Only characters A-Z, a-z, 0-9, _ and - are allowed. The header is useful to ensure that the request comes from a webhook set by you." + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + }, + "has_files": true + }, + { + "name": "deleteWebhook", + "doc": "Use this method to remove webhook integration if you decide to switch back to getUpdates. Returns True on success.", + "params": [ + { + "name": "DropPendingUpdates", + "json_name": "drop_pending_updates", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True to drop all pending updates" + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "getWebhookInfo", + "doc": "Use this method to get current webhook status. Requires no parameters. On success, returns a WebhookInfo object. If the bot is using getUpdates, will return an object with the url field empty.", + "returns": { + "kind": "named", + "name": "WebhookInfo" + } + }, + { + "name": "getMe", + "doc": "A simple method for testing your bot's authentication token. Requires no parameters. Returns basic information about the bot in form of a User object.", + "returns": { + "kind": "named", + "name": "User" + } + }, + { + "name": "logOut", + "doc": "Use this method to log out from the cloud Bot API server before launching the bot locally. You must log out the bot before running it locally, otherwise there is no guarantee that the bot will receive updates. After a successful call, you can immediately log in on a local server, but will not be able to log in back to the cloud Bot API server for 10 minutes. Returns True on success. Requires no parameters.", + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "close", + "doc": "Use this method to close the bot instance before moving it from one local server to another. You need to delete the webhook before calling this method to ensure that the bot isn't launched again after server restart. The method will return error 429 in the first 10 minutes after the bot is launched. Returns True on success. Requires no parameters.", + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "sendMessage", + "doc": "Use this method to send text messages. On success, the sent Message is returned.", + "params": [ + { + "name": "BusinessConnectionID", + "json_name": "business_connection_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Unique identifier of the business connection on behalf of which the message will be sent" + }, + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username" + }, + { + "name": "MessageThreadID", + "json_name": "message_thread_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only" + }, + { + "name": "DirectMessagesTopicID", + "json_name": "direct_messages_topic_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Identifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat" + }, + { + "name": "Text", + "json_name": "text", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Text of the message to be sent, 1-4096 characters after entities parsing" + }, + { + "name": "ParseMode", + "json_name": "parse_mode", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Mode for parsing entities in the message text. See formatting options for more details." + }, + { + "name": "Entities", + "json_name": "entities", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "MessageEntity" + } + }, + "doc": "A JSON-serialized list of special entities that appear in message text, which can be specified instead of parse_mode" + }, + { + "name": "LinkPreviewOptions", + "json_name": "link_preview_options", + "type": { + "kind": "named", + "name": "LinkPreviewOptions" + }, + "doc": "Link preview generation options for the message" + }, + { + "name": "DisableNotification", + "json_name": "disable_notification", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Sends the message silently. Users will receive a notification with no sound." + }, + { + "name": "ProtectContent", + "json_name": "protect_content", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Protects the contents of the sent message from forwarding and saving" + }, + { + "name": "AllowPaidBroadcast", + "json_name": "allow_paid_broadcast", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance." + }, + { + "name": "MessageEffectID", + "json_name": "message_effect_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Unique identifier of the message effect to be added to the message; for private chats only" + }, + { + "name": "SuggestedPostParameters", + "json_name": "suggested_post_parameters", + "type": { + "kind": "named", + "name": "SuggestedPostParameters" + }, + "doc": "A JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined." + }, + { + "name": "ReplyParameters", + "json_name": "reply_parameters", + "type": { + "kind": "named", + "name": "ReplyParameters" + }, + "doc": "Description of the message to reply to" + }, + { + "name": "ReplyMarkup", + "json_name": "reply_markup", + "type": { + "kind": "oneOf", + "variants": [ + "InlineKeyboardMarkup", + "ReplyKeyboardMarkup", + "ReplyKeyboardRemove", + "ForceReply" + ] + }, + "doc": "Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user" + } + ], + "returns": { + "kind": "named", + "name": "Message" + } + }, + { + "name": "forwardMessage", + "doc": "Use this method to forward messages of any kind. Service messages and messages with protected content can't be forwarded. On success, the sent Message is returned.", + "params": [ + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username" + }, + { + "name": "MessageThreadID", + "json_name": "message_thread_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only" + }, + { + "name": "DirectMessagesTopicID", + "json_name": "direct_messages_topic_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Identifier of the direct messages topic to which the message will be forwarded; required if the message is forwarded to a direct messages chat" + }, + { + "name": "FromChatID", + "json_name": "from_chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the chat where the original message was sent (or username of the target bot, supergroup or channel in the format @username)" + }, + { + "name": "VideoStartTimestamp", + "json_name": "video_start_timestamp", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "New start timestamp for the forwarded video in the message" + }, + { + "name": "DisableNotification", + "json_name": "disable_notification", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Sends the message silently. Users will receive a notification with no sound." + }, + { + "name": "ProtectContent", + "json_name": "protect_content", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Protects the contents of the forwarded message from forwarding and saving" + }, + { + "name": "MessageEffectID", + "json_name": "message_effect_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Unique identifier of the message effect to be added to the message; only available when forwarding to private chats" + }, + { + "name": "SuggestedPostParameters", + "json_name": "suggested_post_parameters", + "type": { + "kind": "named", + "name": "SuggestedPostParameters" + }, + "doc": "A JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only" + }, + { + "name": "MessageID", + "json_name": "message_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Message identifier in the chat specified in from_chat_id" + } + ], + "returns": { + "kind": "named", + "name": "Message" + } + }, + { + "name": "forwardMessages", + "doc": "Use this method to forward multiple messages of any kind. If some of the specified messages can't be found or forwarded, they are skipped. Service messages and messages with protected content can't be forwarded. Album grouping is kept for forwarded messages. On success, an array of MessageId of the sent messages is returned.", + "params": [ + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username" + }, + { + "name": "MessageThreadID", + "json_name": "message_thread_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only" + }, + { + "name": "DirectMessagesTopicID", + "json_name": "direct_messages_topic_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Identifier of the direct messages topic to which the messages will be forwarded; required if the messages are forwarded to a direct messages chat" + }, + { + "name": "FromChatID", + "json_name": "from_chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the chat where the original messages were sent (or username of the target bot, supergroup or channel in the format @username)" + }, + { + "name": "MessageIds", + "json_name": "message_ids", + "type": { + "kind": "array", + "elem_type": { + "kind": "primitive", + "name": "int64" + } + }, + "required": true, + "doc": "A JSON-serialized list of 1-100 identifiers of messages in the chat from_chat_id to forward. The identifiers must be specified in a strictly increasing order." + }, + { + "name": "DisableNotification", + "json_name": "disable_notification", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Sends the messages silently. Users will receive a notification with no sound." + }, + { + "name": "ProtectContent", + "json_name": "protect_content", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Protects the contents of the forwarded messages from forwarding and saving" + } + ], + "returns": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "MessageId" + } + } + }, + { + "name": "copyMessage", + "doc": "Use this method to copy messages of any kind. Service messages, paid media messages, giveaway messages, giveaway winners messages, and invoice messages can't be copied. A quiz poll can be copied only if the value of the field correct_option_id is known to the bot. The method is analogous to the method forwardMessage, but the copied message doesn't have a link to the original message. Returns the MessageId of the sent message on success.", + "params": [ + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username" + }, + { + "name": "MessageThreadID", + "json_name": "message_thread_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only" + }, + { + "name": "DirectMessagesTopicID", + "json_name": "direct_messages_topic_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Identifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat" + }, + { + "name": "FromChatID", + "json_name": "from_chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the chat where the original message was sent (or username of the target bot, supergroup or channel in the format @username)" + }, + { + "name": "MessageID", + "json_name": "message_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Message identifier in the chat specified in from_chat_id" + }, + { + "name": "VideoStartTimestamp", + "json_name": "video_start_timestamp", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "New start timestamp for the copied video in the message" + }, + { + "name": "Caption", + "json_name": "caption", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "New caption for media, 0-1024 characters after entities parsing. If not specified, the original caption is kept" + }, + { + "name": "ParseMode", + "json_name": "parse_mode", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Mode for parsing entities in the new caption. See formatting options for more details." + }, + { + "name": "CaptionEntities", + "json_name": "caption_entities", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "MessageEntity" + } + }, + "doc": "A JSON-serialized list of special entities that appear in the new caption, which can be specified instead of parse_mode" + }, + { + "name": "ShowCaptionAboveMedia", + "json_name": "show_caption_above_media", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True, if the caption must be shown above the message media. Ignored if a new caption isn't specified." + }, + { + "name": "DisableNotification", + "json_name": "disable_notification", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Sends the message silently. Users will receive a notification with no sound." + }, + { + "name": "ProtectContent", + "json_name": "protect_content", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Protects the contents of the sent message from forwarding and saving" + }, + { + "name": "AllowPaidBroadcast", + "json_name": "allow_paid_broadcast", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance." + }, + { + "name": "MessageEffectID", + "json_name": "message_effect_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Unique identifier of the message effect to be added to the message; only available when copying to private chats" + }, + { + "name": "SuggestedPostParameters", + "json_name": "suggested_post_parameters", + "type": { + "kind": "named", + "name": "SuggestedPostParameters" + }, + "doc": "A JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined." + }, + { + "name": "ReplyParameters", + "json_name": "reply_parameters", + "type": { + "kind": "named", + "name": "ReplyParameters" + }, + "doc": "Description of the message to reply to" + }, + { + "name": "ReplyMarkup", + "json_name": "reply_markup", + "type": { + "kind": "oneOf", + "variants": [ + "InlineKeyboardMarkup", + "ReplyKeyboardMarkup", + "ReplyKeyboardRemove", + "ForceReply" + ] + }, + "doc": "Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user" + } + ], + "returns": { + "kind": "named", + "name": "MessageId" + } + }, + { + "name": "copyMessages", + "doc": "Use this method to copy messages of any kind. If some of the specified messages can't be found or copied, they are skipped. Service messages, paid media messages, giveaway messages, giveaway winners messages, and invoice messages can't be copied. A quiz poll can be copied only if the value of the field correct_option_id is known to the bot. The method is analogous to the method forwardMessages, but the copied messages don't have a link to the original message. Album grouping is kept for copied messages. On success, an array of MessageId of the sent messages is returned.", + "params": [ + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username" + }, + { + "name": "MessageThreadID", + "json_name": "message_thread_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only" + }, + { + "name": "DirectMessagesTopicID", + "json_name": "direct_messages_topic_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Identifier of the direct messages topic to which the messages will be sent; required if the messages are sent to a direct messages chat" + }, + { + "name": "FromChatID", + "json_name": "from_chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the chat where the original messages were sent (or username of the target bot, supergroup or channel in the format @username)" + }, + { + "name": "MessageIds", + "json_name": "message_ids", + "type": { + "kind": "array", + "elem_type": { + "kind": "primitive", + "name": "int64" + } + }, + "required": true, + "doc": "A JSON-serialized list of 1-100 identifiers of messages in the chat from_chat_id to copy. The identifiers must be specified in a strictly increasing order." + }, + { + "name": "DisableNotification", + "json_name": "disable_notification", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Sends the messages silently. Users will receive a notification with no sound." + }, + { + "name": "ProtectContent", + "json_name": "protect_content", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Protects the contents of the sent messages from forwarding and saving" + }, + { + "name": "RemoveCaption", + "json_name": "remove_caption", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True to copy the messages without their captions" + } + ], + "returns": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "MessageId" + } + } + }, + { + "name": "sendPhoto", + "doc": "Use this method to send photos. On success, the sent Message is returned.", + "params": [ + { + "name": "BusinessConnectionID", + "json_name": "business_connection_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Unique identifier of the business connection on behalf of which the message will be sent" + }, + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username" + }, + { + "name": "MessageThreadID", + "json_name": "message_thread_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only" + }, + { + "name": "DirectMessagesTopicID", + "json_name": "direct_messages_topic_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Identifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat" + }, + { + "name": "Photo", + "json_name": "photo", + "type": { + "kind": "oneOf", + "variants": [ + "InputFile", + "string" + ] + }, + "required": true, + "doc": "Photo to send. Pass a file_id as String to send a photo that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a photo from the Internet, or upload a new photo using multipart/form-data. The photo must be at most 10 MB in size. The photo's width and height must not exceed 10000 in total. Width and height ratio must be at most 20. More information on Sending Files »" + }, + { + "name": "Caption", + "json_name": "caption", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Photo caption (may also be used when resending photos by file_id), 0-1024 characters after entities parsing" + }, + { + "name": "ParseMode", + "json_name": "parse_mode", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Mode for parsing entities in the photo caption. See formatting options for more details." + }, + { + "name": "CaptionEntities", + "json_name": "caption_entities", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "MessageEntity" + } + }, + "doc": "A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode" + }, + { + "name": "ShowCaptionAboveMedia", + "json_name": "show_caption_above_media", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True, if the caption must be shown above the message media" + }, + { + "name": "HasSpoiler", + "json_name": "has_spoiler", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True if the photo needs to be covered with a spoiler animation" + }, + { + "name": "DisableNotification", + "json_name": "disable_notification", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Sends the message silently. Users will receive a notification with no sound." + }, + { + "name": "ProtectContent", + "json_name": "protect_content", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Protects the contents of the sent message from forwarding and saving" + }, + { + "name": "AllowPaidBroadcast", + "json_name": "allow_paid_broadcast", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance." + }, + { + "name": "MessageEffectID", + "json_name": "message_effect_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Unique identifier of the message effect to be added to the message; for private chats only" + }, + { + "name": "SuggestedPostParameters", + "json_name": "suggested_post_parameters", + "type": { + "kind": "named", + "name": "SuggestedPostParameters" + }, + "doc": "A JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined." + }, + { + "name": "ReplyParameters", + "json_name": "reply_parameters", + "type": { + "kind": "named", + "name": "ReplyParameters" + }, + "doc": "Description of the message to reply to" + }, + { + "name": "ReplyMarkup", + "json_name": "reply_markup", + "type": { + "kind": "oneOf", + "variants": [ + "InlineKeyboardMarkup", + "ReplyKeyboardMarkup", + "ReplyKeyboardRemove", + "ForceReply" + ] + }, + "doc": "Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user" + } + ], + "returns": { + "kind": "named", + "name": "Message" + }, + "has_files": true + }, + { + "name": "sendLivePhoto", + "doc": "Use this method to send live photos. On success, the sent Message is returned.", + "params": [ + { + "name": "BusinessConnectionID", + "json_name": "business_connection_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Unique identifier of the business connection on behalf of which the message will be sent" + }, + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the target chat or username of the target channel (in the format @channelusername)" + }, + { + "name": "MessageThreadID", + "json_name": "message_thread_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only" + }, + { + "name": "DirectMessagesTopicID", + "json_name": "direct_messages_topic_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Identifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat" + }, + { + "name": "LivePhoto", + "json_name": "live_photo", + "type": { + "kind": "oneOf", + "variants": [ + "InputFile", + "string" + ] + }, + "required": true, + "doc": "Live photo video to send. The video must be no longer than 10 seconds and must not exceed 10 MB in size. Pass a file_id as String to send a video that exists on the Telegram servers (recommended) or upload a new video using multipart/form-data. More information on Sending Files ». Sending live photos by a URL is currently unsupported." + }, + { + "name": "Photo", + "json_name": "photo", + "type": { + "kind": "oneOf", + "variants": [ + "InputFile", + "string" + ] + }, + "required": true, + "doc": "The static photo to send. Pass a file_id as String to send a photo that exists on the Telegram servers (recommended) or upload a new video using multipart/form-data. More information on Sending Files ». Sending live photos by a URL is currently unsupported." + }, + { + "name": "Caption", + "json_name": "caption", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Video caption (may also be used when resending videos by file_id), 0-1024 characters after entities parsing" + }, + { + "name": "ParseMode", + "json_name": "parse_mode", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Mode for parsing entities in the video caption. See formatting options for more details." + }, + { + "name": "CaptionEntities", + "json_name": "caption_entities", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "MessageEntity" + } + }, + "doc": "A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode" + }, + { + "name": "ShowCaptionAboveMedia", + "json_name": "show_caption_above_media", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True, if the caption must be shown above the message media" + }, + { + "name": "HasSpoiler", + "json_name": "has_spoiler", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True if the video needs to be covered with a spoiler animation" + }, + { + "name": "DisableNotification", + "json_name": "disable_notification", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Sends the message silently. Users will receive a notification with no sound." + }, + { + "name": "ProtectContent", + "json_name": "protect_content", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Protects the contents of the sent message from forwarding and saving" + }, + { + "name": "AllowPaidBroadcast", + "json_name": "allow_paid_broadcast", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance." + }, + { + "name": "MessageEffectID", + "json_name": "message_effect_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Unique identifier of the message effect to be added to the message; for private chats only" + }, + { + "name": "SuggestedPostParameters", + "json_name": "suggested_post_parameters", + "type": { + "kind": "named", + "name": "SuggestedPostParameters" + }, + "doc": "A JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined." + }, + { + "name": "ReplyParameters", + "json_name": "reply_parameters", + "type": { + "kind": "named", + "name": "ReplyParameters" + }, + "doc": "Description of the message to reply to" + }, + { + "name": "ReplyMarkup", + "json_name": "reply_markup", + "type": { + "kind": "oneOf", + "variants": [ + "InlineKeyboardMarkup", + "ReplyKeyboardMarkup", + "ReplyKeyboardRemove", + "ForceReply" + ] + }, + "doc": "Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user." + } + ], + "returns": { + "kind": "named", + "name": "Message" + }, + "has_files": true + }, + { + "name": "sendAudio", + "doc": "Use this method to send audio files, if you want Telegram clients to display them in the music player. Your audio must be in the .MP3 or .M4A format. On success, the sent Message is returned. Bots can currently send audio files of up to 50 MB in size, this limit may be changed in the future.\nFor sending voice messages, use the sendVoice method instead.", + "params": [ + { + "name": "BusinessConnectionID", + "json_name": "business_connection_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Unique identifier of the business connection on behalf of which the message will be sent" + }, + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username" + }, + { + "name": "MessageThreadID", + "json_name": "message_thread_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only" + }, + { + "name": "DirectMessagesTopicID", + "json_name": "direct_messages_topic_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Identifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat" + }, + { + "name": "Audio", + "json_name": "audio", + "type": { + "kind": "oneOf", + "variants": [ + "InputFile", + "string" + ] + }, + "required": true, + "doc": "Audio file to send. Pass a file_id as String to send an audio file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an audio file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files »" + }, + { + "name": "Caption", + "json_name": "caption", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Audio caption, 0-1024 characters after entities parsing" + }, + { + "name": "ParseMode", + "json_name": "parse_mode", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Mode for parsing entities in the audio caption. See formatting options for more details." + }, + { + "name": "CaptionEntities", + "json_name": "caption_entities", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "MessageEntity" + } + }, + "doc": "A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode" + }, + { + "name": "Duration", + "json_name": "duration", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Duration of the audio in seconds" + }, + { + "name": "Performer", + "json_name": "performer", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Performer" + }, + { + "name": "Title", + "json_name": "title", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Track name" + }, + { + "name": "Thumbnail", + "json_name": "thumbnail", + "type": { + "kind": "oneOf", + "variants": [ + "InputFile", + "string" + ] + }, + "doc": "Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://” if the thumbnail was uploaded using multipart/form-data under . More information on Sending Files »" + }, + { + "name": "DisableNotification", + "json_name": "disable_notification", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Sends the message silently. Users will receive a notification with no sound." + }, + { + "name": "ProtectContent", + "json_name": "protect_content", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Protects the contents of the sent message from forwarding and saving" + }, + { + "name": "AllowPaidBroadcast", + "json_name": "allow_paid_broadcast", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance." + }, + { + "name": "MessageEffectID", + "json_name": "message_effect_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Unique identifier of the message effect to be added to the message; for private chats only" + }, + { + "name": "SuggestedPostParameters", + "json_name": "suggested_post_parameters", + "type": { + "kind": "named", + "name": "SuggestedPostParameters" + }, + "doc": "A JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined." + }, + { + "name": "ReplyParameters", + "json_name": "reply_parameters", + "type": { + "kind": "named", + "name": "ReplyParameters" + }, + "doc": "Description of the message to reply to" + }, + { + "name": "ReplyMarkup", + "json_name": "reply_markup", + "type": { + "kind": "oneOf", + "variants": [ + "InlineKeyboardMarkup", + "ReplyKeyboardMarkup", + "ReplyKeyboardRemove", + "ForceReply" + ] + }, + "doc": "Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user" + } + ], + "returns": { + "kind": "named", + "name": "Message" + }, + "has_files": true + }, + { + "name": "sendDocument", + "doc": "Use this method to send general files. On success, the sent Message is returned. Bots can currently send files of any type of up to 50 MB in size, this limit may be changed in the future.", + "params": [ + { + "name": "BusinessConnectionID", + "json_name": "business_connection_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Unique identifier of the business connection on behalf of which the message will be sent" + }, + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username" + }, + { + "name": "MessageThreadID", + "json_name": "message_thread_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only" + }, + { + "name": "DirectMessagesTopicID", + "json_name": "direct_messages_topic_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Identifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat" + }, + { + "name": "Document", + "json_name": "document", + "type": { + "kind": "oneOf", + "variants": [ + "InputFile", + "string" + ] + }, + "required": true, + "doc": "File to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files »" + }, + { + "name": "Thumbnail", + "json_name": "thumbnail", + "type": { + "kind": "oneOf", + "variants": [ + "InputFile", + "string" + ] + }, + "doc": "Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://” if the thumbnail was uploaded using multipart/form-data under . More information on Sending Files »" + }, + { + "name": "Caption", + "json_name": "caption", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Document caption (may also be used when resending documents by file_id), 0-1024 characters after entities parsing" + }, + { + "name": "ParseMode", + "json_name": "parse_mode", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Mode for parsing entities in the document caption. See formatting options for more details." + }, + { + "name": "CaptionEntities", + "json_name": "caption_entities", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "MessageEntity" + } + }, + "doc": "A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode" + }, + { + "name": "DisableContentTypeDetection", + "json_name": "disable_content_type_detection", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Disables automatic server-side content type detection for files uploaded using multipart/form-data" + }, + { + "name": "DisableNotification", + "json_name": "disable_notification", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Sends the message silently. Users will receive a notification with no sound." + }, + { + "name": "ProtectContent", + "json_name": "protect_content", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Protects the contents of the sent message from forwarding and saving" + }, + { + "name": "AllowPaidBroadcast", + "json_name": "allow_paid_broadcast", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance." + }, + { + "name": "MessageEffectID", + "json_name": "message_effect_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Unique identifier of the message effect to be added to the message; for private chats only" + }, + { + "name": "SuggestedPostParameters", + "json_name": "suggested_post_parameters", + "type": { + "kind": "named", + "name": "SuggestedPostParameters" + }, + "doc": "A JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined." + }, + { + "name": "ReplyParameters", + "json_name": "reply_parameters", + "type": { + "kind": "named", + "name": "ReplyParameters" + }, + "doc": "Description of the message to reply to" + }, + { + "name": "ReplyMarkup", + "json_name": "reply_markup", + "type": { + "kind": "oneOf", + "variants": [ + "InlineKeyboardMarkup", + "ReplyKeyboardMarkup", + "ReplyKeyboardRemove", + "ForceReply" + ] + }, + "doc": "Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user" + } + ], + "returns": { + "kind": "named", + "name": "Message" + }, + "has_files": true + }, + { + "name": "sendVideo", + "doc": "Use this method to send video files, Telegram clients support MPEG4 videos (other formats may be sent as Document). On success, the sent Message is returned. Bots can currently send video files of up to 50 MB in size, this limit may be changed in the future.", + "params": [ + { + "name": "BusinessConnectionID", + "json_name": "business_connection_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Unique identifier of the business connection on behalf of which the message will be sent" + }, + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username" + }, + { + "name": "MessageThreadID", + "json_name": "message_thread_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only" + }, + { + "name": "DirectMessagesTopicID", + "json_name": "direct_messages_topic_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Identifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat" + }, + { + "name": "Video", + "json_name": "video", + "type": { + "kind": "oneOf", + "variants": [ + "InputFile", + "string" + ] + }, + "required": true, + "doc": "Video to send. Pass a file_id as String to send a video that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a video from the Internet, or upload a new video using multipart/form-data. More information on Sending Files »" + }, + { + "name": "Duration", + "json_name": "duration", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Duration of sent video in seconds" + }, + { + "name": "Width", + "json_name": "width", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Video width" + }, + { + "name": "Height", + "json_name": "height", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Video height" + }, + { + "name": "Thumbnail", + "json_name": "thumbnail", + "type": { + "kind": "oneOf", + "variants": [ + "InputFile", + "string" + ] + }, + "doc": "Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://” if the thumbnail was uploaded using multipart/form-data under . More information on Sending Files »" + }, + { + "name": "Cover", + "json_name": "cover", + "type": { + "kind": "oneOf", + "variants": [ + "InputFile", + "string" + ] + }, + "doc": "Cover for the video in the message. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet, or pass “attach://” to upload a new one using multipart/form-data under name. More information on Sending Files »" + }, + { + "name": "StartTimestamp", + "json_name": "start_timestamp", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Start timestamp for the video in the message" + }, + { + "name": "Caption", + "json_name": "caption", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Video caption (may also be used when resending videos by file_id), 0-1024 characters after entities parsing" + }, + { + "name": "ParseMode", + "json_name": "parse_mode", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Mode for parsing entities in the video caption. See formatting options for more details." + }, + { + "name": "CaptionEntities", + "json_name": "caption_entities", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "MessageEntity" + } + }, + "doc": "A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode" + }, + { + "name": "ShowCaptionAboveMedia", + "json_name": "show_caption_above_media", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True, if the caption must be shown above the message media" + }, + { + "name": "HasSpoiler", + "json_name": "has_spoiler", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True if the video needs to be covered with a spoiler animation" + }, + { + "name": "SupportsStreaming", + "json_name": "supports_streaming", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True if the uploaded video is suitable for streaming" + }, + { + "name": "DisableNotification", + "json_name": "disable_notification", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Sends the message silently. Users will receive a notification with no sound." + }, + { + "name": "ProtectContent", + "json_name": "protect_content", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Protects the contents of the sent message from forwarding and saving" + }, + { + "name": "AllowPaidBroadcast", + "json_name": "allow_paid_broadcast", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance." + }, + { + "name": "MessageEffectID", + "json_name": "message_effect_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Unique identifier of the message effect to be added to the message; for private chats only" + }, + { + "name": "SuggestedPostParameters", + "json_name": "suggested_post_parameters", + "type": { + "kind": "named", + "name": "SuggestedPostParameters" + }, + "doc": "A JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined." + }, + { + "name": "ReplyParameters", + "json_name": "reply_parameters", + "type": { + "kind": "named", + "name": "ReplyParameters" + }, + "doc": "Description of the message to reply to" + }, + { + "name": "ReplyMarkup", + "json_name": "reply_markup", + "type": { + "kind": "oneOf", + "variants": [ + "InlineKeyboardMarkup", + "ReplyKeyboardMarkup", + "ReplyKeyboardRemove", + "ForceReply" + ] + }, + "doc": "Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user" + } + ], + "returns": { + "kind": "named", + "name": "Message" + }, + "has_files": true + }, + { + "name": "sendAnimation", + "doc": "Use this method to send animation files (GIF or H.264/MPEG-4 AVC video without sound). On success, the sent Message is returned. Bots can currently send animation files of up to 50 MB in size, this limit may be changed in the future.", + "params": [ + { + "name": "BusinessConnectionID", + "json_name": "business_connection_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Unique identifier of the business connection on behalf of which the message will be sent" + }, + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username" + }, + { + "name": "MessageThreadID", + "json_name": "message_thread_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only" + }, + { + "name": "DirectMessagesTopicID", + "json_name": "direct_messages_topic_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Identifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat" + }, + { + "name": "Animation", + "json_name": "animation", + "type": { + "kind": "oneOf", + "variants": [ + "InputFile", + "string" + ] + }, + "required": true, + "doc": "Animation to send. Pass a file_id as String to send an animation that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an animation from the Internet, or upload a new animation using multipart/form-data. More information on Sending Files »" + }, + { + "name": "Duration", + "json_name": "duration", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Duration of sent animation in seconds" + }, + { + "name": "Width", + "json_name": "width", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Animation width" + }, + { + "name": "Height", + "json_name": "height", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Animation height" + }, + { + "name": "Thumbnail", + "json_name": "thumbnail", + "type": { + "kind": "oneOf", + "variants": [ + "InputFile", + "string" + ] + }, + "doc": "Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://” if the thumbnail was uploaded using multipart/form-data under . More information on Sending Files »" + }, + { + "name": "Caption", + "json_name": "caption", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Animation caption (may also be used when resending animation by file_id), 0-1024 characters after entities parsing" + }, + { + "name": "ParseMode", + "json_name": "parse_mode", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Mode for parsing entities in the animation caption. See formatting options for more details." + }, + { + "name": "CaptionEntities", + "json_name": "caption_entities", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "MessageEntity" + } + }, + "doc": "A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode" + }, + { + "name": "ShowCaptionAboveMedia", + "json_name": "show_caption_above_media", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True, if the caption must be shown above the message media" + }, + { + "name": "HasSpoiler", + "json_name": "has_spoiler", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True if the animation needs to be covered with a spoiler animation" + }, + { + "name": "DisableNotification", + "json_name": "disable_notification", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Sends the message silently. Users will receive a notification with no sound." + }, + { + "name": "ProtectContent", + "json_name": "protect_content", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Protects the contents of the sent message from forwarding and saving" + }, + { + "name": "AllowPaidBroadcast", + "json_name": "allow_paid_broadcast", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance." + }, + { + "name": "MessageEffectID", + "json_name": "message_effect_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Unique identifier of the message effect to be added to the message; for private chats only" + }, + { + "name": "SuggestedPostParameters", + "json_name": "suggested_post_parameters", + "type": { + "kind": "named", + "name": "SuggestedPostParameters" + }, + "doc": "A JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined." + }, + { + "name": "ReplyParameters", + "json_name": "reply_parameters", + "type": { + "kind": "named", + "name": "ReplyParameters" + }, + "doc": "Description of the message to reply to" + }, + { + "name": "ReplyMarkup", + "json_name": "reply_markup", + "type": { + "kind": "oneOf", + "variants": [ + "InlineKeyboardMarkup", + "ReplyKeyboardMarkup", + "ReplyKeyboardRemove", + "ForceReply" + ] + }, + "doc": "Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user" + } + ], + "returns": { + "kind": "named", + "name": "Message" + }, + "has_files": true + }, + { + "name": "sendVoice", + "doc": "Use this method to send audio files, if you want Telegram clients to display the file as a playable voice message. For this to work, your audio must be in an .OGG file encoded with OPUS, or in .MP3 format, or in .M4A format (other formats may be sent as Audio or Document). On success, the sent Message is returned. Bots can currently send voice messages of up to 50 MB in size, this limit may be changed in the future.", + "params": [ + { + "name": "BusinessConnectionID", + "json_name": "business_connection_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Unique identifier of the business connection on behalf of which the message will be sent" + }, + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username" + }, + { + "name": "MessageThreadID", + "json_name": "message_thread_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only" + }, + { + "name": "DirectMessagesTopicID", + "json_name": "direct_messages_topic_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Identifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat" + }, + { + "name": "Voice", + "json_name": "voice", + "type": { + "kind": "oneOf", + "variants": [ + "InputFile", + "string" + ] + }, + "required": true, + "doc": "Audio file to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files »" + }, + { + "name": "Caption", + "json_name": "caption", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Voice message caption, 0-1024 characters after entities parsing" + }, + { + "name": "ParseMode", + "json_name": "parse_mode", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Mode for parsing entities in the voice message caption. See formatting options for more details." + }, + { + "name": "CaptionEntities", + "json_name": "caption_entities", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "MessageEntity" + } + }, + "doc": "A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode" + }, + { + "name": "Duration", + "json_name": "duration", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Duration of the voice message in seconds" + }, + { + "name": "DisableNotification", + "json_name": "disable_notification", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Sends the message silently. Users will receive a notification with no sound." + }, + { + "name": "ProtectContent", + "json_name": "protect_content", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Protects the contents of the sent message from forwarding and saving" + }, + { + "name": "AllowPaidBroadcast", + "json_name": "allow_paid_broadcast", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance." + }, + { + "name": "MessageEffectID", + "json_name": "message_effect_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Unique identifier of the message effect to be added to the message; for private chats only" + }, + { + "name": "SuggestedPostParameters", + "json_name": "suggested_post_parameters", + "type": { + "kind": "named", + "name": "SuggestedPostParameters" + }, + "doc": "A JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined." + }, + { + "name": "ReplyParameters", + "json_name": "reply_parameters", + "type": { + "kind": "named", + "name": "ReplyParameters" + }, + "doc": "Description of the message to reply to" + }, + { + "name": "ReplyMarkup", + "json_name": "reply_markup", + "type": { + "kind": "oneOf", + "variants": [ + "InlineKeyboardMarkup", + "ReplyKeyboardMarkup", + "ReplyKeyboardRemove", + "ForceReply" + ] + }, + "doc": "Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user" + } + ], + "returns": { + "kind": "named", + "name": "Message" + }, + "has_files": true + }, + { + "name": "sendVideoNote", + "doc": "As of v.4.0, Telegram clients support rounded square MPEG4 videos of up to 1 minute long. Use this method to send video messages. On success, the sent Message is returned.", + "params": [ + { + "name": "BusinessConnectionID", + "json_name": "business_connection_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Unique identifier of the business connection on behalf of which the message will be sent" + }, + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username" + }, + { + "name": "MessageThreadID", + "json_name": "message_thread_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only" + }, + { + "name": "DirectMessagesTopicID", + "json_name": "direct_messages_topic_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Identifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat" + }, + { + "name": "VideoNote", + "json_name": "video_note", + "type": { + "kind": "oneOf", + "variants": [ + "InputFile", + "string" + ] + }, + "required": true, + "doc": "Video note to send. Pass a file_id as String to send a video note that exists on the Telegram servers (recommended) or upload a new video using multipart/form-data. More information on Sending Files ». Sending video notes by a URL is currently unsupported" + }, + { + "name": "Duration", + "json_name": "duration", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Duration of sent video in seconds" + }, + { + "name": "Length", + "json_name": "length", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Video width and height, i.e. diameter of the video message" + }, + { + "name": "Thumbnail", + "json_name": "thumbnail", + "type": { + "kind": "oneOf", + "variants": [ + "InputFile", + "string" + ] + }, + "doc": "Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://” if the thumbnail was uploaded using multipart/form-data under . More information on Sending Files »" + }, + { + "name": "DisableNotification", + "json_name": "disable_notification", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Sends the message silently. Users will receive a notification with no sound." + }, + { + "name": "ProtectContent", + "json_name": "protect_content", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Protects the contents of the sent message from forwarding and saving" + }, + { + "name": "AllowPaidBroadcast", + "json_name": "allow_paid_broadcast", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance." + }, + { + "name": "MessageEffectID", + "json_name": "message_effect_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Unique identifier of the message effect to be added to the message; for private chats only" + }, + { + "name": "SuggestedPostParameters", + "json_name": "suggested_post_parameters", + "type": { + "kind": "named", + "name": "SuggestedPostParameters" + }, + "doc": "A JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined." + }, + { + "name": "ReplyParameters", + "json_name": "reply_parameters", + "type": { + "kind": "named", + "name": "ReplyParameters" + }, + "doc": "Description of the message to reply to" + }, + { + "name": "ReplyMarkup", + "json_name": "reply_markup", + "type": { + "kind": "oneOf", + "variants": [ + "InlineKeyboardMarkup", + "ReplyKeyboardMarkup", + "ReplyKeyboardRemove", + "ForceReply" + ] + }, + "doc": "Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user" + } + ], + "returns": { + "kind": "named", + "name": "Message" + }, + "has_files": true + }, + { + "name": "sendPaidMedia", + "doc": "Use this method to send paid media. On success, the sent Message is returned.", + "params": [ + { + "name": "BusinessConnectionID", + "json_name": "business_connection_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Unique identifier of the business connection on behalf of which the message will be sent" + }, + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username. If the chat is a channel, all Telegram Star proceeds from this media will be credited to the chat's balance. Otherwise, they will be credited to the bot's balance." + }, + { + "name": "MessageThreadID", + "json_name": "message_thread_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only" + }, + { + "name": "DirectMessagesTopicID", + "json_name": "direct_messages_topic_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Identifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat" + }, + { + "name": "StarCount", + "json_name": "star_count", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "The number of Telegram Stars that must be paid to buy access to the media; 1-25000" + }, + { + "name": "Media", + "json_name": "media", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "InputPaidMedia" + } + }, + "required": true, + "doc": "A JSON-serialized array describing the media to be sent; up to 10 items" + }, + { + "name": "Payload", + "json_name": "payload", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Bot-defined paid media payload, 0-128 bytes. This will not be displayed to the user, use it for your internal processes." + }, + { + "name": "Caption", + "json_name": "caption", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Media caption, 0-1024 characters after entities parsing" + }, + { + "name": "ParseMode", + "json_name": "parse_mode", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Mode for parsing entities in the media caption. See formatting options for more details." + }, + { + "name": "CaptionEntities", + "json_name": "caption_entities", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "MessageEntity" + } + }, + "doc": "A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode" + }, + { + "name": "ShowCaptionAboveMedia", + "json_name": "show_caption_above_media", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True, if the caption must be shown above the message media" + }, + { + "name": "DisableNotification", + "json_name": "disable_notification", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Sends the message silently. Users will receive a notification with no sound." + }, + { + "name": "ProtectContent", + "json_name": "protect_content", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Protects the contents of the sent message from forwarding and saving" + }, + { + "name": "AllowPaidBroadcast", + "json_name": "allow_paid_broadcast", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance." + }, + { + "name": "SuggestedPostParameters", + "json_name": "suggested_post_parameters", + "type": { + "kind": "named", + "name": "SuggestedPostParameters" + }, + "doc": "A JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined." + }, + { + "name": "ReplyParameters", + "json_name": "reply_parameters", + "type": { + "kind": "named", + "name": "ReplyParameters" + }, + "doc": "Description of the message to reply to" + }, + { + "name": "ReplyMarkup", + "json_name": "reply_markup", + "type": { + "kind": "oneOf", + "variants": [ + "InlineKeyboardMarkup", + "ReplyKeyboardMarkup", + "ReplyKeyboardRemove", + "ForceReply" + ] + }, + "doc": "Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user" + } + ], + "returns": { + "kind": "named", + "name": "Message" + }, + "has_files": true + }, + { + "name": "sendMediaGroup", + "doc": "Use this method to send a group of photos, live photos, videos, documents or audios as an album. Documents and audio files can be only grouped in an album with messages of the same type. On success, an array of Message objects that were sent is returned.", + "params": [ + { + "name": "BusinessConnectionID", + "json_name": "business_connection_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Unique identifier of the business connection on behalf of which the message will be sent" + }, + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username" + }, + { + "name": "MessageThreadID", + "json_name": "message_thread_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only" + }, + { + "name": "DirectMessagesTopicID", + "json_name": "direct_messages_topic_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Identifier of the direct messages topic to which the messages will be sent; required if the messages are sent to a direct messages chat" + }, + { + "name": "Media", + "json_name": "media", + "type": { + "kind": "array", + "elem_type": { + "kind": "oneOf", + "variants": [ + "InputMediaAudio", + "InputMediaDocument", + "InputMediaLivePhoto", + "InputMediaPhoto", + "InputMediaVideo" + ] + } + }, + "required": true, + "doc": "A JSON-serialized array describing messages to be sent, must include 2-10 items" + }, + { + "name": "DisableNotification", + "json_name": "disable_notification", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Sends messages silently. Users will receive a notification with no sound." + }, + { + "name": "ProtectContent", + "json_name": "protect_content", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Protects the contents of the sent messages from forwarding and saving" + }, + { + "name": "AllowPaidBroadcast", + "json_name": "allow_paid_broadcast", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance." + }, + { + "name": "MessageEffectID", + "json_name": "message_effect_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Unique identifier of the message effect to be added to the message; for private chats only" + }, + { + "name": "ReplyParameters", + "json_name": "reply_parameters", + "type": { + "kind": "named", + "name": "ReplyParameters" + }, + "doc": "Description of the message to reply to" + } + ], + "returns": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "Message" + } + }, + "has_files": true + }, + { + "name": "sendLocation", + "doc": "Use this method to send point on the map. On success, the sent Message is returned.", + "params": [ + { + "name": "BusinessConnectionID", + "json_name": "business_connection_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Unique identifier of the business connection on behalf of which the message will be sent" + }, + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username" + }, + { + "name": "MessageThreadID", + "json_name": "message_thread_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only" + }, + { + "name": "DirectMessagesTopicID", + "json_name": "direct_messages_topic_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Identifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat" + }, + { + "name": "Latitude", + "json_name": "latitude", + "type": { + "kind": "primitive", + "name": "float64" + }, + "required": true, + "doc": "Latitude of the location" + }, + { + "name": "Longitude", + "json_name": "longitude", + "type": { + "kind": "primitive", + "name": "float64" + }, + "required": true, + "doc": "Longitude of the location" + }, + { + "name": "HorizontalAccuracy", + "json_name": "horizontal_accuracy", + "type": { + "kind": "primitive", + "name": "float64" + }, + "doc": "The radius of uncertainty for the location, measured in meters; 0-1500" + }, + { + "name": "LivePeriod", + "json_name": "live_period", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Period in seconds during which the location will be updated (see Live Locations, should be between 60 and 86400, or 0x7FFFFFFF for live locations that can be edited indefinitely." + }, + { + "name": "Heading", + "json_name": "heading", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "For live locations, a direction in which the user is moving, in degrees. Must be between 1 and 360 if specified." + }, + { + "name": "ProximityAlertRadius", + "json_name": "proximity_alert_radius", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "For live locations, a maximum distance for proximity alerts about approaching another chat member, in meters. Must be between 1 and 100000 if specified." + }, + { + "name": "DisableNotification", + "json_name": "disable_notification", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Sends the message silently. Users will receive a notification with no sound." + }, + { + "name": "ProtectContent", + "json_name": "protect_content", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Protects the contents of the sent message from forwarding and saving" + }, + { + "name": "AllowPaidBroadcast", + "json_name": "allow_paid_broadcast", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance." + }, + { + "name": "MessageEffectID", + "json_name": "message_effect_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Unique identifier of the message effect to be added to the message; for private chats only" + }, + { + "name": "SuggestedPostParameters", + "json_name": "suggested_post_parameters", + "type": { + "kind": "named", + "name": "SuggestedPostParameters" + }, + "doc": "A JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined." + }, + { + "name": "ReplyParameters", + "json_name": "reply_parameters", + "type": { + "kind": "named", + "name": "ReplyParameters" + }, + "doc": "Description of the message to reply to" + }, + { + "name": "ReplyMarkup", + "json_name": "reply_markup", + "type": { + "kind": "oneOf", + "variants": [ + "InlineKeyboardMarkup", + "ReplyKeyboardMarkup", + "ReplyKeyboardRemove", + "ForceReply" + ] + }, + "doc": "Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user" + } + ], + "returns": { + "kind": "named", + "name": "Message" + } + }, + { + "name": "sendVenue", + "doc": "Use this method to send information about a venue. On success, the sent Message is returned.", + "params": [ + { + "name": "BusinessConnectionID", + "json_name": "business_connection_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Unique identifier of the business connection on behalf of which the message will be sent" + }, + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username" + }, + { + "name": "MessageThreadID", + "json_name": "message_thread_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only" + }, + { + "name": "DirectMessagesTopicID", + "json_name": "direct_messages_topic_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Identifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat" + }, + { + "name": "Latitude", + "json_name": "latitude", + "type": { + "kind": "primitive", + "name": "float64" + }, + "required": true, + "doc": "Latitude of the venue" + }, + { + "name": "Longitude", + "json_name": "longitude", + "type": { + "kind": "primitive", + "name": "float64" + }, + "required": true, + "doc": "Longitude of the venue" + }, + { + "name": "Title", + "json_name": "title", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Name of the venue" + }, + { + "name": "Address", + "json_name": "address", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Address of the venue" + }, + { + "name": "FoursquareID", + "json_name": "foursquare_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Foursquare identifier of the venue" + }, + { + "name": "FoursquareType", + "json_name": "foursquare_type", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Foursquare type of the venue, if known. (For example, “arts_entertainment/default”, “arts_entertainment/aquarium” or “food/icecream”.)" + }, + { + "name": "GooglePlaceID", + "json_name": "google_place_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Google Places identifier of the venue" + }, + { + "name": "GooglePlaceType", + "json_name": "google_place_type", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Google Places type of the venue. (See supported types.)" + }, + { + "name": "DisableNotification", + "json_name": "disable_notification", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Sends the message silently. Users will receive a notification with no sound." + }, + { + "name": "ProtectContent", + "json_name": "protect_content", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Protects the contents of the sent message from forwarding and saving" + }, + { + "name": "AllowPaidBroadcast", + "json_name": "allow_paid_broadcast", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance." + }, + { + "name": "MessageEffectID", + "json_name": "message_effect_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Unique identifier of the message effect to be added to the message; for private chats only" + }, + { + "name": "SuggestedPostParameters", + "json_name": "suggested_post_parameters", + "type": { + "kind": "named", + "name": "SuggestedPostParameters" + }, + "doc": "A JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined." + }, + { + "name": "ReplyParameters", + "json_name": "reply_parameters", + "type": { + "kind": "named", + "name": "ReplyParameters" + }, + "doc": "Description of the message to reply to" + }, + { + "name": "ReplyMarkup", + "json_name": "reply_markup", + "type": { + "kind": "oneOf", + "variants": [ + "InlineKeyboardMarkup", + "ReplyKeyboardMarkup", + "ReplyKeyboardRemove", + "ForceReply" + ] + }, + "doc": "Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user" + } + ], + "returns": { + "kind": "named", + "name": "Message" + } + }, + { + "name": "sendContact", + "doc": "Use this method to send phone contacts. On success, the sent Message is returned.", + "params": [ + { + "name": "BusinessConnectionID", + "json_name": "business_connection_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Unique identifier of the business connection on behalf of which the message will be sent" + }, + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username" + }, + { + "name": "MessageThreadID", + "json_name": "message_thread_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only" + }, + { + "name": "DirectMessagesTopicID", + "json_name": "direct_messages_topic_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Identifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat" + }, + { + "name": "PhoneNumber", + "json_name": "phone_number", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Contact's phone number" + }, + { + "name": "FirstName", + "json_name": "first_name", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Contact's first name" + }, + { + "name": "LastName", + "json_name": "last_name", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Contact's last name" + }, + { + "name": "Vcard", + "json_name": "vcard", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Additional data about the contact in the form of a vCard, 0-2048 bytes" + }, + { + "name": "DisableNotification", + "json_name": "disable_notification", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Sends the message silently. Users will receive a notification with no sound." + }, + { + "name": "ProtectContent", + "json_name": "protect_content", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Protects the contents of the sent message from forwarding and saving" + }, + { + "name": "AllowPaidBroadcast", + "json_name": "allow_paid_broadcast", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance." + }, + { + "name": "MessageEffectID", + "json_name": "message_effect_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Unique identifier of the message effect to be added to the message; for private chats only" + }, + { + "name": "SuggestedPostParameters", + "json_name": "suggested_post_parameters", + "type": { + "kind": "named", + "name": "SuggestedPostParameters" + }, + "doc": "A JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined." + }, + { + "name": "ReplyParameters", + "json_name": "reply_parameters", + "type": { + "kind": "named", + "name": "ReplyParameters" + }, + "doc": "Description of the message to reply to" + }, + { + "name": "ReplyMarkup", + "json_name": "reply_markup", + "type": { + "kind": "oneOf", + "variants": [ + "InlineKeyboardMarkup", + "ReplyKeyboardMarkup", + "ReplyKeyboardRemove", + "ForceReply" + ] + }, + "doc": "Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user" + } + ], + "returns": { + "kind": "named", + "name": "Message" + } + }, + { + "name": "sendPoll", + "doc": "Use this method to send a native poll. On success, the sent Message is returned.", + "params": [ + { + "name": "BusinessConnectionID", + "json_name": "business_connection_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Unique identifier of the business connection on behalf of which the message will be sent" + }, + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username. Polls can't be sent to channel direct messages chats." + }, + { + "name": "MessageThreadID", + "json_name": "message_thread_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only" + }, + { + "name": "Question", + "json_name": "question", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Poll question, 1-300 characters" + }, + { + "name": "QuestionParseMode", + "json_name": "question_parse_mode", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Mode for parsing entities in the question. See formatting options for more details. Currently, only custom emoji entities are allowed" + }, + { + "name": "QuestionEntities", + "json_name": "question_entities", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "MessageEntity" + } + }, + "doc": "A JSON-serialized list of special entities that appear in the poll question. It can be specified instead of question_parse_mode" + }, + { + "name": "Options", + "json_name": "options", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "InputPollOption" + } + }, + "required": true, + "doc": "A JSON-serialized list of 1-12 answer options" + }, + { + "name": "IsAnonymous", + "json_name": "is_anonymous", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "True, if the poll needs to be anonymous, defaults to True" + }, + { + "name": "Type", + "json_name": "type", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Poll type, “quiz” or “regular”, defaults to “regular”" + }, + { + "name": "AllowsMultipleAnswers", + "json_name": "allows_multiple_answers", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True, if the poll allows multiple answers, defaults to False" + }, + { + "name": "AllowsRevoting", + "json_name": "allows_revoting", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True, if the poll allows to change chosen answer options, defaults to False for quizzes and to True for regular polls" + }, + { + "name": "ShuffleOptions", + "json_name": "shuffle_options", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True, if the poll options must be shown in random order" + }, + { + "name": "AllowAddingOptions", + "json_name": "allow_adding_options", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True, if answer options can be added to the poll after creation; not supported for anonymous polls and quizzes" + }, + { + "name": "HideResultsUntilCloses", + "json_name": "hide_results_until_closes", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True, if poll results must be shown only after the poll closes" + }, + { + "name": "MembersOnly", + "json_name": "members_only", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True, if voting is limited to users who have been members of the chat where the poll is being sent for more than 24 hours; for channel chats only" + }, + { + "name": "CountryCodes", + "json_name": "country_codes", + "type": { + "kind": "array", + "elem_type": { + "kind": "primitive", + "name": "string" + } + }, + "doc": "A JSON-serialized list of 0-12 two-letter ISO 3166-1 alpha-2 country codes indicating the countries from which users can vote in the poll; for channel chats only. If omitted or empty, then users from any country can participate in the poll." + }, + { + "name": "CorrectOptionIds", + "json_name": "correct_option_ids", + "type": { + "kind": "array", + "elem_type": { + "kind": "primitive", + "name": "int64" + } + }, + "doc": "A JSON-serialized list of monotonically increasing 0-based identifiers of the correct answer options, required for polls in quiz mode" + }, + { + "name": "Explanation", + "json_name": "explanation", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Text that is shown when a user chooses an incorrect answer or taps on the lamp icon in a quiz-style poll, 0-200 characters with at most 2 line feeds after entities parsing" + }, + { + "name": "ExplanationParseMode", + "json_name": "explanation_parse_mode", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Mode for parsing entities in the explanation. See formatting options for more details." + }, + { + "name": "ExplanationEntities", + "json_name": "explanation_entities", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "MessageEntity" + } + }, + "doc": "A JSON-serialized list of special entities that appear in the poll explanation. It can be specified instead of explanation_parse_mode" + }, + { + "name": "ExplanationMedia", + "json_name": "explanation_media", + "type": { + "kind": "named", + "name": "InputPollMedia" + }, + "doc": "Media added to the quiz explanation" + }, + { + "name": "OpenPeriod", + "json_name": "open_period", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Amount of time in seconds the poll will be active after creation, 5-2628000. Can't be used together with close_date." + }, + { + "name": "CloseDate", + "json_name": "close_date", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Point in time (Unix timestamp) when the poll will be automatically closed. Must be at least 5 and no more than 2628000 seconds in the future. Can't be used together with open_period." + }, + { + "name": "IsClosed", + "json_name": "is_closed", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True if the poll needs to be immediately closed. This can be useful for poll preview." + }, + { + "name": "Description", + "json_name": "description", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Description of the poll to be sent, 0-1024 characters after entities parsing" + }, + { + "name": "DescriptionParseMode", + "json_name": "description_parse_mode", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Mode for parsing entities in the poll description. See formatting options for more details." + }, + { + "name": "DescriptionEntities", + "json_name": "description_entities", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "MessageEntity" + } + }, + "doc": "A JSON-serialized list of special entities that appear in the poll description, which can be specified instead of description_parse_mode" + }, + { + "name": "Media", + "json_name": "media", + "type": { + "kind": "named", + "name": "InputPollMedia" + }, + "doc": "Media added to the poll description" + }, + { + "name": "DisableNotification", + "json_name": "disable_notification", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Sends the message silently. Users will receive a notification with no sound." + }, + { + "name": "ProtectContent", + "json_name": "protect_content", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Protects the contents of the sent message from forwarding and saving" + }, + { + "name": "AllowPaidBroadcast", + "json_name": "allow_paid_broadcast", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance." + }, + { + "name": "MessageEffectID", + "json_name": "message_effect_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Unique identifier of the message effect to be added to the message; for private chats only" + }, + { + "name": "ReplyParameters", + "json_name": "reply_parameters", + "type": { + "kind": "named", + "name": "ReplyParameters" + }, + "doc": "Description of the message to reply to" + }, + { + "name": "ReplyMarkup", + "json_name": "reply_markup", + "type": { + "kind": "oneOf", + "variants": [ + "InlineKeyboardMarkup", + "ReplyKeyboardMarkup", + "ReplyKeyboardRemove", + "ForceReply" + ] + }, + "doc": "Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user" + } + ], + "returns": { + "kind": "named", + "name": "Message" + } + }, + { + "name": "sendChecklist", + "doc": "Use this method to send a checklist on behalf of a connected business account. On success, the sent Message is returned.", + "params": [ + { + "name": "BusinessConnectionID", + "json_name": "business_connection_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique identifier of the business connection on behalf of which the message will be sent" + }, + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the target chat or username of the target bot in the format @username" + }, + { + "name": "Checklist", + "json_name": "checklist", + "type": { + "kind": "named", + "name": "InputChecklist" + }, + "required": true, + "doc": "A JSON-serialized object for the checklist to send" + }, + { + "name": "DisableNotification", + "json_name": "disable_notification", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Sends the message silently. Users will receive a notification with no sound." + }, + { + "name": "ProtectContent", + "json_name": "protect_content", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Protects the contents of the sent message from forwarding and saving" + }, + { + "name": "MessageEffectID", + "json_name": "message_effect_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Unique identifier of the message effect to be added to the message" + }, + { + "name": "ReplyParameters", + "json_name": "reply_parameters", + "type": { + "kind": "named", + "name": "ReplyParameters" + }, + "doc": "A JSON-serialized object for description of the message to reply to" + }, + { + "name": "ReplyMarkup", + "json_name": "reply_markup", + "type": { + "kind": "named", + "name": "InlineKeyboardMarkup" + }, + "doc": "A JSON-serialized object for an inline keyboard" + } + ], + "returns": { + "kind": "named", + "name": "Message" + } + }, + { + "name": "sendDice", + "doc": "Use this method to send an animated emoji that will display a random value. On success, the sent Message is returned.", + "params": [ + { + "name": "BusinessConnectionID", + "json_name": "business_connection_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Unique identifier of the business connection on behalf of which the message will be sent" + }, + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username" + }, + { + "name": "MessageThreadID", + "json_name": "message_thread_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only" + }, + { + "name": "DirectMessagesTopicID", + "json_name": "direct_messages_topic_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Identifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat" + }, + { + "name": "Emoji", + "json_name": "emoji", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Emoji on which the dice throw animation is based. Currently, must be one of “”, “”, “”, “”, “”, or “”. Dice can have values 1-6 for “”, “” and “”, values 1-5 for “” and “”, and values 1-64 for “”. Defaults to “”" + }, + { + "name": "DisableNotification", + "json_name": "disable_notification", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Sends the message silently. Users will receive a notification with no sound." + }, + { + "name": "ProtectContent", + "json_name": "protect_content", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Protects the contents of the sent message from forwarding" + }, + { + "name": "AllowPaidBroadcast", + "json_name": "allow_paid_broadcast", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance." + }, + { + "name": "MessageEffectID", + "json_name": "message_effect_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Unique identifier of the message effect to be added to the message; for private chats only" + }, + { + "name": "SuggestedPostParameters", + "json_name": "suggested_post_parameters", + "type": { + "kind": "named", + "name": "SuggestedPostParameters" + }, + "doc": "A JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined." + }, + { + "name": "ReplyParameters", + "json_name": "reply_parameters", + "type": { + "kind": "named", + "name": "ReplyParameters" + }, + "doc": "Description of the message to reply to" + }, + { + "name": "ReplyMarkup", + "json_name": "reply_markup", + "type": { + "kind": "oneOf", + "variants": [ + "InlineKeyboardMarkup", + "ReplyKeyboardMarkup", + "ReplyKeyboardRemove", + "ForceReply" + ] + }, + "doc": "Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user" + } + ], + "returns": { + "kind": "named", + "name": "Message" + } + }, + { + "name": "sendMessageDraft", + "doc": "Use this method to stream a partial message to a user while the message is being generated. Note that the streamed draft is ephemeral and acts as a temporary 30-second preview - once the output is finalized, you must call sendMessage with the complete message to persist it in the user's chat. Returns True on success.", + "params": [ + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Unique identifier for the target private chat" + }, + { + "name": "MessageThreadID", + "json_name": "message_thread_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Unique identifier for the target message thread" + }, + { + "name": "DraftID", + "json_name": "draft_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Unique identifier of the message draft; must be non-zero. Changes of drafts with the same identifier are animated." + }, + { + "name": "Text", + "json_name": "text", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Text of the message to be sent, 0-4096 characters after entities parsing. Pass an empty text to show a “Thinking…” placeholder." + }, + { + "name": "ParseMode", + "json_name": "parse_mode", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Mode for parsing entities in the message text. See formatting options for more details." + }, + { + "name": "Entities", + "json_name": "entities", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "MessageEntity" + } + }, + "doc": "A JSON-serialized list of special entities that appear in message text, which can be specified instead of parse_mode" + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "sendChatAction", + "doc": "Use this method when you need to tell the user that something is happening on the bot's side. The status is set for 5 seconds or less (when a message arrives from your bot, Telegram clients clear its typing status). Returns True on success.\nExample: The ImageBot needs some time to process a request and upload the image. Instead of sending a text message along the lines of “Retrieving image, please wait…”, the bot may use sendChatAction with action = upload_photo. The user will see a “sending photo” status for the bot.\nWe only recommend using this method when a response from the bot will take a noticeable amount of time to arrive.", + "params": [ + { + "name": "BusinessConnectionID", + "json_name": "business_connection_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Unique identifier of the business connection on behalf of which the action will be sent" + }, + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username. Channel chats and channel direct messages chats aren't supported." + }, + { + "name": "MessageThreadID", + "json_name": "message_thread_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Unique identifier for the target message thread or topic of a forum; for supergroups and private chats of bots with forum topic mode enabled only" + }, + { + "name": "Action", + "json_name": "action", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Type of action to broadcast. Choose one, depending on what the user is about to receive: typing for text messages, upload_photo for photos, record_video or upload_video for videos, record_voice or upload_voice for voice notes, upload_document for general files, choose_sticker for stickers, find_location for location data, record_video_note or upload_video_note for video notes." + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "setMessageReaction", + "doc": "Use this method to change the chosen reactions on a message. Service messages of some types can't be reacted to. Automatically forwarded messages from a channel to its discussion group have the same available reactions as messages in the channel. Bots can't use paid reactions. Returns True on success.", + "params": [ + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username" + }, + { + "name": "MessageID", + "json_name": "message_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Identifier of the target message. If the message belongs to a media group, the reaction is set to the first non-deleted message in the group instead." + }, + { + "name": "Reaction", + "json_name": "reaction", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "ReactionType" + } + }, + "doc": "A JSON-serialized list of reaction types to set on the message. Currently, as non-premium users, bots can set up to one reaction per message. A custom emoji reaction can be used if it is either already present on the message or explicitly allowed by chat administrators. Paid reactions can't be used by bots." + }, + { + "name": "IsBig", + "json_name": "is_big", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True to set the reaction with a big animation" + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "getUserProfilePhotos", + "doc": "Use this method to get a list of profile pictures for a user. Returns a UserProfilePhotos object.", + "params": [ + { + "name": "UserID", + "json_name": "user_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Unique identifier of the target user" + }, + { + "name": "Offset", + "json_name": "offset", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Sequential number of the first photo to be returned. By default, all photos are returned." + }, + { + "name": "Limit", + "json_name": "limit", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Limits the number of photos to be retrieved. Values between 1-100 are accepted. Defaults to 100." + } + ], + "returns": { + "kind": "named", + "name": "UserProfilePhotos" + } + }, + { + "name": "getUserProfileAudios", + "doc": "Use this method to get a list of profile audios for a user. Returns a UserProfileAudios object.", + "params": [ + { + "name": "UserID", + "json_name": "user_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Unique identifier of the target user" + }, + { + "name": "Offset", + "json_name": "offset", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Sequential number of the first audio to be returned. By default, all audios are returned." + }, + { + "name": "Limit", + "json_name": "limit", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Limits the number of audios to be retrieved. Values between 1-100 are accepted. Defaults to 100." + } + ], + "returns": { + "kind": "named", + "name": "UserProfileAudios" + } + }, + { + "name": "setUserEmojiStatus", + "doc": "Changes the emoji status for a given user that previously allowed the bot to manage their emoji status via the Mini App method requestEmojiStatusAccess. Returns True on success.", + "params": [ + { + "name": "UserID", + "json_name": "user_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Unique identifier of the target user" + }, + { + "name": "EmojiStatusCustomEmojiID", + "json_name": "emoji_status_custom_emoji_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Custom emoji identifier of the emoji status to set. Pass an empty string to remove the status." + }, + { + "name": "EmojiStatusExpirationDate", + "json_name": "emoji_status_expiration_date", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Expiration date of the emoji status, if any" + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "getFile", + "doc": "Use this method to get basic information about a file and prepare it for downloading. For the moment, bots can download files of up to 20MB in size. On success, a File object is returned. The file can then be downloaded via the link https://api.telegram.org/file/bot/, where is taken from the response. It is guaranteed that the link will be valid for at least 1 hour. When the link expires, a new one can be requested by calling getFile again.\nNote: This function may not preserve the original file name and MIME type. You should save the file's MIME type and name (if available) when the File object is received.", + "params": [ + { + "name": "FileID", + "json_name": "file_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "File identifier to get information about" + } + ], + "returns": { + "kind": "named", + "name": "File" + } + }, + { + "name": "banChatMember", + "doc": "Use this method to ban a user in a group, a supergroup or a channel. In the case of supergroups and channels, the user will not be able to return to the chat on their own using invite links, etc., unless unbanned first. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns True on success.", + "params": [ + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the target group or username of the target supergroup or channel in the format @username" + }, + { + "name": "UserID", + "json_name": "user_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Unique identifier of the target user" + }, + { + "name": "UntilDate", + "json_name": "until_date", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Date when the user will be unbanned; Unix time. If user is banned for more than 366 days or less than 30 seconds from the current time they are considered to be banned forever. Applied for supergroups and channels only." + }, + { + "name": "RevokeMessages", + "json_name": "revoke_messages", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True to delete all messages from the chat for the user that is being removed. If False, the user will be able to see messages in the group that were sent before the user was removed. Always True for supergroups and channels." + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "unbanChatMember", + "doc": "Use this method to unban a previously banned user in a supergroup or channel. The user will not return to the group or channel automatically, but will be able to join via link, etc. The bot must be an administrator for this to work. By default, this method guarantees that after the call the user is not a member of the chat, but will be able to join it. So if the user is a member of the chat they will also be removed from the chat. If you don't want this, use the parameter only_if_banned. Returns True on success.", + "params": [ + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the target group or username of the target supergroup or channel in the format @username" + }, + { + "name": "UserID", + "json_name": "user_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Unique identifier of the target user" + }, + { + "name": "OnlyIfBanned", + "json_name": "only_if_banned", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Do nothing if the user is not banned" + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "restrictChatMember", + "doc": "Use this method to restrict a user in a supergroup. The bot must be an administrator in the supergroup for this to work and must have the appropriate administrator rights. Pass True for all permissions to lift restrictions from a user. Returns True on success.", + "params": [ + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the target chat or username of the target supergroup in the format @username" + }, + { + "name": "UserID", + "json_name": "user_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Unique identifier of the target user" + }, + { + "name": "Permissions", + "json_name": "permissions", + "type": { + "kind": "named", + "name": "ChatPermissions" + }, + "required": true, + "doc": "A JSON-serialized object for new user permissions" + }, + { + "name": "UseIndependentChatPermissions", + "json_name": "use_independent_chat_permissions", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True if chat permissions are set independently. Otherwise, the can_send_other_messages and can_add_web_page_previews permissions will imply the can_send_messages, can_send_audios, can_send_documents, can_send_photos, can_send_videos, can_send_video_notes, and can_send_voice_notes permissions; the can_send_polls permission will imply the can_send_messages permission." + }, + { + "name": "UntilDate", + "json_name": "until_date", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Date when restrictions will be lifted for the user; Unix time. If user is restricted for more than 366 days or less than 30 seconds from the current time, they are considered to be restricted forever" + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "promoteChatMember", + "doc": "Use this method to promote or demote a user in a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Pass False for all boolean parameters to demote a user. Returns True on success.", + "params": [ + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the target chat or username of the target channel in the format @username" + }, + { + "name": "UserID", + "json_name": "user_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Unique identifier of the target user" + }, + { + "name": "IsAnonymous", + "json_name": "is_anonymous", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True if the administrator's presence in the chat is hidden" + }, + { + "name": "CanManageChat", + "json_name": "can_manage_chat", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True if the administrator can access the chat event log, get boost list, see hidden supergroup and channel members, report spam messages, ignore slow mode, and send messages to the chat without paying Telegram Stars. Implied by any other administrator privilege." + }, + { + "name": "CanDeleteMessages", + "json_name": "can_delete_messages", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True if the administrator can delete messages of other users" + }, + { + "name": "CanManageVideoChats", + "json_name": "can_manage_video_chats", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True if the administrator can manage video chats" + }, + { + "name": "CanRestrictMembers", + "json_name": "can_restrict_members", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True if the administrator can restrict, ban or unban chat members, or access supergroup statistics. For backward compatibility, defaults to True for promotions of channel administrators" + }, + { + "name": "CanPromoteMembers", + "json_name": "can_promote_members", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True if the administrator can add new administrators with a subset of their own privileges or demote administrators that they have promoted, directly or indirectly (promoted by administrators that were appointed by him)" + }, + { + "name": "CanChangeInfo", + "json_name": "can_change_info", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True if the administrator can change chat title, photo and other settings" + }, + { + "name": "CanInviteUsers", + "json_name": "can_invite_users", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True if the administrator can invite new users to the chat" + }, + { + "name": "CanPostStories", + "json_name": "can_post_stories", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True if the administrator can post stories to the chat" + }, + { + "name": "CanEditStories", + "json_name": "can_edit_stories", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True if the administrator can edit stories posted by other users, post stories to the chat page, pin chat stories, and access the chat's story archive" + }, + { + "name": "CanDeleteStories", + "json_name": "can_delete_stories", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True if the administrator can delete stories posted by other users" + }, + { + "name": "CanPostMessages", + "json_name": "can_post_messages", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True if the administrator can post messages in the channel, approve suggested posts, or access channel statistics; for channels only" + }, + { + "name": "CanEditMessages", + "json_name": "can_edit_messages", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True if the administrator can edit messages of other users and can pin messages; for channels only" + }, + { + "name": "CanPinMessages", + "json_name": "can_pin_messages", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True if the administrator can pin messages; for supergroups only" + }, + { + "name": "CanManageTopics", + "json_name": "can_manage_topics", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True if the user is allowed to create, rename, close, and reopen forum topics; for supergroups only" + }, + { + "name": "CanManageDirectMessages", + "json_name": "can_manage_direct_messages", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True if the administrator can manage direct messages within the channel and decline suggested posts; for channels only" + }, + { + "name": "CanManageTags", + "json_name": "can_manage_tags", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True if the administrator can edit the tags of regular members; for groups and supergroups only" + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "setChatAdministratorCustomTitle", + "doc": "Use this method to set a custom title for an administrator in a supergroup promoted by the bot. Returns True on success.", + "params": [ + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the target chat or username of the target supergroup in the format @username" + }, + { + "name": "UserID", + "json_name": "user_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Unique identifier of the target user" + }, + { + "name": "CustomTitle", + "json_name": "custom_title", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "New custom title for the administrator; 0-16 characters, emoji are not allowed" + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "setChatMemberTag", + "doc": "Use this method to set a tag for a regular member in a group or a supergroup. The bot must be an administrator in the chat for this to work and must have the can_manage_tags administrator right. Returns True on success.", + "params": [ + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the target chat or username of the target supergroup in the format @username" + }, + { + "name": "UserID", + "json_name": "user_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Unique identifier of the target user" + }, + { + "name": "Tag", + "json_name": "tag", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "New tag for the member; 0-16 characters, emoji are not allowed" + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "banChatSenderChat", + "doc": "Use this method to ban a channel chat in a supergroup or a channel. Until the chat is unbanned, the owner of the banned chat won't be able to send messages on behalf of any of their channels. The bot must be an administrator in the supergroup or channel for this to work and must have the appropriate administrator rights. Returns True on success.", + "params": [ + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the target chat or username of the target channel in the format @username" + }, + { + "name": "SenderChatID", + "json_name": "sender_chat_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Unique identifier of the target sender chat" + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "unbanChatSenderChat", + "doc": "Use this method to unban a previously banned channel chat in a supergroup or channel. The bot must be an administrator for this to work and must have the appropriate administrator rights. Returns True on success.", + "params": [ + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the target chat or username of the target channel in the format @username" + }, + { + "name": "SenderChatID", + "json_name": "sender_chat_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Unique identifier of the target sender chat" + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "setChatPermissions", + "doc": "Use this method to set default chat permissions for all members. The bot must be an administrator in the group or a supergroup for this to work and must have the can_restrict_members administrator rights. Returns True on success.", + "params": [ + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the target chat or username of the target supergroup in the format @username" + }, + { + "name": "Permissions", + "json_name": "permissions", + "type": { + "kind": "named", + "name": "ChatPermissions" + }, + "required": true, + "doc": "A JSON-serialized object for new default chat permissions" + }, + { + "name": "UseIndependentChatPermissions", + "json_name": "use_independent_chat_permissions", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True if chat permissions are set independently. Otherwise, the can_send_other_messages and can_add_web_page_previews permissions will imply the can_send_messages, can_send_audios, can_send_documents, can_send_photos, can_send_videos, can_send_video_notes, and can_send_voice_notes permissions; the can_send_polls permission will imply the can_send_messages permission." + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "exportChatInviteLink", + "doc": "Use this method to generate a new primary invite link for a chat; any previously generated primary link is revoked. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns the new invite link as String on success.\nNote: Each administrator in a chat generates their own invite links. Bots can't use invite links generated by other administrators. If you want your bot to work with invite links, it will need to generate its own link using exportChatInviteLink or by calling the getChat method. If your bot needs to generate a new primary invite link replacing its previous one, use exportChatInviteLink again.", + "params": [ + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the target chat or username of the target channel in the format @username" + } + ], + "returns": { + "kind": "primitive", + "name": "string" + } + }, + { + "name": "createChatInviteLink", + "doc": "Use this method to create an additional invite link for a chat. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. The link can be revoked using the method revokeChatInviteLink. Returns the new invite link as ChatInviteLink object.", + "params": [ + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the target chat or username of the target channel in the format @username" + }, + { + "name": "Name", + "json_name": "name", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Invite link name; 0-32 characters" + }, + { + "name": "ExpireDate", + "json_name": "expire_date", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Point in time (Unix timestamp) when the link will expire" + }, + { + "name": "MemberLimit", + "json_name": "member_limit", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "The maximum number of users that can be members of the chat simultaneously after joining the chat via this invite link; 1-99999" + }, + { + "name": "CreatesJoinRequest", + "json_name": "creates_join_request", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "True, if users joining the chat via the link need to be approved by chat administrators. If True, member_limit can't be specified" + } + ], + "returns": { + "kind": "named", + "name": "ChatInviteLink" + } + }, + { + "name": "editChatInviteLink", + "doc": "Use this method to edit a non-primary invite link created by the bot. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns the edited invite link as a ChatInviteLink object.", + "params": [ + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the target chat or username of the target channel in the format @username" + }, + { + "name": "InviteLink", + "json_name": "invite_link", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "The invite link to edit" + }, + { + "name": "Name", + "json_name": "name", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Invite link name; 0-32 characters" + }, + { + "name": "ExpireDate", + "json_name": "expire_date", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Point in time (Unix timestamp) when the link will expire" + }, + { + "name": "MemberLimit", + "json_name": "member_limit", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "The maximum number of users that can be members of the chat simultaneously after joining the chat via this invite link; 1-99999" + }, + { + "name": "CreatesJoinRequest", + "json_name": "creates_join_request", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "True, if users joining the chat via the link need to be approved by chat administrators. If True, member_limit can't be specified" + } + ], + "returns": { + "kind": "named", + "name": "ChatInviteLink" + } + }, + { + "name": "createChatSubscriptionInviteLink", + "doc": "Use this method to create a subscription invite link for a channel chat. The bot must have the can_invite_users administrator rights. The link can be edited using the method editChatSubscriptionInviteLink or revoked using the method revokeChatInviteLink. Returns the new invite link as a ChatInviteLink object.", + "params": [ + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the target channel chat or username of the target channel in the format @username" + }, + { + "name": "Name", + "json_name": "name", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Invite link name; 0-32 characters" + }, + { + "name": "SubscriptionPeriod", + "json_name": "subscription_period", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "The number of seconds the subscription will be active for before the next payment. Currently, it must always be 2592000 (30 days)." + }, + { + "name": "SubscriptionPrice", + "json_name": "subscription_price", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "The amount of Telegram Stars a user must pay initially and after each subsequent subscription period to be a member of the chat; 1-10000" + } + ], + "returns": { + "kind": "named", + "name": "ChatInviteLink" + } + }, + { + "name": "editChatSubscriptionInviteLink", + "doc": "Use this method to edit a subscription invite link created by the bot. The bot must have the can_invite_users administrator rights. Returns the edited invite link as a ChatInviteLink object.", + "params": [ + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the target chat or username of the target channel in the format @username" + }, + { + "name": "InviteLink", + "json_name": "invite_link", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "The invite link to edit" + }, + { + "name": "Name", + "json_name": "name", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Invite link name; 0-32 characters" + } + ], + "returns": { + "kind": "named", + "name": "ChatInviteLink" + } + }, + { + "name": "revokeChatInviteLink", + "doc": "Use this method to revoke an invite link created by the bot. If the primary link is revoked, a new link is automatically generated. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns the revoked invite link as ChatInviteLink object.", + "params": [ + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier of the target chat or username of the target channel in the format @username" + }, + { + "name": "InviteLink", + "json_name": "invite_link", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "The invite link to revoke" + } + ], + "returns": { + "kind": "named", + "name": "ChatInviteLink" + } + }, + { + "name": "approveChatJoinRequest", + "doc": "Use this method to approve a chat join request. The bot must be an administrator in the chat for this to work and must have the can_invite_users administrator right. Returns True on success.", + "params": [ + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the target chat or username of the target channel in the format @username" + }, + { + "name": "UserID", + "json_name": "user_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Unique identifier of the target user" + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "declineChatJoinRequest", + "doc": "Use this method to decline a chat join request. The bot must be an administrator in the chat for this to work and must have the can_invite_users administrator right. Returns True on success.", + "params": [ + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the target chat or username of the target channel in the format @username" + }, + { + "name": "UserID", + "json_name": "user_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Unique identifier of the target user" + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "setChatPhoto", + "doc": "Use this method to set a new profile photo for the chat. Photos can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns True on success.", + "params": [ + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the target chat or username of the target channel in the format @username" + }, + { + "name": "Photo", + "json_name": "photo", + "type": { + "kind": "named", + "name": "InputFile" + }, + "required": true, + "doc": "New chat photo, uploaded using multipart/form-data" + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + }, + "has_files": true + }, + { + "name": "deleteChatPhoto", + "doc": "Use this method to delete a chat photo. Photos can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns True on success.", + "params": [ + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the target chat or username of the target channel in the format @username" + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "setChatTitle", + "doc": "Use this method to change the title of a chat. Titles can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns True on success.", + "params": [ + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the target chat or username of the target channel in the format @username" + }, + { + "name": "Title", + "json_name": "title", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "New chat title, 1-128 characters" + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "setChatDescription", + "doc": "Use this method to change the description of a group, a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns True on success.", + "params": [ + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the target chat or username of the target channel in the format @username" + }, + { + "name": "Description", + "json_name": "description", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "New chat description, 0-255 characters" + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "pinChatMessage", + "doc": "Use this method to add a message to the list of pinned messages in a chat. In private chats and channel direct messages chats, all non-service messages can be pinned. Conversely, the bot must be an administrator with the 'can_pin_messages' right or the 'can_edit_messages' right to pin messages in groups and channels respectively. Returns True on success.", + "params": [ + { + "name": "BusinessConnectionID", + "json_name": "business_connection_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Unique identifier of the business connection on behalf of which the message will be pinned" + }, + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the target chat or username of the target channel in the format @username" + }, + { + "name": "MessageID", + "json_name": "message_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Identifier of a message to pin" + }, + { + "name": "DisableNotification", + "json_name": "disable_notification", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True if it is not necessary to send a notification to all chat members about the new pinned message. Notifications are always disabled in channels and private chats." + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "unpinChatMessage", + "doc": "Use this method to remove a message from the list of pinned messages in a chat. In private chats and channel direct messages chats, all messages can be unpinned. Conversely, the bot must be an administrator with the 'can_pin_messages' right or the 'can_edit_messages' right to unpin messages in groups and channels respectively. Returns True on success.", + "params": [ + { + "name": "BusinessConnectionID", + "json_name": "business_connection_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Unique identifier of the business connection on behalf of which the message will be unpinned" + }, + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the target chat or username of the target channel in the format @username" + }, + { + "name": "MessageID", + "json_name": "message_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Identifier of the message to unpin. Required if business_connection_id is specified. If not specified, the most recent pinned message (by sending date) will be unpinned." + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "unpinAllChatMessages", + "doc": "Use this method to clear the list of pinned messages in a chat. In private chats and channel direct messages chats, no additional rights are required to unpin all pinned messages. Conversely, the bot must be an administrator with the 'can_pin_messages' right or the 'can_edit_messages' right to unpin all pinned messages in groups and channels respectively. Returns True on success.", + "params": [ + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the target chat or username of the target channel in the format @username" + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "leaveChat", + "doc": "Use this method for your bot to leave a group, supergroup or channel. Returns True on success.", + "params": [ + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the target chat or username of the target supergroup or channel in the format @username. Channel direct messages chats aren't supported; leave the corresponding channel instead." + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "getChat", + "doc": "Use this method to get up-to-date information about the chat. Returns a ChatFullInfo object on success.", + "params": [ + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the target chat or username of the target supergroup or channel in the format @username" + } + ], + "returns": { + "kind": "named", + "name": "ChatFullInfo" + } + }, + { + "name": "getChatAdministrators", + "doc": "Use this method to get a list of administrators in a chat. Returns an Array of ChatMember objects.", + "params": [ + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the target chat or username of the target supergroup or channel in the format @username" + }, + { + "name": "ReturnBots", + "json_name": "return_bots", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True to additionally receive all bots that are administrators of the chat. By default, bots other than the current bot are omitted." + } + ], + "returns": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "ChatMember" + } + } + }, + { + "name": "getChatMemberCount", + "doc": "Use this method to get the number of members in a chat. Returns Int on success.", + "params": [ + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the target chat or username of the target supergroup or channel in the format @username" + } + ], + "returns": { + "kind": "primitive", + "name": "int64" + } + }, + { + "name": "getChatMember", + "doc": "Use this method to get information about a member of a chat. The method is only guaranteed to work for other users if the bot is an administrator in the chat. Returns a ChatMember object on success.", + "params": [ + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the target chat or username of the target supergroup or channel in the format @username" + }, + { + "name": "UserID", + "json_name": "user_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Unique identifier of the target user" + } + ], + "returns": { + "kind": "named", + "name": "ChatMember" + } + }, + { + "name": "getUserPersonalChatMessages", + "doc": "Use this method to get the last messages from the personal chat (i.e., the chat currently added to their profile) of a given user. On success, an array of Message objects is returned.", + "params": [ + { + "name": "UserID", + "json_name": "user_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Unique identifier for the target user" + }, + { + "name": "Limit", + "json_name": "limit", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "The maximum number of messages to return; 1-20" + } + ], + "returns": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "Message" + } + } + }, + { + "name": "setChatStickerSet", + "doc": "Use this method to set a new group sticker set for a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Use the field can_set_sticker_set optionally returned in getChat requests to check if the bot can use this method. Returns True on success.", + "params": [ + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the target chat or username of the target supergroup in the format @username" + }, + { + "name": "StickerSetName", + "json_name": "sticker_set_name", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Name of the sticker set to be set as the group sticker set" + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "deleteChatStickerSet", + "doc": "Use this method to delete a group sticker set from a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Use the field can_set_sticker_set optionally returned in getChat requests to check if the bot can use this method. Returns True on success.", + "params": [ + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the target chat or username of the target supergroup in the format @username" + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "getForumTopicIconStickers", + "doc": "Use this method to get custom emoji stickers, which can be used as a forum topic icon by any user. Requires no parameters. Returns an Array of Sticker objects.", + "returns": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "Sticker" + } + } + }, + { + "name": "createForumTopic", + "doc": "Use this method to create a topic in a forum supergroup chat or a private chat with a user. In the case of a supergroup chat the bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator right. Returns information about the created topic as a ForumTopic object.", + "params": [ + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the target chat or username of the target supergroup in the format @username" + }, + { + "name": "Name", + "json_name": "name", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Topic name, 1-128 characters" + }, + { + "name": "IconColor", + "json_name": "icon_color", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Color of the topic icon in RGB format. Currently, must be one of 7322096 (0x6FB9F0), 16766590 (0xFFD67E), 13338331 (0xCB86DB), 9367192 (0x8EEE98), 16749490 (0xFF93B2), or 16478047 (0xFB6F5F)" + }, + { + "name": "IconCustomEmojiID", + "json_name": "icon_custom_emoji_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Unique identifier of the custom emoji shown as the topic icon. Use getForumTopicIconStickers to get all allowed custom emoji identifiers." + } + ], + "returns": { + "kind": "named", + "name": "ForumTopic" + } + }, + { + "name": "editForumTopic", + "doc": "Use this method to edit name and icon of a topic in a forum supergroup chat or a private chat with a user. In the case of a supergroup chat the bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights, unless it is the creator of the topic. Returns True on success.", + "params": [ + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the target chat or username of the target supergroup in the format @username" + }, + { + "name": "MessageThreadID", + "json_name": "message_thread_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Unique identifier for the target message thread of the forum topic" + }, + { + "name": "Name", + "json_name": "name", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "New topic name, 0-128 characters. If not specified or empty, the current name of the topic will be kept" + }, + { + "name": "IconCustomEmojiID", + "json_name": "icon_custom_emoji_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "New unique identifier of the custom emoji shown as the topic icon. Use getForumTopicIconStickers to get all allowed custom emoji identifiers. Pass an empty string to remove the icon. If not specified, the current icon will be kept" + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "closeForumTopic", + "doc": "Use this method to close an open topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights, unless it is the creator of the topic. Returns True on success.", + "params": [ + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the target chat or username of the target supergroup in the format @username" + }, + { + "name": "MessageThreadID", + "json_name": "message_thread_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Unique identifier for the target message thread of the forum topic" + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "reopenForumTopic", + "doc": "Use this method to reopen a closed topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights, unless it is the creator of the topic. Returns True on success.", + "params": [ + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the target chat or username of the target supergroup in the format @username" + }, + { + "name": "MessageThreadID", + "json_name": "message_thread_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Unique identifier for the target message thread of the forum topic" + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "deleteForumTopic", + "doc": "Use this method to delete a forum topic along with all its messages in a forum supergroup chat or a private chat with a user. In the case of a supergroup chat the bot must be an administrator in the chat for this to work and must have the can_delete_messages administrator rights. Returns True on success.", + "params": [ + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the target chat or username of the target supergroup in the format @username" + }, + { + "name": "MessageThreadID", + "json_name": "message_thread_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Unique identifier for the target message thread of the forum topic" + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "unpinAllForumTopicMessages", + "doc": "Use this method to clear the list of pinned messages in a forum topic in a forum supergroup chat or a private chat with a user. In the case of a supergroup chat the bot must be an administrator in the chat for this to work and must have the can_pin_messages administrator right in the supergroup. Returns True on success.", + "params": [ + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the target chat or username of the target supergroup in the format @username" + }, + { + "name": "MessageThreadID", + "json_name": "message_thread_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Unique identifier for the target message thread of the forum topic" + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "editGeneralForumTopic", + "doc": "Use this method to edit the name of the 'General' topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights. Returns True on success.", + "params": [ + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the target chat or username of the target supergroup in the format @username" + }, + { + "name": "Name", + "json_name": "name", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "New topic name, 1-128 characters" + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "closeGeneralForumTopic", + "doc": "Use this method to close an open 'General' topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights. Returns True on success.", + "params": [ + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the target chat or username of the target supergroup in the format @username" + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "reopenGeneralForumTopic", + "doc": "Use this method to reopen a closed 'General' topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights. The topic will be automatically unhidden if it was hidden. Returns True on success.", + "params": [ + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the target chat or username of the target supergroup in the format @username" + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "hideGeneralForumTopic", + "doc": "Use this method to hide the 'General' topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights. The topic will be automatically closed if it was open. Returns True on success.", + "params": [ + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the target chat or username of the target supergroup in the format @username" + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "unhideGeneralForumTopic", + "doc": "Use this method to unhide the 'General' topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights. Returns True on success.", + "params": [ + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the target chat or username of the target supergroup in the format @username" + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "unpinAllGeneralForumTopicMessages", + "doc": "Use this method to clear the list of pinned messages in a General forum topic. The bot must be an administrator in the chat for this to work and must have the can_pin_messages administrator right in the supergroup. Returns True on success.", + "params": [ + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the target chat or username of the target supergroup in the format @username" + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "answerCallbackQuery", + "doc": "Use this method to send answers to callback queries sent from inline keyboards. The answer will be displayed to the user as a notification at the top of the chat screen or as an alert. On success, True is returned.\nAlternatively, the user can be redirected to the specified Game URL. For this option to work, you must first create a game for your bot via @BotFather and accept the terms. Otherwise, you may use links like t.me/your_bot?start=XXXX that open your bot with a parameter.", + "params": [ + { + "name": "CallbackQueryID", + "json_name": "callback_query_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique identifier for the query to be answered" + }, + { + "name": "Text", + "json_name": "text", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Text of the notification. If not specified, nothing will be shown to the user, 0-200 characters" + }, + { + "name": "ShowAlert", + "json_name": "show_alert", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "If True, an alert will be shown by the client instead of a notification at the top of the chat screen. Defaults to false." + }, + { + "name": "URL", + "json_name": "url", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "URL that will be opened by the user's client. If you have created a Game and accepted the conditions via @BotFather, specify the URL that opens your game - note that this will only work if the query comes from a callback_game button.Otherwise, you may use links like t.me/your_bot?start=XXXX that open your bot with a parameter." + }, + { + "name": "CacheTime", + "json_name": "cache_time", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "The maximum amount of time in seconds that the result of the callback query may be cached client-side. Telegram apps will support caching starting in version 3.14. Defaults to 0." + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "answerGuestQuery", + "doc": "Use this method to reply to a received guest message. On success, a SentGuestMessage object is returned.", + "params": [ + { + "name": "GuestQueryID", + "json_name": "guest_query_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique identifier for the query to be answered" + }, + { + "name": "Result", + "json_name": "result", + "type": { + "kind": "named", + "name": "InlineQueryResult" + }, + "required": true, + "doc": "A JSON-serialized object describing the message to be sent" + } + ], + "returns": { + "kind": "named", + "name": "SentGuestMessage" + } + }, + { + "name": "getUserChatBoosts", + "doc": "Use this method to get the list of boosts added to a chat by a user. Requires administrator rights in the chat. Returns a UserChatBoosts object.", + "params": [ + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the chat or username of the channel in the format @username" + }, + { + "name": "UserID", + "json_name": "user_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Unique identifier of the target user" + } + ], + "returns": { + "kind": "named", + "name": "UserChatBoosts" + } + }, + { + "name": "getBusinessConnection", + "doc": "Use this method to get information about the connection of the bot with a business account. Returns a BusinessConnection object on success.", + "params": [ + { + "name": "BusinessConnectionID", + "json_name": "business_connection_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique identifier of the business connection" + } + ], + "returns": { + "kind": "named", + "name": "BusinessConnection" + } + }, + { + "name": "getManagedBotToken", + "doc": "Use this method to get the token of a managed bot. Returns the token as String on success.", + "params": [ + { + "name": "UserID", + "json_name": "user_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "User identifier of the managed bot whose token will be returned" + } + ], + "returns": { + "kind": "primitive", + "name": "string" + } + }, + { + "name": "replaceManagedBotToken", + "doc": "Use this method to revoke the current token of a managed bot and generate a new one. Returns the new token as String on success.", + "params": [ + { + "name": "UserID", + "json_name": "user_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "User identifier of the managed bot whose token will be replaced" + } + ], + "returns": { + "kind": "primitive", + "name": "string" + } + }, + { + "name": "getManagedBotAccessSettings", + "doc": "Use this method to get the access settings of a managed bot. Returns a BotAccessSettings object on success.", + "params": [ + { + "name": "UserID", + "json_name": "user_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "User identifier of the managed bot whose access settings will be returned" + } + ], + "returns": { + "kind": "named", + "name": "BotAccessSettings" + } + }, + { + "name": "setManagedBotAccessSettings", + "doc": "Use this method to change the access settings of a managed bot. Returns True on success.", + "params": [ + { + "name": "UserID", + "json_name": "user_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "User identifier of the managed bot whose access settings will be changed" + }, + { + "name": "IsAccessRestricted", + "json_name": "is_access_restricted", + "type": { + "kind": "primitive", + "name": "bool" + }, + "required": true, + "doc": "Pass True, if only selected users can access the bot. The bot's owner can always access it." + }, + { + "name": "AddedUserIds", + "json_name": "added_user_ids", + "type": { + "kind": "array", + "elem_type": { + "kind": "primitive", + "name": "int64" + } + }, + "doc": "A JSON-serialized list of up to 10 identifiers of users who will have access to the bot in addition to its owner. Ignored if is_access_restricted is false." + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "setMyCommands", + "doc": "Use this method to change the list of the bot's commands. See this manual for more details about bot commands. Returns True on success.", + "params": [ + { + "name": "Commands", + "json_name": "commands", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "BotCommand" + } + }, + "required": true, + "doc": "A JSON-serialized list of bot commands to be set as the list of the bot's commands. At most 100 commands can be specified." + }, + { + "name": "Scope", + "json_name": "scope", + "type": { + "kind": "named", + "name": "BotCommandScope" + }, + "doc": "A JSON-serialized object, describing scope of users for which the commands are relevant. Defaults to BotCommandScopeDefault." + }, + { + "name": "LanguageCode", + "json_name": "language_code", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "A two-letter ISO 639-1 language code. If empty, commands will be applied to all users from the given scope, for whose language there are no dedicated commands" + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "deleteMyCommands", + "doc": "Use this method to delete the list of the bot's commands for the given scope and user language. After deletion, higher level commands will be shown to affected users. Returns True on success.", + "params": [ + { + "name": "Scope", + "json_name": "scope", + "type": { + "kind": "named", + "name": "BotCommandScope" + }, + "doc": "A JSON-serialized object, describing scope of users for which the commands are relevant. Defaults to BotCommandScopeDefault." + }, + { + "name": "LanguageCode", + "json_name": "language_code", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "A two-letter ISO 639-1 language code. If empty, commands will be applied to all users from the given scope, for whose language there are no dedicated commands" + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "getMyCommands", + "doc": "Use this method to get the current list of the bot's commands for the given scope and user language. Returns an Array of BotCommand objects. If commands aren't set, an empty list is returned.", + "params": [ + { + "name": "Scope", + "json_name": "scope", + "type": { + "kind": "named", + "name": "BotCommandScope" + }, + "doc": "A JSON-serialized object, describing scope of users. Defaults to BotCommandScopeDefault." + }, + { + "name": "LanguageCode", + "json_name": "language_code", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "A two-letter ISO 639-1 language code or an empty string" + } + ], + "returns": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "BotCommand" + } + } + }, + { + "name": "setMyName", + "doc": "Use this method to change the bot's name. Returns True on success.", + "params": [ + { + "name": "Name", + "json_name": "name", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "New bot name; 0-64 characters. Pass an empty string to remove the dedicated name for the given language." + }, + { + "name": "LanguageCode", + "json_name": "language_code", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "A two-letter ISO 639-1 language code. If empty, the name will be shown to all users for whose language there is no dedicated name." + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "getMyName", + "doc": "Use this method to get the current bot name for the given user language. Returns BotName on success.", + "params": [ + { + "name": "LanguageCode", + "json_name": "language_code", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "A two-letter ISO 639-1 language code or an empty string" + } + ], + "returns": { + "kind": "named", + "name": "BotName" + } + }, + { + "name": "setMyDescription", + "doc": "Use this method to change the bot's description, which is shown in the chat with the bot if the chat is empty. Returns True on success.", + "params": [ + { + "name": "Description", + "json_name": "description", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "New bot description; 0-512 characters. Pass an empty string to remove the dedicated description for the given language." + }, + { + "name": "LanguageCode", + "json_name": "language_code", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "A two-letter ISO 639-1 language code. If empty, the description will be applied to all users for whose language there is no dedicated description." + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "getMyDescription", + "doc": "Use this method to get the current bot description for the given user language. Returns BotDescription on success.", + "params": [ + { + "name": "LanguageCode", + "json_name": "language_code", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "A two-letter ISO 639-1 language code or an empty string" + } + ], + "returns": { + "kind": "named", + "name": "BotDescription" + } + }, + { + "name": "setMyShortDescription", + "doc": "Use this method to change the bot's short description, which is shown on the bot's profile page and is sent together with the link when users share the bot. Returns True on success.", + "params": [ + { + "name": "ShortDescription", + "json_name": "short_description", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "New short description for the bot; 0-120 characters. Pass an empty string to remove the dedicated short description for the given language." + }, + { + "name": "LanguageCode", + "json_name": "language_code", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "A two-letter ISO 639-1 language code. If empty, the short description will be applied to all users for whose language there is no dedicated short description." + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "getMyShortDescription", + "doc": "Use this method to get the current bot short description for the given user language. Returns BotShortDescription on success.", + "params": [ + { + "name": "LanguageCode", + "json_name": "language_code", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "A two-letter ISO 639-1 language code or an empty string" + } + ], + "returns": { + "kind": "named", + "name": "BotShortDescription" + } + }, + { + "name": "setMyProfilePhoto", + "doc": "Changes the profile photo of the bot. Returns True on success.", + "params": [ + { + "name": "Photo", + "json_name": "photo", + "type": { + "kind": "named", + "name": "InputProfilePhoto" + }, + "required": true, + "doc": "The new profile photo to set" + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "removeMyProfilePhoto", + "doc": "Removes the profile photo of the bot. Requires no parameters. Returns True on success.", + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "setChatMenuButton", + "doc": "Use this method to change the bot's menu button in a private chat, or the default menu button. Returns True on success.", + "params": [ + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Unique identifier for the target private chat. If not specified, default bot's menu button will be changed" + }, + { + "name": "MenuButton", + "json_name": "menu_button", + "type": { + "kind": "named", + "name": "MenuButton" + }, + "doc": "A JSON-serialized object for the bot's new menu button. Defaults to MenuButtonDefault" + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "getChatMenuButton", + "doc": "Use this method to get the current value of the bot's menu button in a private chat, or the default menu button. Returns MenuButton on success.", + "params": [ + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Unique identifier for the target private chat. If not specified, default bot's menu button will be returned" + } + ], + "returns": { + "kind": "named", + "name": "MenuButton" + } + }, + { + "name": "setMyDefaultAdministratorRights", + "doc": "Use this method to change the default administrator rights requested by the bot when it's added as an administrator to groups or channels. These rights will be suggested to users, but they are free to modify the list before adding the bot. Returns True on success.", + "params": [ + { + "name": "Rights", + "json_name": "rights", + "type": { + "kind": "named", + "name": "ChatAdministratorRights" + }, + "doc": "A JSON-serialized object describing new default administrator rights. If not specified, the default administrator rights will be cleared." + }, + { + "name": "ForChannels", + "json_name": "for_channels", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True to change the default administrator rights of the bot in channels. Otherwise, the default administrator rights of the bot for groups and supergroups will be changed." + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "getMyDefaultAdministratorRights", + "doc": "Use this method to get the current default administrator rights of the bot. Returns ChatAdministratorRights on success.", + "params": [ + { + "name": "ForChannels", + "json_name": "for_channels", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True to get default administrator rights of the bot in channels. Otherwise, default administrator rights of the bot for groups and supergroups will be returned." + } + ], + "returns": { + "kind": "named", + "name": "ChatAdministratorRights" + } + }, + { + "name": "getAvailableGifts", + "doc": "Returns the list of gifts that can be sent by the bot to users and channel chats. Requires no parameters. Returns a Gifts object.", + "returns": { + "kind": "named", + "name": "Gifts" + } + }, + { + "name": "sendGift", + "doc": "Sends a gift to the given user or channel chat. The gift can't be converted to Telegram Stars by the receiver. Returns True on success.", + "params": [ + { + "name": "UserID", + "json_name": "user_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Required if chat_id is not specified. Unique identifier of the target user who will receive the gift." + }, + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "doc": "Required if user_id is not specified. Unique identifier for the chat or username of the channel (in the format @username) that will receive the gift." + }, + { + "name": "GiftID", + "json_name": "gift_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Identifier of the gift; limited gifts can't be sent to channel chats" + }, + { + "name": "PayForUpgrade", + "json_name": "pay_for_upgrade", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True to pay for the gift upgrade from the bot's balance, thereby making the upgrade free for the receiver" + }, + { + "name": "Text", + "json_name": "text", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Text that will be shown along with the gift; 0-128 characters" + }, + { + "name": "TextParseMode", + "json_name": "text_parse_mode", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Mode for parsing entities in the text. See formatting options for more details. Entities other than “bold”, “italic”, “underline”, “strikethrough”, “spoiler”, “custom_emoji”, and “date_time” are ignored." + }, + { + "name": "TextEntities", + "json_name": "text_entities", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "MessageEntity" + } + }, + "doc": "A JSON-serialized list of special entities that appear in the gift text. It can be specified instead of text_parse_mode. Entities other than “bold”, “italic”, “underline”, “strikethrough”, “spoiler”, “custom_emoji”, and “date_time” are ignored." + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "giftPremiumSubscription", + "doc": "Gifts a Telegram Premium subscription to the given user. Returns True on success.", + "params": [ + { + "name": "UserID", + "json_name": "user_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Unique identifier of the target user who will receive a Telegram Premium subscription" + }, + { + "name": "MonthCount", + "json_name": "month_count", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Number of months the Telegram Premium subscription will be active for the user; must be one of 3, 6, or 12" + }, + { + "name": "StarCount", + "json_name": "star_count", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Number of Telegram Stars to pay for the Telegram Premium subscription; must be 1000 for 3 months, 1500 for 6 months, and 2500 for 12 months" + }, + { + "name": "Text", + "json_name": "text", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Text that will be shown along with the service message about the subscription; 0-128 characters" + }, + { + "name": "TextParseMode", + "json_name": "text_parse_mode", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Mode for parsing entities in the text. See formatting options for more details. Entities other than “bold”, “italic”, “underline”, “strikethrough”, “spoiler”, “custom_emoji”, and “date_time” are ignored." + }, + { + "name": "TextEntities", + "json_name": "text_entities", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "MessageEntity" + } + }, + "doc": "A JSON-serialized list of special entities that appear in the gift text. It can be specified instead of text_parse_mode. Entities other than “bold”, “italic”, “underline”, “strikethrough”, “spoiler”, “custom_emoji”, and “date_time” are ignored." + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "verifyUser", + "doc": "Verifies a user on behalf of the organization which is represented by the bot. Returns True on success.", + "params": [ + { + "name": "UserID", + "json_name": "user_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Unique identifier of the target user" + }, + { + "name": "CustomDescription", + "json_name": "custom_description", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Custom description for the verification; 0-70 characters. Must be empty if the organization isn't allowed to provide a custom verification description." + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "verifyChat", + "doc": "Verifies a chat on behalf of the organization which is represented by the bot. Returns True on success.", + "params": [ + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username. Channel direct messages chats can't be verified." + }, + { + "name": "CustomDescription", + "json_name": "custom_description", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Custom description for the verification; 0-70 characters. Must be empty if the organization isn't allowed to provide a custom verification description." + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "removeUserVerification", + "doc": "Removes verification from a user who is currently verified on behalf of the organization represented by the bot. Returns True on success.", + "params": [ + { + "name": "UserID", + "json_name": "user_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Unique identifier of the target user" + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "removeChatVerification", + "doc": "Removes verification from a chat that is currently verified on behalf of the organization represented by the bot. Returns True on success.", + "params": [ + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the target chat or username of the target bot or channel in the format @username" + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "readBusinessMessage", + "doc": "Marks incoming message as read on behalf of a business account. Requires the can_read_messages business bot right. Returns True on success.", + "params": [ + { + "name": "BusinessConnectionID", + "json_name": "business_connection_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique identifier of the business connection on behalf of which to read the message" + }, + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Unique identifier of the chat in which the message was received. The chat must have been active in the last 24 hours." + }, + { + "name": "MessageID", + "json_name": "message_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Unique identifier of the message to mark as read" + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "deleteBusinessMessages", + "doc": "Delete messages on behalf of a business account. Requires the can_delete_sent_messages business bot right to delete messages sent by the bot itself, or the can_delete_all_messages business bot right to delete any message. Returns True on success.", + "params": [ + { + "name": "BusinessConnectionID", + "json_name": "business_connection_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique identifier of the business connection on behalf of which to delete the messages" + }, + { + "name": "MessageIds", + "json_name": "message_ids", + "type": { + "kind": "array", + "elem_type": { + "kind": "primitive", + "name": "int64" + } + }, + "required": true, + "doc": "A JSON-serialized list of 1-100 identifiers of messages to delete. All messages must be from the same chat. See deleteMessage for limitations on which messages can be deleted" + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "setBusinessAccountName", + "doc": "Changes the first and last name of a managed business account. Requires the can_change_name business bot right. Returns True on success.", + "params": [ + { + "name": "BusinessConnectionID", + "json_name": "business_connection_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique identifier of the business connection" + }, + { + "name": "FirstName", + "json_name": "first_name", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "The new value of the first name for the business account; 1-64 characters" + }, + { + "name": "LastName", + "json_name": "last_name", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "The new value of the last name for the business account; 0-64 characters" + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "setBusinessAccountUsername", + "doc": "Changes the username of a managed business account. Requires the can_change_username business bot right. Returns True on success.", + "params": [ + { + "name": "BusinessConnectionID", + "json_name": "business_connection_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique identifier of the business connection" + }, + { + "name": "Username", + "json_name": "username", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "The new value of the username for the business account; 0-32 characters" + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "setBusinessAccountBio", + "doc": "Changes the bio of a managed business account. Requires the can_change_bio business bot right. Returns True on success.", + "params": [ + { + "name": "BusinessConnectionID", + "json_name": "business_connection_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique identifier of the business connection" + }, + { + "name": "Bio", + "json_name": "bio", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "The new value of the bio for the business account; 0-140 characters" + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "setBusinessAccountProfilePhoto", + "doc": "Changes the profile photo of a managed business account. Requires the can_edit_profile_photo business bot right. Returns True on success.", + "params": [ + { + "name": "BusinessConnectionID", + "json_name": "business_connection_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique identifier of the business connection" + }, + { + "name": "Photo", + "json_name": "photo", + "type": { + "kind": "named", + "name": "InputProfilePhoto" + }, + "required": true, + "doc": "The new profile photo to set" + }, + { + "name": "IsPublic", + "json_name": "is_public", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True to set the public photo, which will be visible even if the main photo is hidden by the business account's privacy settings. An account can have only one public photo." + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "removeBusinessAccountProfilePhoto", + "doc": "Removes the current profile photo of a managed business account. Requires the can_edit_profile_photo business bot right. Returns True on success.", + "params": [ + { + "name": "BusinessConnectionID", + "json_name": "business_connection_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique identifier of the business connection" + }, + { + "name": "IsPublic", + "json_name": "is_public", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True to remove the public photo, which is visible even if the main photo is hidden by the business account's privacy settings. After the main photo is removed, the previous profile photo (if present) becomes the main photo." + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "setBusinessAccountGiftSettings", + "doc": "Changes the privacy settings pertaining to incoming gifts in a managed business account. Requires the can_change_gift_settings business bot right. Returns True on success.", + "params": [ + { + "name": "BusinessConnectionID", + "json_name": "business_connection_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique identifier of the business connection" + }, + { + "name": "ShowGiftButton", + "json_name": "show_gift_button", + "type": { + "kind": "primitive", + "name": "bool" + }, + "required": true, + "doc": "Pass True, if a button for sending a gift to the user or by the business account must always be shown in the input field" + }, + { + "name": "AcceptedGiftTypes", + "json_name": "accepted_gift_types", + "type": { + "kind": "named", + "name": "AcceptedGiftTypes" + }, + "required": true, + "doc": "Types of gifts accepted by the business account" + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "getBusinessAccountStarBalance", + "doc": "Returns the amount of Telegram Stars owned by a managed business account. Requires the can_view_gifts_and_stars business bot right. Returns StarAmount on success.", + "params": [ + { + "name": "BusinessConnectionID", + "json_name": "business_connection_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique identifier of the business connection" + } + ], + "returns": { + "kind": "named", + "name": "StarAmount" + } + }, + { + "name": "transferBusinessAccountStars", + "doc": "Transfers Telegram Stars from the business account balance to the bot's balance. Requires the can_transfer_stars business bot right. Returns True on success.", + "params": [ + { + "name": "BusinessConnectionID", + "json_name": "business_connection_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique identifier of the business connection" + }, + { + "name": "StarCount", + "json_name": "star_count", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Number of Telegram Stars to transfer; 1-10000" + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "getBusinessAccountGifts", + "doc": "Returns the gifts received and owned by a managed business account. Requires the can_view_gifts_and_stars business bot right. Returns OwnedGifts on success.", + "params": [ + { + "name": "BusinessConnectionID", + "json_name": "business_connection_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique identifier of the business connection" + }, + { + "name": "ExcludeUnsaved", + "json_name": "exclude_unsaved", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True to exclude gifts that aren't saved to the account's profile page" + }, + { + "name": "ExcludeSaved", + "json_name": "exclude_saved", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True to exclude gifts that are saved to the account's profile page" + }, + { + "name": "ExcludeUnlimited", + "json_name": "exclude_unlimited", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True to exclude gifts that can be purchased an unlimited number of times" + }, + { + "name": "ExcludeLimitedUpgradable", + "json_name": "exclude_limited_upgradable", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True to exclude gifts that can be purchased a limited number of times and can be upgraded to unique" + }, + { + "name": "ExcludeLimitedNonUpgradable", + "json_name": "exclude_limited_non_upgradable", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True to exclude gifts that can be purchased a limited number of times and can't be upgraded to unique" + }, + { + "name": "ExcludeUnique", + "json_name": "exclude_unique", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True to exclude unique gifts" + }, + { + "name": "ExcludeFromBlockchain", + "json_name": "exclude_from_blockchain", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True to exclude gifts that were assigned from the TON blockchain and can't be resold or transferred in Telegram" + }, + { + "name": "SortByPrice", + "json_name": "sort_by_price", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True to sort results by gift price instead of send date. Sorting is applied before pagination." + }, + { + "name": "Offset", + "json_name": "offset", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Offset of the first entry to return as received from the previous request; use empty string to get the first chunk of results" + }, + { + "name": "Limit", + "json_name": "limit", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "The maximum number of gifts to be returned; 1-100. Defaults to 100" + } + ], + "returns": { + "kind": "named", + "name": "OwnedGifts" + } + }, + { + "name": "getUserGifts", + "doc": "Returns the gifts owned and hosted by a user. Returns OwnedGifts on success.", + "params": [ + { + "name": "UserID", + "json_name": "user_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Unique identifier of the user" + }, + { + "name": "ExcludeUnlimited", + "json_name": "exclude_unlimited", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True to exclude gifts that can be purchased an unlimited number of times" + }, + { + "name": "ExcludeLimitedUpgradable", + "json_name": "exclude_limited_upgradable", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True to exclude gifts that can be purchased a limited number of times and can be upgraded to unique" + }, + { + "name": "ExcludeLimitedNonUpgradable", + "json_name": "exclude_limited_non_upgradable", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True to exclude gifts that can be purchased a limited number of times and can't be upgraded to unique" + }, + { + "name": "ExcludeFromBlockchain", + "json_name": "exclude_from_blockchain", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True to exclude gifts that were assigned from the TON blockchain and can't be resold or transferred in Telegram" + }, + { + "name": "ExcludeUnique", + "json_name": "exclude_unique", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True to exclude unique gifts" + }, + { + "name": "SortByPrice", + "json_name": "sort_by_price", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True to sort results by gift price instead of send date. Sorting is applied before pagination." + }, + { + "name": "Offset", + "json_name": "offset", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Offset of the first entry to return as received from the previous request; use an empty string to get the first chunk of results" + }, + { + "name": "Limit", + "json_name": "limit", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "The maximum number of gifts to be returned; 1-100. Defaults to 100" + } + ], + "returns": { + "kind": "named", + "name": "OwnedGifts" + } + }, + { + "name": "getChatGifts", + "doc": "Returns the gifts owned by a chat. Returns OwnedGifts on success.", + "params": [ + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the target chat or username of the target channel in the format @username" + }, + { + "name": "ExcludeUnsaved", + "json_name": "exclude_unsaved", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True to exclude gifts that aren't saved to the chat's profile page. Always True, unless the bot has the can_post_messages administrator right in the channel." + }, + { + "name": "ExcludeSaved", + "json_name": "exclude_saved", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True to exclude gifts that are saved to the chat's profile page. Always False, unless the bot has the can_post_messages administrator right in the channel." + }, + { + "name": "ExcludeUnlimited", + "json_name": "exclude_unlimited", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True to exclude gifts that can be purchased an unlimited number of times" + }, + { + "name": "ExcludeLimitedUpgradable", + "json_name": "exclude_limited_upgradable", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True to exclude gifts that can be purchased a limited number of times and can be upgraded to unique" + }, + { + "name": "ExcludeLimitedNonUpgradable", + "json_name": "exclude_limited_non_upgradable", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True to exclude gifts that can be purchased a limited number of times and can't be upgraded to unique" + }, + { + "name": "ExcludeFromBlockchain", + "json_name": "exclude_from_blockchain", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True to exclude gifts that were assigned from the TON blockchain and can't be resold or transferred in Telegram" + }, + { + "name": "ExcludeUnique", + "json_name": "exclude_unique", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True to exclude unique gifts" + }, + { + "name": "SortByPrice", + "json_name": "sort_by_price", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True to sort results by gift price instead of send date. Sorting is applied before pagination." + }, + { + "name": "Offset", + "json_name": "offset", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Offset of the first entry to return as received from the previous request; use an empty string to get the first chunk of results" + }, + { + "name": "Limit", + "json_name": "limit", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "The maximum number of gifts to be returned; 1-100. Defaults to 100" + } + ], + "returns": { + "kind": "named", + "name": "OwnedGifts" + } + }, + { + "name": "convertGiftToStars", + "doc": "Converts a given regular gift to Telegram Stars. Requires the can_convert_gifts_to_stars business bot right. Returns True on success.", + "params": [ + { + "name": "BusinessConnectionID", + "json_name": "business_connection_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique identifier of the business connection" + }, + { + "name": "OwnedGiftID", + "json_name": "owned_gift_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique identifier of the regular gift that should be converted to Telegram Stars" + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "upgradeGift", + "doc": "Upgrades a given regular gift to a unique gift. Requires the can_transfer_and_upgrade_gifts business bot right. Additionally requires the can_transfer_stars business bot right if the upgrade is paid. Returns True on success.", + "params": [ + { + "name": "BusinessConnectionID", + "json_name": "business_connection_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique identifier of the business connection" + }, + { + "name": "OwnedGiftID", + "json_name": "owned_gift_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique identifier of the regular gift that should be upgraded to a unique one" + }, + { + "name": "KeepOriginalDetails", + "json_name": "keep_original_details", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True to keep the original gift text, sender and receiver in the upgraded gift" + }, + { + "name": "StarCount", + "json_name": "star_count", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "The amount of Telegram Stars that will be paid for the upgrade from the business account balance. If gift.prepaid_upgrade_star_count > 0, then pass 0, otherwise, the can_transfer_stars business bot right is required and gift.upgrade_star_count must be passed." + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "transferGift", + "doc": "Transfers an owned unique gift to another user. Requires the can_transfer_and_upgrade_gifts business bot right. Requires can_transfer_stars business bot right if the transfer is paid. Returns True on success.", + "params": [ + { + "name": "BusinessConnectionID", + "json_name": "business_connection_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique identifier of the business connection" + }, + { + "name": "OwnedGiftID", + "json_name": "owned_gift_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique identifier of the regular gift that should be transferred" + }, + { + "name": "NewOwnerChatID", + "json_name": "new_owner_chat_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Unique identifier of the chat which will own the gift. The chat must be active in the last 24 hours." + }, + { + "name": "StarCount", + "json_name": "star_count", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "The amount of Telegram Stars that will be paid for the transfer from the business account balance. If positive, then the can_transfer_stars business bot right is required." + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "postStory", + "doc": "Posts a story on behalf of a managed business account. Requires the can_manage_stories business bot right. Returns Story on success.", + "params": [ + { + "name": "BusinessConnectionID", + "json_name": "business_connection_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique identifier of the business connection" + }, + { + "name": "Content", + "json_name": "content", + "type": { + "kind": "named", + "name": "InputStoryContent" + }, + "required": true, + "doc": "Content of the story" + }, + { + "name": "ActivePeriod", + "json_name": "active_period", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Period after which the story is moved to the archive, in seconds; must be one of 6 * 3600, 12 * 3600, 86400, or 2 * 86400" + }, + { + "name": "Caption", + "json_name": "caption", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Caption of the story, 0-2048 characters after entities parsing" + }, + { + "name": "ParseMode", + "json_name": "parse_mode", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Mode for parsing entities in the story caption. See formatting options for more details." + }, + { + "name": "CaptionEntities", + "json_name": "caption_entities", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "MessageEntity" + } + }, + "doc": "A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode" + }, + { + "name": "Areas", + "json_name": "areas", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "StoryArea" + } + }, + "doc": "A JSON-serialized list of clickable areas to be shown on the story" + }, + { + "name": "PostToChatPage", + "json_name": "post_to_chat_page", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True to keep the story accessible after it expires" + }, + { + "name": "ProtectContent", + "json_name": "protect_content", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True if the content of the story must be protected from forwarding and screenshotting" + } + ], + "returns": { + "kind": "named", + "name": "Story" + } + }, + { + "name": "repostStory", + "doc": "Reposts a story on behalf of a business account from another business account. Both business accounts must be managed by the same bot, and the story on the source account must have been posted (or reposted) by the bot. Requires the can_manage_stories business bot right for both business accounts. Returns Story on success.", + "params": [ + { + "name": "BusinessConnectionID", + "json_name": "business_connection_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique identifier of the business connection" + }, + { + "name": "FromChatID", + "json_name": "from_chat_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Unique identifier of the chat which posted the story that should be reposted" + }, + { + "name": "FromStoryID", + "json_name": "from_story_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Unique identifier of the story that should be reposted" + }, + { + "name": "ActivePeriod", + "json_name": "active_period", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Period after which the story is moved to the archive, in seconds; must be one of 6 * 3600, 12 * 3600, 86400, or 2 * 86400" + }, + { + "name": "PostToChatPage", + "json_name": "post_to_chat_page", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True to keep the story accessible after it expires" + }, + { + "name": "ProtectContent", + "json_name": "protect_content", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True if the content of the story must be protected from forwarding and screenshotting" + } + ], + "returns": { + "kind": "named", + "name": "Story" + } + }, + { + "name": "editStory", + "doc": "Edits a story previously posted by the bot on behalf of a managed business account. Requires the can_manage_stories business bot right. Returns Story on success.", + "params": [ + { + "name": "BusinessConnectionID", + "json_name": "business_connection_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique identifier of the business connection" + }, + { + "name": "StoryID", + "json_name": "story_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Unique identifier of the story to edit" + }, + { + "name": "Content", + "json_name": "content", + "type": { + "kind": "named", + "name": "InputStoryContent" + }, + "required": true, + "doc": "Content of the story" + }, + { + "name": "Caption", + "json_name": "caption", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Caption of the story, 0-2048 characters after entities parsing" + }, + { + "name": "ParseMode", + "json_name": "parse_mode", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Mode for parsing entities in the story caption. See formatting options for more details." + }, + { + "name": "CaptionEntities", + "json_name": "caption_entities", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "MessageEntity" + } + }, + "doc": "A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode" + }, + { + "name": "Areas", + "json_name": "areas", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "StoryArea" + } + }, + "doc": "A JSON-serialized list of clickable areas to be shown on the story" + } + ], + "returns": { + "kind": "named", + "name": "Story" + } + }, + { + "name": "deleteStory", + "doc": "Deletes a story previously posted by the bot on behalf of a managed business account. Requires the can_manage_stories business bot right. Returns True on success.", + "params": [ + { + "name": "BusinessConnectionID", + "json_name": "business_connection_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique identifier of the business connection" + }, + { + "name": "StoryID", + "json_name": "story_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Unique identifier of the story to delete" + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "answerWebAppQuery", + "doc": "Use this method to set the result of an interaction with a Web App and send a corresponding message on behalf of the user to the chat from which the query originated. On success, a SentWebAppMessage object is returned.", + "params": [ + { + "name": "WebAppQueryID", + "json_name": "web_app_query_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique identifier for the query to be answered" + }, + { + "name": "Result", + "json_name": "result", + "type": { + "kind": "named", + "name": "InlineQueryResult" + }, + "required": true, + "doc": "A JSON-serialized object describing the message to be sent" + } + ], + "returns": { + "kind": "named", + "name": "SentWebAppMessage" + } + }, + { + "name": "savePreparedInlineMessage", + "doc": "Stores a message that can be sent by a user of a Mini App. Returns a PreparedInlineMessage object.", + "params": [ + { + "name": "UserID", + "json_name": "user_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Unique identifier of the target user that can use the prepared message" + }, + { + "name": "Result", + "json_name": "result", + "type": { + "kind": "named", + "name": "InlineQueryResult" + }, + "required": true, + "doc": "A JSON-serialized object describing the message to be sent" + }, + { + "name": "AllowUserChats", + "json_name": "allow_user_chats", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True if the message can be sent to private chats with users" + }, + { + "name": "AllowBotChats", + "json_name": "allow_bot_chats", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True if the message can be sent to private chats with bots" + }, + { + "name": "AllowGroupChats", + "json_name": "allow_group_chats", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True if the message can be sent to group and supergroup chats" + }, + { + "name": "AllowChannelChats", + "json_name": "allow_channel_chats", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True if the message can be sent to channel chats" + } + ], + "returns": { + "kind": "named", + "name": "PreparedInlineMessage" + } + }, + { + "name": "savePreparedKeyboardButton", + "doc": "Stores a keyboard button that can be used by a user within a Mini App. Returns a PreparedKeyboardButton object.", + "params": [ + { + "name": "UserID", + "json_name": "user_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Unique identifier of the target user that can use the button" + }, + { + "name": "Button", + "json_name": "button", + "type": { + "kind": "named", + "name": "KeyboardButton" + }, + "required": true, + "doc": "A JSON-serialized object describing the button to be saved. The button must be of the type request_users, request_chat, or request_managed_bot" + } + ], + "returns": { + "kind": "named", + "name": "PreparedKeyboardButton" + } + }, + { + "name": "editMessageText", + "doc": "Use this method to edit text and game messages. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. Note that business messages that were not sent by the bot and do not contain an inline keyboard can only be edited within 48 hours from the time they were sent.", + "params": [ + { + "name": "BusinessConnectionID", + "json_name": "business_connection_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Unique identifier of the business connection on behalf of which the message to be edited was sent" + }, + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "doc": "Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username." + }, + { + "name": "MessageID", + "json_name": "message_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Required if inline_message_id is not specified. Identifier of the message to edit" + }, + { + "name": "InlineMessageID", + "json_name": "inline_message_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Required if chat_id and message_id are not specified. Identifier of the inline message" + }, + { + "name": "Text", + "json_name": "text", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "New text of the message, 1-4096 characters after entities parsing" + }, + { + "name": "ParseMode", + "json_name": "parse_mode", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Mode for parsing entities in the message text. See formatting options for more details." + }, + { + "name": "Entities", + "json_name": "entities", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "MessageEntity" + } + }, + "doc": "A JSON-serialized list of special entities that appear in message text, which can be specified instead of parse_mode" + }, + { + "name": "LinkPreviewOptions", + "json_name": "link_preview_options", + "type": { + "kind": "named", + "name": "LinkPreviewOptions" + }, + "doc": "Link preview generation options for the message" + }, + { + "name": "ReplyMarkup", + "json_name": "reply_markup", + "type": { + "kind": "named", + "name": "InlineKeyboardMarkup" + }, + "doc": "A JSON-serialized object for an inline keyboard." + } + ], + "returns": { + "kind": "named", + "name": "MessageOrBool" + } + }, + { + "name": "editMessageCaption", + "doc": "Use this method to edit captions of messages. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. Note that business messages that were not sent by the bot and do not contain an inline keyboard can only be edited within 48 hours from the time they were sent.", + "params": [ + { + "name": "BusinessConnectionID", + "json_name": "business_connection_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Unique identifier of the business connection on behalf of which the message to be edited was sent" + }, + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "doc": "Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username." + }, + { + "name": "MessageID", + "json_name": "message_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Required if inline_message_id is not specified. Identifier of the message to edit" + }, + { + "name": "InlineMessageID", + "json_name": "inline_message_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Required if chat_id and message_id are not specified. Identifier of the inline message" + }, + { + "name": "Caption", + "json_name": "caption", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "New caption of the message, 0-1024 characters after entities parsing" + }, + { + "name": "ParseMode", + "json_name": "parse_mode", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Mode for parsing entities in the message caption. See formatting options for more details." + }, + { + "name": "CaptionEntities", + "json_name": "caption_entities", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "MessageEntity" + } + }, + "doc": "A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode" + }, + { + "name": "ShowCaptionAboveMedia", + "json_name": "show_caption_above_media", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True, if the caption must be shown above the message media. Supported only for animation, photo and video messages." + }, + { + "name": "ReplyMarkup", + "json_name": "reply_markup", + "type": { + "kind": "named", + "name": "InlineKeyboardMarkup" + }, + "doc": "A JSON-serialized object for an inline keyboard." + } + ], + "returns": { + "kind": "named", + "name": "MessageOrBool" + } + }, + { + "name": "editMessageMedia", + "doc": "Use this method to edit animation, audio, document, live photo, photo, or video messages, or to add media to text messages. If a message is part of a message album, then it can be edited only to an audio for audio albums, only to a document for document albums and to a photo, a live photo, or a video otherwise. When an inline message is edited, a new file can't be uploaded; use a previously uploaded file via its file_id or specify a URL. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. Note that business messages that were not sent by the bot and do not contain an inline keyboard can only be edited within 48 hours from the time they were sent.", + "params": [ + { + "name": "BusinessConnectionID", + "json_name": "business_connection_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Unique identifier of the business connection on behalf of which the message to be edited was sent" + }, + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "doc": "Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username." + }, + { + "name": "MessageID", + "json_name": "message_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Required if inline_message_id is not specified. Identifier of the message to edit" + }, + { + "name": "InlineMessageID", + "json_name": "inline_message_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Required if chat_id and message_id are not specified. Identifier of the inline message" + }, + { + "name": "Media", + "json_name": "media", + "type": { + "kind": "named", + "name": "InputMedia" + }, + "required": true, + "doc": "A JSON-serialized object for a new media content of the message" + }, + { + "name": "ReplyMarkup", + "json_name": "reply_markup", + "type": { + "kind": "named", + "name": "InlineKeyboardMarkup" + }, + "doc": "A JSON-serialized object for a new inline keyboard." + } + ], + "returns": { + "kind": "named", + "name": "MessageOrBool" + }, + "has_files": true + }, + { + "name": "editMessageLiveLocation", + "doc": "Use this method to edit live location messages. A location can be edited until its live_period expires or editing is explicitly disabled by a call to stopMessageLiveLocation. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned.", + "params": [ + { + "name": "BusinessConnectionID", + "json_name": "business_connection_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Unique identifier of the business connection on behalf of which the message to be edited was sent" + }, + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "doc": "Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username." + }, + { + "name": "MessageID", + "json_name": "message_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Required if inline_message_id is not specified. Identifier of the message to edit" + }, + { + "name": "InlineMessageID", + "json_name": "inline_message_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Required if chat_id and message_id are not specified. Identifier of the inline message" + }, + { + "name": "Latitude", + "json_name": "latitude", + "type": { + "kind": "primitive", + "name": "float64" + }, + "required": true, + "doc": "Latitude of new location" + }, + { + "name": "Longitude", + "json_name": "longitude", + "type": { + "kind": "primitive", + "name": "float64" + }, + "required": true, + "doc": "Longitude of new location" + }, + { + "name": "LivePeriod", + "json_name": "live_period", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "New period in seconds during which the location can be updated, starting from the message send date. If 0x7FFFFFFF is specified, then the location can be updated forever. Otherwise, the new value must not exceed the current live_period by more than a day, and the live location expiration date must remain within the next 90 days. If not specified, then live_period remains unchanged" + }, + { + "name": "HorizontalAccuracy", + "json_name": "horizontal_accuracy", + "type": { + "kind": "primitive", + "name": "float64" + }, + "doc": "The radius of uncertainty for the location, measured in meters; 0-1500" + }, + { + "name": "Heading", + "json_name": "heading", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Direction in which the user is moving, in degrees. Must be between 1 and 360 if specified." + }, + { + "name": "ProximityAlertRadius", + "json_name": "proximity_alert_radius", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "The maximum distance for proximity alerts about approaching another chat member, in meters. Must be between 1 and 100000 if specified." + }, + { + "name": "ReplyMarkup", + "json_name": "reply_markup", + "type": { + "kind": "named", + "name": "InlineKeyboardMarkup" + }, + "doc": "A JSON-serialized object for a new inline keyboard." + } + ], + "returns": { + "kind": "named", + "name": "MessageOrBool" + } + }, + { + "name": "stopMessageLiveLocation", + "doc": "Use this method to stop updating a live location message before live_period expires. On success, if the message is not an inline message, the edited Message is returned, otherwise True is returned.", + "params": [ + { + "name": "BusinessConnectionID", + "json_name": "business_connection_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Unique identifier of the business connection on behalf of which the message to be edited was sent" + }, + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "doc": "Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username." + }, + { + "name": "MessageID", + "json_name": "message_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Required if inline_message_id is not specified. Identifier of the message with live location to stop" + }, + { + "name": "InlineMessageID", + "json_name": "inline_message_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Required if chat_id and message_id are not specified. Identifier of the inline message" + }, + { + "name": "ReplyMarkup", + "json_name": "reply_markup", + "type": { + "kind": "named", + "name": "InlineKeyboardMarkup" + }, + "doc": "A JSON-serialized object for a new inline keyboard." + } + ], + "returns": { + "kind": "named", + "name": "MessageOrBool" + } + }, + { + "name": "editMessageChecklist", + "doc": "Use this method to edit a checklist on behalf of a connected business account. On success, the edited Message is returned.", + "params": [ + { + "name": "BusinessConnectionID", + "json_name": "business_connection_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique identifier of the business connection on behalf of which the message will be sent" + }, + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the target chat or username of the target bot in the format @username" + }, + { + "name": "MessageID", + "json_name": "message_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Unique identifier for the target message" + }, + { + "name": "Checklist", + "json_name": "checklist", + "type": { + "kind": "named", + "name": "InputChecklist" + }, + "required": true, + "doc": "A JSON-serialized object for the new checklist" + }, + { + "name": "ReplyMarkup", + "json_name": "reply_markup", + "type": { + "kind": "named", + "name": "InlineKeyboardMarkup" + }, + "doc": "A JSON-serialized object for the new inline keyboard for the message" + } + ], + "returns": { + "kind": "named", + "name": "Message" + } + }, + { + "name": "editMessageReplyMarkup", + "doc": "Use this method to edit only the reply markup of messages. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. Note that business messages that were not sent by the bot and do not contain an inline keyboard can only be edited within 48 hours from the time they were sent.", + "params": [ + { + "name": "BusinessConnectionID", + "json_name": "business_connection_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Unique identifier of the business connection on behalf of which the message to be edited was sent" + }, + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "doc": "Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username." + }, + { + "name": "MessageID", + "json_name": "message_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Required if inline_message_id is not specified. Identifier of the message to edit" + }, + { + "name": "InlineMessageID", + "json_name": "inline_message_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Required if chat_id and message_id are not specified. Identifier of the inline message" + }, + { + "name": "ReplyMarkup", + "json_name": "reply_markup", + "type": { + "kind": "named", + "name": "InlineKeyboardMarkup" + }, + "doc": "A JSON-serialized object for an inline keyboard." + } + ], + "returns": { + "kind": "named", + "name": "MessageOrBool" + } + }, + { + "name": "stopPoll", + "doc": "Use this method to stop a poll which was sent by the bot. On success, the stopped Poll is returned.", + "params": [ + { + "name": "BusinessConnectionID", + "json_name": "business_connection_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Unique identifier of the business connection on behalf of which the message to be edited was sent" + }, + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username" + }, + { + "name": "MessageID", + "json_name": "message_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Identifier of the original message with the poll" + }, + { + "name": "ReplyMarkup", + "json_name": "reply_markup", + "type": { + "kind": "named", + "name": "InlineKeyboardMarkup" + }, + "doc": "A JSON-serialized object for a new message inline keyboard." + } + ], + "returns": { + "kind": "named", + "name": "Poll" + } + }, + { + "name": "approveSuggestedPost", + "doc": "Use this method to approve a suggested post in a direct messages chat. The bot must have the 'can_post_messages' administrator right in the corresponding channel chat. Returns True on success.", + "params": [ + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Unique identifier for the target direct messages chat" + }, + { + "name": "MessageID", + "json_name": "message_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Identifier of a suggested post message to approve" + }, + { + "name": "SendDate", + "json_name": "send_date", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Point in time (Unix timestamp) when the post is expected to be published; omit if the date has already been specified when the suggested post was created. If specified, then the date must be not more than 2678400 seconds (30 days) in the future" + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "declineSuggestedPost", + "doc": "Use this method to decline a suggested post in a direct messages chat. The bot must have the 'can_manage_direct_messages' administrator right in the corresponding channel chat. Returns True on success.", + "params": [ + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Unique identifier for the target direct messages chat" + }, + { + "name": "MessageID", + "json_name": "message_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Identifier of a suggested post message to decline" + }, + { + "name": "Comment", + "json_name": "comment", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Comment for the creator of the suggested post; 0-128 characters" + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "deleteMessage", + "doc": "Use this method to delete a message, including service messages, with the following limitations:- A message can only be deleted if it was sent less than 48 hours ago.- Service messages about a supergroup, channel, or forum topic creation can't be deleted.- A dice message in a private chat can only be deleted if it was sent more than 24 hours ago.- Bots can delete outgoing messages in private chats, groups, and supergroups.- Bots can delete incoming messages in private chats.- Bots granted can_post_messages permissions can delete outgoing messages in channels.- If the bot is an administrator of a group, it can delete any message there.- If the bot has can_delete_messages administrator right in a supergroup or a channel, it can delete any message there.- If the bot has can_manage_direct_messages administrator right in a channel, it can delete any message in the corresponding direct messages chat.Returns True on success.", + "params": [ + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username" + }, + { + "name": "MessageID", + "json_name": "message_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Identifier of the message to delete" + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "deleteMessages", + "doc": "Use this method to delete multiple messages simultaneously. If some of the specified messages can't be found, they are skipped. Returns True on success.", + "params": [ + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username" + }, + { + "name": "MessageIds", + "json_name": "message_ids", + "type": { + "kind": "array", + "elem_type": { + "kind": "primitive", + "name": "int64" + } + }, + "required": true, + "doc": "A JSON-serialized list of 1-100 identifiers of messages to delete. See deleteMessage for limitations on which messages can be deleted" + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "deleteMessageReaction", + "doc": "Use this method to remove a reaction from a message in a group or a supergroup chat. The bot must have the 'can_delete_messages' administrator right in the chat. Returns True on success.", + "params": [ + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the target chat or username of the target supergroup (in the format @username)" + }, + { + "name": "MessageID", + "json_name": "message_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Identifier of the target message" + }, + { + "name": "UserID", + "json_name": "user_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Identifier of the user whose reaction will be removed, if the reaction was added by a user" + }, + { + "name": "ActorChatID", + "json_name": "actor_chat_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Identifier of the chat whose reaction will be removed, if the reaction was added by a chat" + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "deleteAllMessageReactions", + "doc": "Use this method to remove up to 10000 recent reactions in a group or a supergroup chat added by a given user or chat. The bot must have the 'can_delete_messages' administrator right in the chat. Returns True on success.", + "params": [ + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the target chat or username of the target supergroup (in the format @username)" + }, + { + "name": "UserID", + "json_name": "user_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Identifier of the user whose reactions will be removed, if the reactions were added by a user" + }, + { + "name": "ActorChatID", + "json_name": "actor_chat_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Identifier of the chat whose reactions will be removed, if the reactions were added by a chat" + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "sendSticker", + "doc": "Use this method to send static .WEBP, animated .TGS, or video .WEBM stickers. On success, the sent Message is returned.", + "params": [ + { + "name": "BusinessConnectionID", + "json_name": "business_connection_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Unique identifier of the business connection on behalf of which the message will be sent" + }, + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username" + }, + { + "name": "MessageThreadID", + "json_name": "message_thread_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only" + }, + { + "name": "DirectMessagesTopicID", + "json_name": "direct_messages_topic_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Identifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat" + }, + { + "name": "Sticker", + "json_name": "sticker", + "type": { + "kind": "oneOf", + "variants": [ + "InputFile", + "string" + ] + }, + "required": true, + "doc": "Sticker to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a .WEBP sticker from the Internet, or upload a new .WEBP, .TGS, or .WEBM sticker using multipart/form-data. More information on Sending Files ». Video and animated stickers can't be sent via an HTTP URL." + }, + { + "name": "Emoji", + "json_name": "emoji", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Emoji associated with the sticker; only for just uploaded stickers" + }, + { + "name": "DisableNotification", + "json_name": "disable_notification", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Sends the message silently. Users will receive a notification with no sound." + }, + { + "name": "ProtectContent", + "json_name": "protect_content", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Protects the contents of the sent message from forwarding and saving" + }, + { + "name": "AllowPaidBroadcast", + "json_name": "allow_paid_broadcast", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance." + }, + { + "name": "MessageEffectID", + "json_name": "message_effect_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Unique identifier of the message effect to be added to the message; for private chats only" + }, + { + "name": "SuggestedPostParameters", + "json_name": "suggested_post_parameters", + "type": { + "kind": "named", + "name": "SuggestedPostParameters" + }, + "doc": "A JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined." + }, + { + "name": "ReplyParameters", + "json_name": "reply_parameters", + "type": { + "kind": "named", + "name": "ReplyParameters" + }, + "doc": "Description of the message to reply to" + }, + { + "name": "ReplyMarkup", + "json_name": "reply_markup", + "type": { + "kind": "oneOf", + "variants": [ + "InlineKeyboardMarkup", + "ReplyKeyboardMarkup", + "ReplyKeyboardRemove", + "ForceReply" + ] + }, + "doc": "Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user" + } + ], + "returns": { + "kind": "named", + "name": "Message" + }, + "has_files": true + }, + { + "name": "getStickerSet", + "doc": "Use this method to get a sticker set. On success, a StickerSet object is returned.", + "params": [ + { + "name": "Name", + "json_name": "name", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Name of the sticker set" + } + ], + "returns": { + "kind": "named", + "name": "StickerSet" + } + }, + { + "name": "getCustomEmojiStickers", + "doc": "Use this method to get information about custom emoji stickers by their identifiers. Returns an Array of Sticker objects.", + "params": [ + { + "name": "CustomEmojiIds", + "json_name": "custom_emoji_ids", + "type": { + "kind": "array", + "elem_type": { + "kind": "primitive", + "name": "string" + } + }, + "required": true, + "doc": "A JSON-serialized list of custom emoji identifiers. At most 200 custom emoji identifiers can be specified." + } + ], + "returns": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "Sticker" + } + } + }, + { + "name": "uploadStickerFile", + "doc": "Use this method to upload a file with a sticker for later use in the createNewStickerSet, addStickerToSet, or replaceStickerInSet methods (the file can be used multiple times). Returns the uploaded File on success.", + "params": [ + { + "name": "UserID", + "json_name": "user_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "User identifier of sticker file owner" + }, + { + "name": "Sticker", + "json_name": "sticker", + "type": { + "kind": "named", + "name": "InputFile" + }, + "required": true, + "doc": "A file with the sticker in .WEBP, .PNG, .TGS, or .WEBM format. See https://core.telegram.org/stickers for technical requirements. More information on Sending Files »" + }, + { + "name": "StickerFormat", + "json_name": "sticker_format", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Format of the sticker, must be one of “static”, “animated”, “video”" + } + ], + "returns": { + "kind": "named", + "name": "File" + }, + "has_files": true + }, + { + "name": "createNewStickerSet", + "doc": "Use this method to create a new sticker set owned by a user. The bot will be able to edit the sticker set thus created. Returns True on success.", + "params": [ + { + "name": "UserID", + "json_name": "user_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "User identifier of created sticker set owner" + }, + { + "name": "Name", + "json_name": "name", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Short name of sticker set, to be used in t.me/addstickers/ URLs (e.g., animals). Can contain only English letters, digits and underscores. Must begin with a letter, can't contain consecutive underscores and must end in \"_by_\". is case insensitive. 1-64 characters." + }, + { + "name": "Title", + "json_name": "title", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Sticker set title, 1-64 characters" + }, + { + "name": "Stickers", + "json_name": "stickers", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "InputSticker" + } + }, + "required": true, + "doc": "A JSON-serialized list of 1-50 initial stickers to be added to the sticker set" + }, + { + "name": "StickerType", + "json_name": "sticker_type", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Type of stickers in the set, pass “regular”, “mask”, or “custom_emoji”. By default, a regular sticker set is created." + }, + { + "name": "NeedsRepainting", + "json_name": "needs_repainting", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True if stickers in the sticker set must be repainted to the color of text when used in messages, the accent color if used as emoji status, white on chat photos, or another appropriate color based on context; for custom emoji sticker sets only" + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "addStickerToSet", + "doc": "Use this method to add a new sticker to a set created by the bot. Emoji sticker sets can have up to 200 stickers. Other sticker sets can have up to 120 stickers. Returns True on success.", + "params": [ + { + "name": "UserID", + "json_name": "user_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "User identifier of sticker set owner" + }, + { + "name": "Name", + "json_name": "name", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Sticker set name" + }, + { + "name": "Sticker", + "json_name": "sticker", + "type": { + "kind": "named", + "name": "InputSticker" + }, + "required": true, + "doc": "A JSON-serialized object with information about the added sticker. If exactly the same sticker had already been added to the set, then the set isn't changed." + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "setStickerPositionInSet", + "doc": "Use this method to move a sticker in a set created by the bot to a specific position. Returns True on success.", + "params": [ + { + "name": "Sticker", + "json_name": "sticker", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "File identifier of the sticker" + }, + { + "name": "Position", + "json_name": "position", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "New sticker position in the set, zero-based" + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "deleteStickerFromSet", + "doc": "Use this method to delete a sticker from a set created by the bot. Returns True on success.", + "params": [ + { + "name": "Sticker", + "json_name": "sticker", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "File identifier of the sticker" + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "replaceStickerInSet", + "doc": "Use this method to replace an existing sticker in a sticker set with a new one. The method is equivalent to calling deleteStickerFromSet, then addStickerToSet, then setStickerPositionInSet. Returns True on success.", + "params": [ + { + "name": "UserID", + "json_name": "user_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "User identifier of the sticker set owner" + }, + { + "name": "Name", + "json_name": "name", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Sticker set name" + }, + { + "name": "OldSticker", + "json_name": "old_sticker", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "File identifier of the replaced sticker" + }, + { + "name": "Sticker", + "json_name": "sticker", + "type": { + "kind": "named", + "name": "InputSticker" + }, + "required": true, + "doc": "A JSON-serialized object with information about the added sticker. If exactly the same sticker had already been added to the set, then the set remains unchanged." + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "setStickerEmojiList", + "doc": "Use this method to change the list of emoji assigned to a regular or custom emoji sticker. The sticker must belong to a sticker set created by the bot. Returns True on success.", + "params": [ + { + "name": "Sticker", + "json_name": "sticker", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "File identifier of the sticker" + }, + { + "name": "EmojiList", + "json_name": "emoji_list", + "type": { + "kind": "array", + "elem_type": { + "kind": "primitive", + "name": "string" + } + }, + "required": true, + "doc": "A JSON-serialized list of 1-20 emoji associated with the sticker" + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "setStickerKeywords", + "doc": "Use this method to change search keywords assigned to a regular or custom emoji sticker. The sticker must belong to a sticker set created by the bot. Returns True on success.", + "params": [ + { + "name": "Sticker", + "json_name": "sticker", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "File identifier of the sticker" + }, + { + "name": "Keywords", + "json_name": "keywords", + "type": { + "kind": "array", + "elem_type": { + "kind": "primitive", + "name": "string" + } + }, + "doc": "A JSON-serialized list of 0-20 search keywords for the sticker with total length of up to 64 characters" + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "setStickerMaskPosition", + "doc": "Use this method to change the mask position of a mask sticker. The sticker must belong to a sticker set that was created by the bot. Returns True on success.", + "params": [ + { + "name": "Sticker", + "json_name": "sticker", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "File identifier of the sticker" + }, + { + "name": "MaskPosition", + "json_name": "mask_position", + "type": { + "kind": "named", + "name": "MaskPosition" + }, + "doc": "A JSON-serialized object with the position where the mask should be placed on faces. Omit the parameter to remove the mask position." + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "setStickerSetTitle", + "doc": "Use this method to set the title of a created sticker set. Returns True on success.", + "params": [ + { + "name": "Name", + "json_name": "name", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Sticker set name" + }, + { + "name": "Title", + "json_name": "title", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Sticker set title, 1-64 characters" + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "setStickerSetThumbnail", + "doc": "Use this method to set the thumbnail of a regular or mask sticker set. The format of the thumbnail file must match the format of the stickers in the set. Returns True on success.", + "params": [ + { + "name": "Name", + "json_name": "name", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Sticker set name" + }, + { + "name": "UserID", + "json_name": "user_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "User identifier of the sticker set owner" + }, + { + "name": "Thumbnail", + "json_name": "thumbnail", + "type": { + "kind": "oneOf", + "variants": [ + "InputFile", + "string" + ] + }, + "doc": "A .WEBP or .PNG image with the thumbnail, must be up to 128 kilobytes in size and have a width and height of exactly 100px, or a .TGS animation with a thumbnail up to 32 kilobytes in size (see https://core.telegram.org/stickers#animation-requirements for animated sticker technical requirements), or a .WEBM video with the thumbnail up to 32 kilobytes in size; see https://core.telegram.org/stickers#video-requirements for video sticker technical requirements. Pass a file_id as a String to send a file that already exists on the Telegram servers, pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files ». Animated and video sticker set thumbnails can't be uploaded via HTTP URL. If omitted, then the thumbnail is dropped and the first sticker is used as the thumbnail." + }, + { + "name": "Format", + "json_name": "format", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Format of the thumbnail, must be one of “static” for a .WEBP or .PNG image, “animated” for a .TGS animation, or “video” for a .WEBM video" + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + }, + "has_files": true + }, + { + "name": "setCustomEmojiStickerSetThumbnail", + "doc": "Use this method to set the thumbnail of a custom emoji sticker set. Returns True on success.", + "params": [ + { + "name": "Name", + "json_name": "name", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Sticker set name" + }, + { + "name": "CustomEmojiID", + "json_name": "custom_emoji_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Custom emoji identifier of a sticker from the sticker set; pass an empty string to drop the thumbnail and use the first sticker as the thumbnail." + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "deleteStickerSet", + "doc": "Use this method to delete a sticker set that was created by the bot. Returns True on success.", + "params": [ + { + "name": "Name", + "json_name": "name", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Sticker set name" + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "answerInlineQuery", + "doc": "Use this method to send answers to an inline query. On success, True is returned.No more than 50 results per query are allowed.", + "params": [ + { + "name": "InlineQueryID", + "json_name": "inline_query_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique identifier for the answered query" + }, + { + "name": "Results", + "json_name": "results", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "InlineQueryResult" + } + }, + "required": true, + "doc": "A JSON-serialized array of results for the inline query" + }, + { + "name": "CacheTime", + "json_name": "cache_time", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "The maximum amount of time in seconds that the result of the inline query may be cached on the server. Defaults to 300." + }, + { + "name": "IsPersonal", + "json_name": "is_personal", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True if results may be cached on the server side only for the user that sent the query. By default, results may be returned to any user who sends the same query." + }, + { + "name": "NextOffset", + "json_name": "next_offset", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Pass the offset that a client should send in the next query with the same text to receive more results. Pass an empty string if there are no more results or if you don't support pagination. Offset length can't exceed 64 bytes." + }, + { + "name": "Button", + "json_name": "button", + "type": { + "kind": "named", + "name": "InlineQueryResultsButton" + }, + "doc": "A JSON-serialized object describing a button to be shown above inline query results" + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "sendInvoice", + "doc": "Use this method to send invoices. On success, the sent Message is returned.", + "params": [ + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username" + }, + { + "name": "MessageThreadID", + "json_name": "message_thread_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only" + }, + { + "name": "DirectMessagesTopicID", + "json_name": "direct_messages_topic_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Identifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat" + }, + { + "name": "Title", + "json_name": "title", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Product name, 1-32 characters" + }, + { + "name": "Description", + "json_name": "description", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Product description, 1-255 characters" + }, + { + "name": "Payload", + "json_name": "payload", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Bot-defined invoice payload, 1-128 bytes. This will not be displayed to the user, use it for your internal processes." + }, + { + "name": "ProviderToken", + "json_name": "provider_token", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Payment provider token, obtained via @BotFather. Pass an empty string for payments in Telegram Stars." + }, + { + "name": "Currency", + "json_name": "currency", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Three-letter ISO 4217 currency code, see more on currencies. Pass “XTR” for payments in Telegram Stars." + }, + { + "name": "Prices", + "json_name": "prices", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "LabeledPrice" + } + }, + "required": true, + "doc": "Price breakdown, a JSON-serialized list of components (e.g. product price, tax, discount, delivery cost, delivery tax, bonus, etc.). Must contain exactly one item for payments in Telegram Stars." + }, + { + "name": "MaxTipAmount", + "json_name": "max_tip_amount", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "The maximum accepted amount for tips in the smallest units of the currency (integer, not float/double). For example, for a maximum tip of US$ 1.45 pass max_tip_amount = 145. See the exp parameter in currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies). Defaults to 0. Not supported for payments in Telegram Stars." + }, + { + "name": "SuggestedTipAmounts", + "json_name": "suggested_tip_amounts", + "type": { + "kind": "array", + "elem_type": { + "kind": "primitive", + "name": "int64" + } + }, + "doc": "A JSON-serialized array of suggested amounts of tips in the smallest units of the currency (integer, not float/double). At most 4 suggested tip amounts can be specified. The suggested tip amounts must be positive, passed in a strictly increased order and must not exceed max_tip_amount." + }, + { + "name": "StartParameter", + "json_name": "start_parameter", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Unique deep-linking parameter. If left empty, forwarded copies of the sent message will have a Pay button, allowing multiple users to pay directly from the forwarded message, using the same invoice. If non-empty, forwarded copies of the sent message will have a URL button with a deep link to the bot (instead of a Pay button), with the value used as the start parameter" + }, + { + "name": "ProviderData", + "json_name": "provider_data", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "JSON-serialized data about the invoice, which will be shared with the payment provider. A detailed description of required fields should be provided by the payment provider." + }, + { + "name": "PhotoURL", + "json_name": "photo_url", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "URL of the product photo for the invoice. Can be a photo of the goods or a marketing image for a service. People like it better when they see what they are paying for." + }, + { + "name": "PhotoSize", + "json_name": "photo_size", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Photo size in bytes" + }, + { + "name": "PhotoWidth", + "json_name": "photo_width", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Photo width" + }, + { + "name": "PhotoHeight", + "json_name": "photo_height", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Photo height" + }, + { + "name": "NeedName", + "json_name": "need_name", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True if you require the user's full name to complete the order. Ignored for payments in Telegram Stars." + }, + { + "name": "NeedPhoneNumber", + "json_name": "need_phone_number", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True if you require the user's phone number to complete the order. Ignored for payments in Telegram Stars." + }, + { + "name": "NeedEmail", + "json_name": "need_email", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True if you require the user's email address to complete the order. Ignored for payments in Telegram Stars." + }, + { + "name": "NeedShippingAddress", + "json_name": "need_shipping_address", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True if you require the user's shipping address to complete the order. Ignored for payments in Telegram Stars." + }, + { + "name": "SendPhoneNumberToProvider", + "json_name": "send_phone_number_to_provider", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True if the user's phone number should be sent to the provider. Ignored for payments in Telegram Stars." + }, + { + "name": "SendEmailToProvider", + "json_name": "send_email_to_provider", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True if the user's email address should be sent to the provider. Ignored for payments in Telegram Stars." + }, + { + "name": "IsFlexible", + "json_name": "is_flexible", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True if the final price depends on the shipping method. Ignored for payments in Telegram Stars." + }, + { + "name": "DisableNotification", + "json_name": "disable_notification", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Sends the message silently. Users will receive a notification with no sound." + }, + { + "name": "ProtectContent", + "json_name": "protect_content", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Protects the contents of the sent message from forwarding and saving" + }, + { + "name": "AllowPaidBroadcast", + "json_name": "allow_paid_broadcast", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance." + }, + { + "name": "MessageEffectID", + "json_name": "message_effect_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Unique identifier of the message effect to be added to the message; for private chats only" + }, + { + "name": "SuggestedPostParameters", + "json_name": "suggested_post_parameters", + "type": { + "kind": "named", + "name": "SuggestedPostParameters" + }, + "doc": "A JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined." + }, + { + "name": "ReplyParameters", + "json_name": "reply_parameters", + "type": { + "kind": "named", + "name": "ReplyParameters" + }, + "doc": "Description of the message to reply to" + }, + { + "name": "ReplyMarkup", + "json_name": "reply_markup", + "type": { + "kind": "named", + "name": "InlineKeyboardMarkup" + }, + "doc": "A JSON-serialized object for an inline keyboard. If empty, one 'Pay total price' button will be shown. If not empty, the first button must be a Pay button." + } + ], + "returns": { + "kind": "named", + "name": "Message" + } + }, + { + "name": "createInvoiceLink", + "doc": "Use this method to create a link for an invoice. Returns the created invoice link as String on success.", + "params": [ + { + "name": "BusinessConnectionID", + "json_name": "business_connection_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Unique identifier of the business connection on behalf of which the link will be created. For payments in Telegram Stars only." + }, + { + "name": "Title", + "json_name": "title", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Product name, 1-32 characters" + }, + { + "name": "Description", + "json_name": "description", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Product description, 1-255 characters" + }, + { + "name": "Payload", + "json_name": "payload", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Bot-defined invoice payload, 1-128 bytes. This will not be displayed to the user, use it for your internal processes." + }, + { + "name": "ProviderToken", + "json_name": "provider_token", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Payment provider token, obtained via @BotFather. Pass an empty string for payments in Telegram Stars." + }, + { + "name": "Currency", + "json_name": "currency", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Three-letter ISO 4217 currency code, see more on currencies. Pass “XTR” for payments in Telegram Stars." + }, + { + "name": "Prices", + "json_name": "prices", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "LabeledPrice" + } + }, + "required": true, + "doc": "Price breakdown, a JSON-serialized list of components (e.g. product price, tax, discount, delivery cost, delivery tax, bonus, etc.). Must contain exactly one item for payments in Telegram Stars." + }, + { + "name": "SubscriptionPeriod", + "json_name": "subscription_period", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "The number of seconds the subscription will be active for before the next payment. The currency must be set to “XTR” (Telegram Stars) if the parameter is used. Currently, it must always be 2592000 (30 days) if specified. Any number of subscriptions can be active for a given bot at the same time, including multiple concurrent subscriptions from the same user. Subscription price must no exceed 10000 Telegram Stars." + }, + { + "name": "MaxTipAmount", + "json_name": "max_tip_amount", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "The maximum accepted amount for tips in the smallest units of the currency (integer, not float/double). For example, for a maximum tip of US$ 1.45 pass max_tip_amount = 145. See the exp parameter in currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies). Defaults to 0. Not supported for payments in Telegram Stars." + }, + { + "name": "SuggestedTipAmounts", + "json_name": "suggested_tip_amounts", + "type": { + "kind": "array", + "elem_type": { + "kind": "primitive", + "name": "int64" + } + }, + "doc": "A JSON-serialized array of suggested amounts of tips in the smallest units of the currency (integer, not float/double). At most 4 suggested tip amounts can be specified. The suggested tip amounts must be positive, passed in a strictly increased order and must not exceed max_tip_amount." + }, + { + "name": "ProviderData", + "json_name": "provider_data", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "JSON-serialized data about the invoice, which will be shared with the payment provider. A detailed description of required fields should be provided by the payment provider." + }, + { + "name": "PhotoURL", + "json_name": "photo_url", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "URL of the product photo for the invoice. Can be a photo of the goods or a marketing image for a service." + }, + { + "name": "PhotoSize", + "json_name": "photo_size", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Photo size in bytes" + }, + { + "name": "PhotoWidth", + "json_name": "photo_width", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Photo width" + }, + { + "name": "PhotoHeight", + "json_name": "photo_height", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Photo height" + }, + { + "name": "NeedName", + "json_name": "need_name", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True if you require the user's full name to complete the order. Ignored for payments in Telegram Stars." + }, + { + "name": "NeedPhoneNumber", + "json_name": "need_phone_number", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True if you require the user's phone number to complete the order. Ignored for payments in Telegram Stars." + }, + { + "name": "NeedEmail", + "json_name": "need_email", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True if you require the user's email address to complete the order. Ignored for payments in Telegram Stars." + }, + { + "name": "NeedShippingAddress", + "json_name": "need_shipping_address", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True if you require the user's shipping address to complete the order. Ignored for payments in Telegram Stars." + }, + { + "name": "SendPhoneNumberToProvider", + "json_name": "send_phone_number_to_provider", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True if the user's phone number should be sent to the provider. Ignored for payments in Telegram Stars." + }, + { + "name": "SendEmailToProvider", + "json_name": "send_email_to_provider", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True if the user's email address should be sent to the provider. Ignored for payments in Telegram Stars." + }, + { + "name": "IsFlexible", + "json_name": "is_flexible", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True if the final price depends on the shipping method. Ignored for payments in Telegram Stars." + } + ], + "returns": { + "kind": "primitive", + "name": "string" + } + }, + { + "name": "answerShippingQuery", + "doc": "If you sent an invoice requesting a shipping address and the parameter is_flexible was specified, the Bot API will send an Update with a shipping_query field to the bot. Use this method to reply to shipping queries. On success, True is returned.", + "params": [ + { + "name": "ShippingQueryID", + "json_name": "shipping_query_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique identifier for the query to be answered" + }, + { + "name": "Ok", + "json_name": "ok", + "type": { + "kind": "primitive", + "name": "bool" + }, + "required": true, + "doc": "Pass True if delivery to the specified address is possible and False if there are any problems (for example, if delivery to the specified address is not possible)" + }, + { + "name": "ShippingOptions", + "json_name": "shipping_options", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "ShippingOption" + } + }, + "doc": "Required if ok is True. A JSON-serialized array of available shipping options." + }, + { + "name": "ErrorMessage", + "json_name": "error_message", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Required if ok is False. Error message in human readable form that explains why it is impossible to complete the order (e.g. “Sorry, delivery to your desired address is unavailable”). Telegram will display this message to the user." + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "answerPreCheckoutQuery", + "doc": "Once the user has confirmed their payment and shipping details, the Bot API sends the final confirmation in the form of an Update with the field pre_checkout_query. Use this method to respond to such pre-checkout queries. On success, True is returned. Note: The Bot API must receive an answer within 10 seconds after the pre-checkout query was sent.", + "params": [ + { + "name": "PreCheckoutQueryID", + "json_name": "pre_checkout_query_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Unique identifier for the query to be answered" + }, + { + "name": "Ok", + "json_name": "ok", + "type": { + "kind": "primitive", + "name": "bool" + }, + "required": true, + "doc": "Specify True if everything is alright (goods are available, etc.) and the bot is ready to proceed with the order. Use False if there are any problems." + }, + { + "name": "ErrorMessage", + "json_name": "error_message", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Required if ok is False. Error message in human readable form that explains the reason for failure to proceed with the checkout (e.g. \"Sorry, somebody just bought the last of our amazing black T-shirts while you were busy filling out your payment details. Please choose a different color or garment!\"). Telegram will display this message to the user." + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "getMyStarBalance", + "doc": "A method to get the current Telegram Stars balance of the bot. Requires no parameters. On success, returns a StarAmount object.", + "returns": { + "kind": "named", + "name": "StarAmount" + } + }, + { + "name": "getStarTransactions", + "doc": "Returns the bot's Telegram Star transactions in chronological order. On success, returns a StarTransactions object.", + "params": [ + { + "name": "Offset", + "json_name": "offset", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Number of transactions to skip in the response" + }, + { + "name": "Limit", + "json_name": "limit", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "The maximum number of transactions to be retrieved. Values between 1-100 are accepted. Defaults to 100." + } + ], + "returns": { + "kind": "named", + "name": "StarTransactions" + } + }, + { + "name": "refundStarPayment", + "doc": "Refunds a successful payment in Telegram Stars. Returns True on success.", + "params": [ + { + "name": "UserID", + "json_name": "user_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Identifier of the user whose payment will be refunded" + }, + { + "name": "TelegramPaymentChargeID", + "json_name": "telegram_payment_charge_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Telegram payment identifier" + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "editUserStarSubscription", + "doc": "Allows the bot to cancel or re-enable extension of a subscription paid in Telegram Stars. Returns True on success.", + "params": [ + { + "name": "UserID", + "json_name": "user_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Identifier of the user whose subscription will be edited" + }, + { + "name": "TelegramPaymentChargeID", + "json_name": "telegram_payment_charge_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Telegram payment identifier for the subscription" + }, + { + "name": "IsCanceled", + "json_name": "is_canceled", + "type": { + "kind": "primitive", + "name": "bool" + }, + "required": true, + "doc": "Pass True to cancel extension of the user subscription; the subscription must be active up to the end of the current subscription period. Pass False to allow the user to re-enable a subscription that was previously canceled by the bot." + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "setPassportDataErrors", + "doc": "Informs a user that some of the Telegram Passport elements they provided contains errors. The user will not be able to re-submit their Passport to you until the errors are fixed (the contents of the field for which you returned the error must change). Returns True on success.\nUse this if the data submitted by the user doesn't satisfy the standards your service requires for any reason. For example, if a birthday date seems invalid, a submitted document is blurry, a scan shows evidence of tampering, etc. Supply some details in the error message to make sure the user knows how to correct the issues.", + "params": [ + { + "name": "UserID", + "json_name": "user_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "User identifier" + }, + { + "name": "Errors", + "json_name": "errors", + "type": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "PassportElementError" + } + }, + "required": true, + "doc": "A JSON-serialized array describing the errors" + } + ], + "returns": { + "kind": "primitive", + "name": "bool" + } + }, + { + "name": "sendGame", + "doc": "Use this method to send a game. On success, the sent Message is returned.", + "params": [ + { + "name": "BusinessConnectionID", + "json_name": "business_connection_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Unique identifier of the business connection on behalf of which the message will be sent" + }, + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the target chat or username of the target bot in the format @username. Games can't be sent to channel direct messages chats and channel chats." + }, + { + "name": "MessageThreadID", + "json_name": "message_thread_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Unique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only" + }, + { + "name": "GameShortName", + "json_name": "game_short_name", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Short name of the game, serves as the unique identifier for the game. Set up your games via @BotFather." + }, + { + "name": "DisableNotification", + "json_name": "disable_notification", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Sends the message silently. Users will receive a notification with no sound." + }, + { + "name": "ProtectContent", + "json_name": "protect_content", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Protects the contents of the sent message from forwarding and saving" + }, + { + "name": "AllowPaidBroadcast", + "json_name": "allow_paid_broadcast", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance." + }, + { + "name": "MessageEffectID", + "json_name": "message_effect_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Unique identifier of the message effect to be added to the message; for private chats only" + }, + { + "name": "ReplyParameters", + "json_name": "reply_parameters", + "type": { + "kind": "named", + "name": "ReplyParameters" + }, + "doc": "Description of the message to reply to" + }, + { + "name": "ReplyMarkup", + "json_name": "reply_markup", + "type": { + "kind": "named", + "name": "InlineKeyboardMarkup" + }, + "doc": "A JSON-serialized object for an inline keyboard. If empty, one 'Play game_title' button will be shown. If not empty, the first button must launch the game." + } + ], + "returns": { + "kind": "named", + "name": "Message" + } + }, + { + "name": "setGameScore", + "doc": "Use this method to set the score of the specified user in a game message. On success, if the message is not an inline message, the Message is returned, otherwise True is returned. Returns an error, if the new score is not greater than the user's current score in the chat and force is False.", + "params": [ + { + "name": "UserID", + "json_name": "user_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "User identifier" + }, + { + "name": "Score", + "json_name": "score", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "New score, must be non-negative" + }, + { + "name": "Force", + "json_name": "force", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True if the high score is allowed to decrease. This can be useful when fixing mistakes or banning cheaters" + }, + { + "name": "DisableEditMessage", + "json_name": "disable_edit_message", + "type": { + "kind": "primitive", + "name": "bool" + }, + "doc": "Pass True if the game message should not be automatically edited to include the current scoreboard" + }, + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Required if inline_message_id is not specified. Unique identifier for the target chat" + }, + { + "name": "MessageID", + "json_name": "message_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Required if inline_message_id is not specified. Identifier of the sent message" + }, + { + "name": "InlineMessageID", + "json_name": "inline_message_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Required if chat_id and message_id are not specified. Identifier of the inline message" + } + ], + "returns": { + "kind": "named", + "name": "MessageOrBool" + } + }, + { + "name": "getGameHighScores", + "doc": "Use this method to get data for high score tables. Will return the score of the specified user and several of their neighbors in a game. Returns an Array of GameHighScore objects.\nThis method will currently return scores for the target user, plus two of their closest neighbors on each side. Will also return the top three users if the user and their neighbors are not among them. Please note that this behavior is subject to change.", + "params": [ + { + "name": "UserID", + "json_name": "user_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Target user id" + }, + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Required if inline_message_id is not specified. Unique identifier for the target chat" + }, + { + "name": "MessageID", + "json_name": "message_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Required if inline_message_id is not specified. Identifier of the sent message" + }, + { + "name": "InlineMessageID", + "json_name": "inline_message_id", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Required if chat_id and message_id are not specified. Identifier of the inline message" + } + ], + "returns": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "GameHighScore" + } + } + } + ] +} diff --git a/internal/spec/ir.go b/internal/spec/ir.go new file mode 100644 index 0000000..3eb49bc --- /dev/null +++ b/internal/spec/ir.go @@ -0,0 +1,105 @@ +// Package spec defines the intermediate representation produced by the +// Telegram Bot API scraper (cmd/scrape) and consumed by the code generator +// (cmd/genapi). It is committed as internal/spec/api.json so PR diffs read +// as a Telegram changelog. +package spec + +import "fmt" + +// API is the top-level IR document. +type API struct { + // Version is the Telegram Bot API version parsed from the "Recent changes" section of the docs page. + Version string `json:"version"` + // Types lists all object types in declaration order. + Types []TypeDecl `json:"types"` + // Methods lists all API methods in declaration order. + Methods []MethodDecl `json:"methods"` +} + +// TypeDecl describes a Telegram object type. +type TypeDecl struct { + Name string `json:"name"` + Doc string `json:"doc,omitempty"` + Fields []Field `json:"fields,omitempty"` + // OneOf, when non-empty, indicates this type is a union and lists the concrete variant type names. + // Variants are emitted as concrete structs implementing a sealed interface. + OneOf []string `json:"one_of,omitempty"` +} + +// MethodDecl describes a Telegram API method. +type MethodDecl struct { + Name string `json:"name"` + Doc string `json:"doc,omitempty"` + Params []Field `json:"params,omitempty"` + Returns TypeRef `json:"returns"` + // HasFiles is true when any parameter accepts an InputFile, requiring a multipart/form-data request. + HasFiles bool `json:"has_files,omitempty"` +} + +// Field describes a single field on a type or a single parameter on a method. +type Field struct { + // Name is the Go-style identifier (e.g. "ChatID"). + Name string `json:"name"` + // JSONName is the wire name (e.g. "chat_id"). + JSONName string `json:"json_name"` + Type TypeRef `json:"type"` + Required bool `json:"required,omitempty"` + Doc string `json:"doc,omitempty"` +} + +// Kind enumerates TypeRef shapes. +type Kind int + +const ( + // KindPrimitive: int64, string, bool, float64. + KindPrimitive Kind = iota + // KindNamed: a TypeDecl by name. + KindNamed + // KindArray: ElemType is the element type. + KindArray + // KindOneOf: Variants lists discriminant union members. + KindOneOf +) + +// String returns a stable, lowercase representation suitable for serialisation. +func (k Kind) String() string { + switch k { + case KindPrimitive: + return "primitive" + case KindNamed: + return "named" + case KindArray: + return "array" + case KindOneOf: + return "oneOf" + default: + return "unknown" + } +} + +// MarshalText / UnmarshalText keep JSON output human-readable. +func (k Kind) MarshalText() ([]byte, error) { return []byte(k.String()), nil } + +func (k *Kind) UnmarshalText(b []byte) error { + switch string(b) { + case "primitive": + *k = KindPrimitive + case "named": + *k = KindNamed + case "array": + *k = KindArray + case "oneOf": + *k = KindOneOf + default: + return fmt.Errorf("unknown Kind: %q", string(b)) + } + return nil +} + +// TypeRef is a structural reference used wherever a Field type is expressed. +type TypeRef struct { + Kind Kind `json:"kind"` + Name string `json:"name,omitempty"` + ElemType *TypeRef `json:"elem_type,omitempty"` + Variants []string `json:"variants,omitempty"` +} diff --git a/internal/spec/ir_test.go b/internal/spec/ir_test.go new file mode 100644 index 0000000..19eb343 --- /dev/null +++ b/internal/spec/ir_test.go @@ -0,0 +1,87 @@ +package spec + +import ( + "encoding/json" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestAPIRoundTripJSON(t *testing.T) { + in := API{ + Version: "7.10", + Types: []TypeDecl{{ + Name: "User", + Doc: "This object represents a Telegram user or bot.", + Fields: []Field{ + {Name: "ID", JSONName: "id", Type: TypeRef{Kind: KindPrimitive, Name: "int64"}, Required: true, Doc: "Unique identifier."}, + {Name: "Username", JSONName: "username", Type: TypeRef{Kind: KindPrimitive, Name: "string"}, Required: false, Doc: "Optional username."}, + }, + }}, + Methods: []MethodDecl{{ + Name: "getMe", + Doc: "A simple method for testing your bot's authentication token.", + Returns: TypeRef{Kind: KindNamed, Name: "User"}, + }}, + } + + data, err := json.MarshalIndent(in, "", " ") + require.NoError(t, err) + + var out API + require.NoError(t, json.Unmarshal(data, &out)) + require.Equal(t, in, out) +} + +func TestTypeRefKindString(t *testing.T) { + require.Equal(t, "primitive", KindPrimitive.String()) + require.Equal(t, "named", KindNamed.String()) + require.Equal(t, "array", KindArray.String()) + require.Equal(t, "oneOf", KindOneOf.String()) +} + +func TestAPIRoundTrip_ArrayAndOneOf(t *testing.T) { + elem := &TypeRef{Kind: KindNamed, Name: "Update"} + in := API{ + Version: "7.10", + Types: []TypeDecl{{ + Name: "InputMedia", + OneOf: []string{"InputMediaPhoto", "InputMediaVideo"}, + }}, + Methods: []MethodDecl{{ + Name: "getUpdates", + Params: []Field{{Name: "Limit", JSONName: "limit", Type: TypeRef{Kind: KindPrimitive, Name: "int"}}}, + Returns: TypeRef{Kind: KindArray, ElemType: elem}, + }}, + } + data, err := json.Marshal(in) + require.NoError(t, err) + var out API + require.NoError(t, json.Unmarshal(data, &out)) + require.Equal(t, in, out) +} + +func TestKind_MarshalUnmarshalText(t *testing.T) { + cases := []Kind{KindPrimitive, KindNamed, KindArray, KindOneOf} + for _, k := range cases { + b, err := k.MarshalText() + require.NoError(t, err) + var out Kind + require.NoError(t, out.UnmarshalText(b)) + require.Equal(t, k, out) + } +} + +func TestKind_UnmarshalText_UnknownReturnsError(t *testing.T) { + var k Kind + err := k.UnmarshalText([]byte("bogus")) + require.Error(t, err) +} + +func TestField_OmitsOptional(t *testing.T) { + f := Field{Name: "X", JSONName: "x", Type: TypeRef{Kind: KindPrimitive, Name: "string"}} + data, err := json.Marshal(f) + require.NoError(t, err) + require.NotContains(t, string(data), "required") + require.NotContains(t, string(data), "doc") +} diff --git a/internal/spec/overrides.go b/internal/spec/overrides.go new file mode 100644 index 0000000..f07e46e --- /dev/null +++ b/internal/spec/overrides.go @@ -0,0 +1,75 @@ +package spec + +import ( + "errors" + "fmt" + "github.com/goccy/go-json" + "os" +) + +// Overrides is the schema of internal/spec/overrides.json. It lets engineers +// pin specific method returns or field types, and approve methods that +// genuinely return bool but whose doc phrasing the scraper doesn't recognise. +type Overrides struct { + // MethodReturns maps "" → desired return TypeRef. + // Applied AFTER the scraper extracts a return type, overriding it. + MethodReturns map[string]TypeRef `json:"method_returns,omitempty"` + + // FieldTypes maps "." → desired field TypeRef. + // Applied AFTER the scraper builds the IR, overriding the field type. + FieldTypes map[string]TypeRef `json:"field_types,omitempty"` + + // ApprovedBoolMethods lists methods whose returns are genuinely bool. + // The audit tool ignores these. + ApprovedBoolMethods []string `json:"approved_bool_methods,omitempty"` +} + +// LoadOverrides reads and parses overrides.json. Returns an empty Overrides +// (not an error) if the file does not exist. +func LoadOverrides(path string) (*Overrides, error) { + data, err := os.ReadFile(path) + if errors.Is(err, os.ErrNotExist) { + return &Overrides{}, nil + } + if err != nil { + return nil, fmt.Errorf("read %s: %w", path, err) + } + var o Overrides + if err := json.Unmarshal(data, &o); err != nil { + return nil, fmt.Errorf("parse %s: %w", path, err) + } + return &o, nil +} + +// Apply patches an API in place using the overrides. +func (o *Overrides) Apply(api *API) { + if o == nil { + return + } + for i, m := range api.Methods { + if rt, ok := o.MethodReturns[m.Name]; ok { + api.Methods[i].Returns = rt + } + } + for i, t := range api.Types { + for j, f := range t.Fields { + key := t.Name + "." + f.Name + if ft, ok := o.FieldTypes[key]; ok { + api.Types[i].Fields[j].Type = ft + } + } + } +} + +// IsBoolApproved reports whether methodName is on the approved bool list. +func (o *Overrides) IsBoolApproved(methodName string) bool { + if o == nil { + return false + } + for _, n := range o.ApprovedBoolMethods { + if n == methodName { + return true + } + } + return false +} diff --git a/internal/spec/overrides.json b/internal/spec/overrides.json new file mode 100644 index 0000000..19fafc7 --- /dev/null +++ b/internal/spec/overrides.json @@ -0,0 +1,100 @@ +{ + "method_returns": {}, + "field_types": {}, + "approved_bool_methods": [ + "setWebhook", + "deleteWebhook", + "logOut", + "close", + "sendMessageDraft", + "sendChatAction", + "setMessageReaction", + "setUserEmojiStatus", + "banChatMember", + "unbanChatMember", + "restrictChatMember", + "promoteChatMember", + "setChatAdministratorCustomTitle", + "setChatMemberTag", + "banChatSenderChat", + "unbanChatSenderChat", + "setChatPermissions", + "approveChatJoinRequest", + "declineChatJoinRequest", + "setChatPhoto", + "deleteChatPhoto", + "setChatTitle", + "setChatDescription", + "pinChatMessage", + "unpinChatMessage", + "unpinAllChatMessages", + "leaveChat", + "setChatStickerSet", + "deleteChatStickerSet", + "editForumTopic", + "closeForumTopic", + "reopenForumTopic", + "deleteForumTopic", + "unpinAllForumTopicMessages", + "editGeneralForumTopic", + "closeGeneralForumTopic", + "reopenGeneralForumTopic", + "hideGeneralForumTopic", + "unhideGeneralForumTopic", + "unpinAllGeneralForumTopicMessages", + "answerCallbackQuery", + "setManagedBotAccessSettings", + "setMyCommands", + "deleteMyCommands", + "setMyName", + "setMyDescription", + "setMyShortDescription", + "setMyProfilePhoto", + "removeMyProfilePhoto", + "setChatMenuButton", + "setMyDefaultAdministratorRights", + "sendGift", + "giftPremiumSubscription", + "verifyUser", + "verifyChat", + "removeUserVerification", + "removeChatVerification", + "readBusinessMessage", + "deleteBusinessMessages", + "setBusinessAccountName", + "setBusinessAccountUsername", + "setBusinessAccountBio", + "setBusinessAccountProfilePhoto", + "removeBusinessAccountProfilePhoto", + "setBusinessAccountGiftSettings", + "transferBusinessAccountStars", + "convertGiftToStars", + "upgradeGift", + "transferGift", + "deleteStory", + "approveSuggestedPost", + "declineSuggestedPost", + "deleteMessage", + "deleteMessages", + "deleteMessageReaction", + "deleteAllMessageReactions", + "createNewStickerSet", + "addStickerToSet", + "setStickerPositionInSet", + "deleteStickerFromSet", + "replaceStickerInSet", + "setStickerEmojiList", + "setStickerKeywords", + "setStickerMaskPosition", + "setStickerSetTitle", + "setStickerSetThumbnail", + "setCustomEmojiStickerSetThumbnail", + "deleteStickerSet", + "answerInlineQuery", + "answerShippingQuery", + "answerPreCheckoutQuery", + "refundStarPayment", + "editUserStarSubscription", + "setPassportDataErrors" + ] +} diff --git a/internal/spec/overrides_test.go b/internal/spec/overrides_test.go new file mode 100644 index 0000000..e536146 --- /dev/null +++ b/internal/spec/overrides_test.go @@ -0,0 +1,87 @@ +package spec + +import ( + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestLoadOverrides_MissingFile(t *testing.T) { + o, err := LoadOverrides(filepath.Join(t.TempDir(), "nonexistent.json")) + require.NoError(t, err) + require.NotNil(t, o) + require.Empty(t, o.MethodReturns) + require.Empty(t, o.FieldTypes) + require.Empty(t, o.ApprovedBoolMethods) +} + +func TestLoadOverrides_MalformedJSON(t *testing.T) { + p := filepath.Join(t.TempDir(), "bad.json") + require.NoError(t, os.WriteFile(p, []byte("{bad json"), 0o600)) + _, err := LoadOverrides(p) + require.Error(t, err) +} + +func TestApply_PatchesMethodReturn(t *testing.T) { + api := &API{ + Methods: []MethodDecl{ + {Name: "getMe", Returns: TypeRef{Kind: KindPrimitive, Name: "bool"}}, + }, + } + o := &Overrides{ + MethodReturns: map[string]TypeRef{ + "getMe": {Kind: KindNamed, Name: "User"}, + }, + } + o.Apply(api) + require.Equal(t, KindNamed, api.Methods[0].Returns.Kind) + require.Equal(t, "User", api.Methods[0].Returns.Name) +} + +func TestApply_PatchesFieldType(t *testing.T) { + api := &API{ + Types: []TypeDecl{ + { + Name: "Message", + Fields: []Field{ + {Name: "ChatID", JSONName: "chat_id", Type: TypeRef{Kind: KindPrimitive, Name: "string"}}, + }, + }, + }, + } + o := &Overrides{ + FieldTypes: map[string]TypeRef{ + "Message.ChatID": {Kind: KindOneOf, Variants: []string{"int64", "string"}}, + }, + } + o.Apply(api) + require.Equal(t, KindOneOf, api.Types[0].Fields[0].Type.Kind) + require.Equal(t, []string{"int64", "string"}, api.Types[0].Fields[0].Type.Variants) +} + +func TestApply_NilOverrides(t *testing.T) { + api := &API{ + Methods: []MethodDecl{{Name: "getMe", Returns: TypeRef{Kind: KindPrimitive, Name: "bool"}}}, + } + var o *Overrides + require.NotPanics(t, func() { o.Apply(api) }) + require.Equal(t, "bool", api.Methods[0].Returns.Name) +} + +func TestIsBoolApproved_Hit(t *testing.T) { + o := &Overrides{ApprovedBoolMethods: []string{"setWebhook", "deleteWebhook"}} + require.True(t, o.IsBoolApproved("setWebhook")) + require.True(t, o.IsBoolApproved("deleteWebhook")) +} + +func TestIsBoolApproved_Miss(t *testing.T) { + o := &Overrides{ApprovedBoolMethods: []string{"setWebhook"}} + require.False(t, o.IsBoolApproved("getMe")) +} + +func TestIsBoolApproved_NilOverrides(t *testing.T) { + var o *Overrides + require.False(t, o.IsBoolApproved("anything")) +} diff --git a/scripts/snapshot.sh b/scripts/snapshot.sh new file mode 100755 index 0000000..5f429b0 --- /dev/null +++ b/scripts/snapshot.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +# Capture the live Telegram Bot API HTML to testdata/html/snapshot_.html +# and update the latest.html symlink. Used by `make snapshot`. +set -euo pipefail + +DATE=$(date +%Y-%m-%d) +DEST="testdata/html/snapshot_${DATE}.html" + +curl -fsSL --user-agent "go-telegram codegen scraper" \ + https://core.telegram.org/bots/api > "$DEST" + +ln -sf "snapshot_${DATE}.html" "testdata/html/latest.html" +echo "captured: $DEST" diff --git a/test/integration/README.md b/test/integration/README.md new file mode 100644 index 0000000..319fa63 --- /dev/null +++ b/test/integration/README.md @@ -0,0 +1,13 @@ +# Integration tests + +Live tests against the real Telegram Bot API. Skipped by default. + +## Run + +```bash +export TELEGRAM_BOT_TOKEN=test_bot_token_here +export TELEGRAM_TEST_CHAT_ID=123456789 # a chat the bot can post in +make integration +``` + +The suite covers `getMe`, `sendMessage`, and the `setWebhook`/`deleteWebhook` cycle. diff --git a/test/integration/integration_test.go b/test/integration/integration_test.go new file mode 100644 index 0000000..07fc095 --- /dev/null +++ b/test/integration/integration_test.go @@ -0,0 +1,73 @@ +//go:build integration + +// Package integration_test contains tests that hit the live Telegram Bot +// API. These tests are gated behind the "integration" build tag and the +// TELEGRAM_BOT_TOKEN environment variable; they do not run on default +// `go test ./...`. +package integration_test + +import ( + "context" + "os" + "strconv" + "testing" + "time" + + "github.com/lukaszraczylo/go-telegram/api" + "github.com/lukaszraczylo/go-telegram/client" + "github.com/stretchr/testify/require" +) + +func botFromEnv(t *testing.T) *client.Bot { + tok := os.Getenv("TELEGRAM_BOT_TOKEN") + if tok == "" { + t.Skip("TELEGRAM_BOT_TOKEN not set") + } + return client.New(tok) +} + +func TestGetMe(t *testing.T) { + b := botFromEnv(t) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + u, err := api.GetMe(ctx, b) + require.NoError(t, err) + require.True(t, u.IsBot) +} + +func TestSendMessage(t *testing.T) { + b := botFromEnv(t) + chatRaw := os.Getenv("TELEGRAM_TEST_CHAT_ID") + if chatRaw == "" { + t.Skip("TELEGRAM_TEST_CHAT_ID not set") + } + chatID, err := strconv.ParseInt(chatRaw, 10, 64) + require.NoError(t, err, "TELEGRAM_TEST_CHAT_ID must be an integer") + + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + msg, err := api.SendMessage(ctx, b, &api.SendMessageParams{ + ChatID: chatID, + Text: "integration test " + time.Now().UTC().Format(time.RFC3339), + }) + require.NoError(t, err) + require.NotZero(t, msg.MessageID) +} + +func TestWebhookCycle(t *testing.T) { + b := botFromEnv(t) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + // Make sure no webhook is set first (long-poll mode). + _, _ = api.DeleteWebhook(ctx, b, &api.DeleteWebhookParams{}) + + ok, err := api.SetWebhook(ctx, b, &api.SetWebhookParams{URL: "https://example.invalid/no-receive"}) + require.NoError(t, err) + require.True(t, ok) + + ok, err = api.DeleteWebhook(ctx, b, &api.DeleteWebhookParams{}) + require.NoError(t, err) + require.True(t, ok) +} diff --git a/testdata/golden/.gitkeep b/testdata/golden/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/testdata/golden/api_small_fixture.json b/testdata/golden/api_small_fixture.json new file mode 100644 index 0000000..3d8b6d0 --- /dev/null +++ b/testdata/golden/api_small_fixture.json @@ -0,0 +1,175 @@ +{ + "version": "7.10", + "types": [ + { + "name": "User", + "doc": "This object represents a Telegram user or bot.", + "fields": [ + { + "name": "ID", + "json_name": "id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Unique identifier." + }, + { + "name": "IsBot", + "json_name": "is_bot", + "type": { + "kind": "primitive", + "name": "bool" + }, + "required": true, + "doc": "True, if this user is a bot." + }, + { + "name": "FirstName", + "json_name": "first_name", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "User's or bot's first name." + }, + { + "name": "LastName", + "json_name": "last_name", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Optional. User's or bot's last name." + } + ] + }, + { + "name": "ChatMember", + "doc": "This object contains information about one member of a chat. Currently, the following 6 types of chat members are supported:", + "one_of": [ + "ChatMemberOwner", + "ChatMemberAdministrator" + ] + } + ], + "methods": [ + { + "name": "getMe", + "doc": "A simple method for testing your bot's authentication token. Requires no parameters. Returns basic information about the bot in form of a User object.", + "returns": { + "kind": "named", + "name": "User" + } + }, + { + "name": "sendMessage", + "doc": "Use this method to send text messages. On success, the sent Message is returned.", + "params": [ + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "oneOf", + "variants": [ + "int64", + "string" + ] + }, + "required": true, + "doc": "Unique identifier for the target chat." + }, + { + "name": "Text", + "json_name": "text", + "type": { + "kind": "primitive", + "name": "string" + }, + "required": true, + "doc": "Text of the message to be sent." + }, + { + "name": "ParseMode", + "json_name": "parse_mode", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Mode for parsing entities in the message text." + } + ], + "returns": { + "kind": "named", + "name": "Message" + } + }, + { + "name": "sendDocument", + "doc": "Use this method to send general files. On success, the sent Message is returned.", + "params": [ + { + "name": "ChatID", + "json_name": "chat_id", + "type": { + "kind": "primitive", + "name": "int64" + }, + "required": true, + "doc": "Unique identifier for the target chat." + }, + { + "name": "Document", + "json_name": "document", + "type": { + "kind": "oneOf", + "variants": [ + "InputFile", + "string" + ] + }, + "required": true, + "doc": "File to send." + }, + { + "name": "Caption", + "json_name": "caption", + "type": { + "kind": "primitive", + "name": "string" + }, + "doc": "Document caption." + } + ], + "returns": { + "kind": "named", + "name": "Message" + }, + "has_files": true + }, + { + "name": "getUpdates", + "doc": "Use this method to receive incoming updates using long polling. Returns an Array of Update objects.", + "params": [ + { + "name": "Limit", + "json_name": "limit", + "type": { + "kind": "primitive", + "name": "int64" + }, + "doc": "Limits the number of updates to be retrieved." + } + ], + "returns": { + "kind": "array", + "elem_type": { + "kind": "named", + "name": "Update" + } + } + } + ] +} diff --git a/testdata/golden/enums.gen.go b/testdata/golden/enums.gen.go new file mode 100644 index 0000000..0484394 --- /dev/null +++ b/testdata/golden/enums.gen.go @@ -0,0 +1,60 @@ +// Code generated by cmd/genapi. DO NOT EDIT. + +//go:build !ignore_autogenerated + +package api + +// ParseMode controls how Telegram interprets formatting in message text. +type ParseMode string + +const ( + ParseModeMarkdown ParseMode = "Markdown" // legacy + ParseModeMarkdownV2 ParseMode = "MarkdownV2" + ParseModeHTML ParseMode = "HTML" +) + +// ChatType is the type of a Telegram chat. +type ChatType string + +const ( + ChatTypePrivate ChatType = "private" + ChatTypeGroup ChatType = "group" + ChatTypeSupergroup ChatType = "supergroup" + ChatTypeChannel ChatType = "channel" +) + +// UpdateType identifies an Update payload variant. Used by allowed_updates +// in getUpdates / setWebhook. +type UpdateType string + +const ( + UpdateMessage UpdateType = "message" + UpdateEditedMessage UpdateType = "edited_message" + UpdateChannelPost UpdateType = "channel_post" + UpdateEditedChannelPost UpdateType = "edited_channel_post" + UpdateCallbackQuery UpdateType = "callback_query" + UpdateInlineQuery UpdateType = "inline_query" +) + +// MessageEntityType is the kind of an entity (mention, hashtag, command, ...). +type MessageEntityType string + +const ( + EntityMention MessageEntityType = "mention" + EntityHashtag MessageEntityType = "hashtag" + EntityCashtag MessageEntityType = "cashtag" + EntityBotCommand MessageEntityType = "bot_command" + EntityURL MessageEntityType = "url" + EntityEmail MessageEntityType = "email" + EntityPhoneNumber MessageEntityType = "phone_number" + EntityBold MessageEntityType = "bold" + EntityItalic MessageEntityType = "italic" + EntityUnderline MessageEntityType = "underline" + EntityStrike MessageEntityType = "strikethrough" + EntitySpoiler MessageEntityType = "spoiler" + EntityCode MessageEntityType = "code" + EntityPre MessageEntityType = "pre" + EntityTextLink MessageEntityType = "text_link" + EntityTextMention MessageEntityType = "text_mention" + EntityCustomEmoji MessageEntityType = "custom_emoji" +) diff --git a/testdata/golden/methods.gen.go b/testdata/golden/methods.gen.go new file mode 100644 index 0000000..de33d21 --- /dev/null +++ b/testdata/golden/methods.gen.go @@ -0,0 +1,113 @@ +// Code generated by cmd/genapi. DO NOT EDIT. + +//go:build !ignore_autogenerated + +package api + +import ( + "context" + "github.com/goccy/go-json" + "strconv" + + "github.com/lukaszraczylo/go-telegram/client" +) + +var _ = strconv.Itoa // keep import for multipart helpers +var _ = json.Marshal // keep import for complex multipart fields + +// GetMeParams is the parameter set for GetMe. +// +// A simple method for testing your bot's authentication token. Requires no parameters. Returns basic information about the bot in form of a User object. +type GetMeParams struct { +} + +// GetMe calls the getMe Telegram Bot API method. +// +// A simple method for testing your bot's authentication token. Requires no parameters. Returns basic information about the bot in form of a User object. +func GetMe(ctx context.Context, b *client.Bot, p *GetMeParams) (*User, error) { + return client.Call[*GetMeParams, *User](ctx, b, "getMe", p) +} + +// SendMessageParams is the parameter set for SendMessage. +// +// Use this method to send text messages. On success, the sent Message is returned. +type SendMessageParams struct { + // Unique identifier for the target chat. + ChatID ChatID `json:"chat_id"` + // Text of the message to be sent. + Text string `json:"text"` + // Mode for parsing entities in the message text. + ParseMode string `json:"parse_mode,omitempty"` +} + +// SendMessage calls the sendMessage Telegram Bot API method. +// +// Use this method to send text messages. On success, the sent Message is returned. +func SendMessage(ctx context.Context, b *client.Bot, p *SendMessageParams) (*Message, error) { + return client.Call[*SendMessageParams, *Message](ctx, b, "sendMessage", p) +} + +// SendDocumentParams is the parameter set for SendDocument. +// +// Use this method to send general files. On success, the sent Message is returned. +type SendDocumentParams struct { + // Unique identifier for the target chat. + ChatID int64 `json:"chat_id"` + // File to send. + Document *InputFile `json:"document"` + // Document caption. + Caption string `json:"caption,omitempty"` +} + +// HasFile reports whether a multipart upload is required. +func (p *SendDocumentParams) HasFile() bool { + if p.Document != nil && p.Document.IsLocalUpload() { + return true + } + return false +} + +// MultipartFields returns the non-file fields used in the multipart body. +func (p *SendDocumentParams) MultipartFields() map[string]string { + out := map[string]string{} + out["chat_id"] = strconv.FormatInt(p.ChatID, 10) + if p.Caption != "" { + out["caption"] = p.Caption + } + return out +} + +// MultipartFiles returns the file parts. +func (p *SendDocumentParams) MultipartFiles() []client.MultipartFile { + var files []client.MultipartFile + if p.Document != nil && p.Document.IsLocalUpload() { + name := p.Document.Filename + if name == "" { + name = "document" + } + files = append(files, client.MultipartFile{FieldName: "document", Filename: name, Reader: p.Document.Reader}) + } + return files +} + +// SendDocument calls the sendDocument Telegram Bot API method. +// +// Use this method to send general files. On success, the sent Message is returned. +func SendDocument(ctx context.Context, b *client.Bot, p *SendDocumentParams) (*Message, error) { + return client.Call[*SendDocumentParams, *Message](ctx, b, "sendDocument", p) +} + +// GetUpdatesParams is the parameter set for GetUpdates. +// +// Use this method to receive incoming updates using long polling. Returns an Array of Update objects. +type GetUpdatesParams struct { + // Limits the number of updates to be retrieved. + Limit *int64 `json:"limit,omitempty"` +} + +// GetUpdates calls the getUpdates Telegram Bot API method. +// +// Use this method to receive incoming updates using long polling. Returns an Array of Update objects. +func GetUpdates(ctx context.Context, b *client.Bot, p *GetUpdatesParams) ([]Update, error) { + return client.Call[*GetUpdatesParams, []Update](ctx, b, "getUpdates", p) +} diff --git a/testdata/golden/methods_gen_test.go b/testdata/golden/methods_gen_test.go new file mode 100644 index 0000000..4bb2a62 --- /dev/null +++ b/testdata/golden/methods_gen_test.go @@ -0,0 +1,565 @@ +// Code generated by cmd/genapi. DO NOT EDIT. + +//go:build !ignore_autogenerated + +package api + +import ( + "bytes" + "context" + "errors" + "io" + "net/http" + "strings" + "testing" + + "github.com/lukaszraczylo/go-telegram/client" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" +) + +// genTestMockDoer is a testify-mock HTTPDoer used by generated tests only. +type genTestMockDoer struct{ mock.Mock } + +func (m *genTestMockDoer) Do(r *http.Request) (*http.Response, error) { + args := m.Called(r) + if v := args.Get(0); v != nil { + return v.(*http.Response), args.Error(1) + } + return nil, args.Error(1) +} + +func genTestResp(status int, body string) *http.Response { + return &http.Response{ + StatusCode: status, + Body: io.NopCloser(bytes.NewBufferString(body)), + Header: http.Header{"Content-Type": []string{"application/json"}}, + } +} + +func Test_GetMe_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/getMe") + })).Return(genTestResp(200, `{"ok":true,"result":{}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + _, err := GetMe(context.Background(), bot, &GetMeParams{}) + require.NoError(t, err) +} + +func Test_GetMe_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + _, err := GetMe(context.Background(), bot, &GetMeParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_GetMe_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + _, err := GetMe(context.Background(), bot, &GetMeParams{}) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_GetMe_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + _, err := GetMe(context.Background(), bot, &GetMeParams{}) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_GetMe_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + _, err := GetMe(ctx, bot, &GetMeParams{}) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_GetMe_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_GetMe_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := GetMe(context.Background(), bot, &GetMeParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_GetMe_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_GetMe_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + _, err := GetMe(context.Background(), bot, &GetMeParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_GetMe_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_GetMe_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + _, err := GetMe(context.Background(), bot, &GetMeParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_SendMessage_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/sendMessage") + })).Return(genTestResp(200, `{"ok":true,"result":{}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendMessageParams{ + ChatID: ChatIDFromInt(123), + Text: "test_value", + } + _, err := SendMessage(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_SendMessage_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendMessageParams{ + ChatID: ChatIDFromInt(123), + Text: "test_value", + } + _, err := SendMessage(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_SendMessage_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendMessageParams{ + ChatID: ChatIDFromInt(123), + Text: "test_value", + } + _, err := SendMessage(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_SendMessage_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendMessageParams{ + ChatID: ChatIDFromInt(123), + Text: "test_value", + } + _, err := SendMessage(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_SendMessage_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendMessageParams{ + ChatID: ChatIDFromInt(123), + Text: "test_value", + } + _, err := SendMessage(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_SendMessage_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_SendMessage_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := SendMessage(context.Background(), bot, &SendMessageParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_SendMessage_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_SendMessage_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendMessageParams{ + ChatID: ChatIDFromInt(123), + Text: "test_value", + } + _, err := SendMessage(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_SendMessage_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_SendMessage_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendMessageParams{ + ChatID: ChatIDFromInt(123), + Text: "test_value", + } + _, err := SendMessage(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_SendDocument_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/sendDocument") + })).Return(genTestResp(200, `{"ok":true,"result":{}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendDocumentParams{ + ChatID: 42, + Document: &InputFile{PathOrID: "file_id_test"}, + } + _, err := SendDocument(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_SendDocument_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendDocumentParams{ + ChatID: 42, + Document: &InputFile{PathOrID: "file_id_test"}, + } + _, err := SendDocument(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_SendDocument_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendDocumentParams{ + ChatID: 42, + Document: &InputFile{PathOrID: "file_id_test"}, + } + _, err := SendDocument(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_SendDocument_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendDocumentParams{ + ChatID: 42, + Document: &InputFile{PathOrID: "file_id_test"}, + } + _, err := SendDocument(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_SendDocument_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendDocumentParams{ + ChatID: 42, + Document: &InputFile{PathOrID: "file_id_test"}, + } + _, err := SendDocument(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_SendDocument_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_SendDocument_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := SendDocument(context.Background(), bot, &SendDocumentParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_SendDocument_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_SendDocument_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendDocumentParams{ + ChatID: 42, + Document: &InputFile{PathOrID: "file_id_test"}, + } + _, err := SendDocument(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_SendDocument_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_SendDocument_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &SendDocumentParams{ + ChatID: 42, + Document: &InputFile{PathOrID: "file_id_test"}, + } + _, err := SendDocument(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} + +func Test_GetUpdates_Success(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + return strings.HasSuffix(r.URL.Path, "/getUpdates") + })).Return(genTestResp(200, `{"ok":true,"result":[]}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetUpdatesParams{} + _, err := GetUpdates(context.Background(), bot, params) + require.NoError(t, err) +} + +func Test_GetUpdates_APIError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetUpdatesParams{} + _, err := GetUpdates(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 429, ae.Code) + require.True(t, ae.IsRetryable()) +} + +func Test_GetUpdates_NetworkError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, errors.New("dial tcp: timeout")) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetUpdatesParams{} + _, err := GetUpdates(context.Background(), bot, params) + require.Error(t, err) + var ne *client.NetworkError + require.ErrorAs(t, err, &ne) +} + +func Test_GetUpdates_ParseError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(genTestResp(200, `not json`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetUpdatesParams{} + _, err := GetUpdates(context.Background(), bot, params) + require.Error(t, err) + var pe *client.ParseError + require.ErrorAs(t, err, &pe) +} + +func Test_GetUpdates_ContextCanceled(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return(nil, context.Canceled).Maybe() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetUpdatesParams{} + _, err := GetUpdates(ctx, bot, params) + require.Error(t, err) + require.ErrorIs(t, err, context.Canceled) +} + +// Test_GetUpdates_MissingRequiredFields exercises Telegram's server-side +// validation: when a required field is omitted, Telegram returns 400 with +// a description like "Bad Request: is empty". The library must +// surface this as *APIError with the ErrBadRequest sentinel. +func Test_GetUpdates_MissingRequiredFields(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":400,"description":"Bad Request: chat_id is empty"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + // Send a Params with all required fields zeroed — simulates a caller + // that forgot to populate them. The bot library marshals as-is and + // surfaces Telegram's 400 reply. + _, err := GetUpdates(context.Background(), bot, &GetUpdatesParams{}) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 400, ae.Code) + require.True(t, errors.Is(err, client.ErrBadRequest)) + require.False(t, ae.IsRetryable()) +} + +// Test_GetUpdates_Forbidden exercises the 403 path (bot blocked by user, +// removed from chat, etc.). The library must surface the ErrForbidden +// sentinel. +func Test_GetUpdates_Forbidden(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetUpdatesParams{} + _, err := GetUpdates(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 403, ae.Code) + require.True(t, errors.Is(err, client.ErrForbidden)) + require.False(t, ae.IsRetryable()) +} + +// Test_GetUpdates_ServerError exercises the 5xx path. The library must +// classify these as retryable so RetryDoer / user retry logic kicks in. +func Test_GetUpdates_ServerError(t *testing.T) { + m := &genTestMockDoer{} + m.On("Do", mock.Anything).Return( + genTestResp(200, `{"ok":false,"error_code":500,"description":"Internal server error"}`), nil) + + bot := client.New("test:token", client.WithHTTPClient(m)) + params := &GetUpdatesParams{} + _, err := GetUpdates(context.Background(), bot, params) + require.Error(t, err) + var ae *client.APIError + require.ErrorAs(t, err, &ae) + require.Equal(t, 500, ae.Code) + require.True(t, ae.IsRetryable(), "5xx must be retryable") +} diff --git a/testdata/golden/types.gen.go b/testdata/golden/types.gen.go new file mode 100644 index 0000000..e5b15fe --- /dev/null +++ b/testdata/golden/types.gen.go @@ -0,0 +1,75 @@ +// Code generated by cmd/genapi. DO NOT EDIT. + +//go:build !ignore_autogenerated + +// Package api contains the Telegram Bot API object types and method +// wrappers, generated from the live documentation by cmd/genapi. +package api + +import ( + "fmt" + "github.com/goccy/go-json" + "io" +) + +var _ = io.Discard // keep import even if no fields use io +var _ = json.Marshal // keep import for UnmarshalXxx helpers +var _ = fmt.Errorf // keep import for UnmarshalXxx helpers + +// This object represents a Telegram user or bot. +type User struct { + // Unique identifier. + ID int64 `json:"id"` + // True, if this user is a bot. + IsBot bool `json:"is_bot"` + // User's or bot's first name. + FirstName string `json:"first_name"` + // Optional. User's or bot's last name. + LastName string `json:"last_name,omitempty"` +} + +// ChatMember is a union type. The following concrete variants implement +// it: +// - ChatMemberOwner +// - ChatMemberAdministrator +// +// This object contains information about one member of a chat. Currently, the following 6 types of chat members are supported: +type ChatMember interface{ isChatMember() } + +// isChatMember is the marker method that makes ChatMemberOwner implement ChatMember. +func (*ChatMemberOwner) isChatMember() {} + +// isChatMember is the marker method that makes ChatMemberAdministrator implement ChatMember. +func (*ChatMemberAdministrator) isChatMember() {} + +// UnmarshalChatMember decodes a ChatMember from JSON by inspecting the +// "status" field and dispatching to the correct concrete type. +func UnmarshalChatMember(data []byte) (ChatMember, error) { + var probe struct { + V string `json:"status"` + } + if err := json.Unmarshal(data, &probe); err != nil { + return nil, err + } + var v ChatMember + switch probe.V { + case "administrator": + v = &ChatMemberAdministrator{} + case "creator": + v = &ChatMemberOwner{} + case "kicked": + v = &ChatMemberBanned{} + case "left": + v = &ChatMemberLeft{} + case "member": + v = &ChatMemberMember{} + case "restricted": + v = &ChatMemberRestricted{} + default: + return nil, fmt.Errorf("ChatMember: unknown status %q", probe.V) + } + if err := json.Unmarshal(data, v); err != nil { + return nil, err + } + return v, nil +} diff --git a/testdata/html/.gitkeep b/testdata/html/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/testdata/html/latest.html b/testdata/html/latest.html new file mode 120000 index 0000000..25c1e65 --- /dev/null +++ b/testdata/html/latest.html @@ -0,0 +1 @@ +snapshot_2026-05-08.html \ No newline at end of file diff --git a/testdata/html/small_fixture.html b/testdata/html/small_fixture.html new file mode 100644 index 0000000..997f257 --- /dev/null +++ b/testdata/html/small_fixture.html @@ -0,0 +1,68 @@ + +fixture +
        + +

        Recent changes

        +

        Bot API 7.10

        +

        Test fixture; not a real release.

        + +

        Available types

        + +

        User

        +

        This object represents a Telegram user or bot.

        +
      + + + + + + + +
      FieldTypeDescription
      idIntegerUnique identifier.
      is_botBooleanTrue, if this user is a bot.
      first_nameStringUser's or bot's first name.
      last_nameStringOptional. User's or bot's last name.
      + +

      ChatMember

      +

      This object contains information about one member of a chat. +Currently, the following 6 types of chat members are supported:

      + + +

      Available methods

      + +

      getMe

      +

      A simple method for testing your bot's authentication token. Requires +no parameters. Returns basic information about the bot in form of a User object.

      + +

      sendMessage

      +

      Use this method to send text messages. On success, the sent Message is returned.

      + + + + + + + +
      ParameterTypeRequiredDescription
      chat_idInteger or StringYesUnique identifier for the target chat.
      textStringYesText of the message to be sent.
      parse_modeStringOptionalMode for parsing entities in the message text.
      + +

      sendDocument

      +

      Use this method to send general files. On success, the sent Message is returned.

      + + + + + + + +
      ParameterTypeRequiredDescription
      chat_idIntegerYesUnique identifier for the target chat.
      documentInputFile or StringYesFile to send.
      captionStringOptionalDocument caption.
      + +

      getUpdates

      +

      Use this method to receive incoming updates using long polling. Returns an Array of Update objects.

      + + + + + +
      ParameterTypeRequiredDescription
      limitIntegerOptionalLimits the number of updates to be retrieved.
      + + diff --git a/testdata/html/snapshot_2026-05-08.html b/testdata/html/snapshot_2026-05-08.html new file mode 100644 index 0000000..86a6f20 --- /dev/null +++ b/testdata/html/snapshot_2026-05-08.html @@ -0,0 +1,19872 @@ + + + + + Telegram Bot API + + + + + + + + + + + + + + + + +
      + +
      +
      +
      + +

      Telegram Bot API

      + +
      + +
      +

      The Bot API is an HTTP-based interface created for developers keen on building bots for Telegram.
      To learn how to create and set up a bot, please consult our Introduction to Bots and Bot FAQ.

      +
      +

      Recent changes

      +
      +

      Subscribe to @BotNews to be the first to know about the latest updates and join the discussion in @BotTalk

      +
      +

      May 8, 2026

      +

      Bot API 10.0

      +

      Guest Mode

      +
        +
      • Introduced support for guest mode, allowing bots to receive certain messages and issue replies within chats they are not a member of.
      • +
      • Added the field supports_guest_queries to the class User.
      • +
      • Added the fields guest_bot_caller_user and guest_bot_caller_chat to the class Message.
      • +
      • Added the field guest_query_id to the class Message.
      • +
      • Added the field guest_message to the class Update.
      • +
      • Added the class SentGuestMessage and the method answerGuestQuery.
      • +
      +

      Chat Management

      + +

      Polls

      +
        +
      • Added the classes InputMediaSticker, InputMediaLocation, and InputMediaVenue.
      • +
      • Added the class PollMedia, representing a media in a poll.
      • +
      • Added the field media to the class Poll, allowing bots to see media in polls.
      • +
      • Added the field explanation_media to the class Poll, allowing bots to see media in quiz explanations.
      • +
      • Added the field media to the class PollOption, allowing bots to see media in poll options.
      • +
      • Added the class InputPollMedia and the parameters media and explanation_media to the method sendPoll, allowing bots to add media to polls.
      • +
      • Added the class InputPollOptionMedia and the field media to the class InputPollOption, allowing bots to add media to poll options.
      • +
      • Added the field members_only to the class Poll.
      • +
      • Added the parameter members_only to the method sendPoll.
      • +
      • Added the field country_codes to the class Poll.
      • +
      • Added the parameter country_codes to the method sendPoll.
      • +
      • Decreased the minimum number of poll options from 2 to 1.
      • +
      +

      Live photos

      + +

      General

      + +

      April 3, 2026

      +

      Bot API 9.6

      +

      Managed Bots

      + +

      Polls

      +
        +
      • Added support for quizzes with multiple correct answers.
      • +
      • Replaced the field correct_option_id with the field correct_option_ids in the class Poll.
      • +
      • Replaced the parameter correct_option_id with the parameter correct_option_ids in the method sendPoll.
      • +
      • Allowed to pass allows_multiple_answers for quizzes in the method sendPoll.
      • +
      • Increased the maximum time for automatic poll closure to 2628000 seconds.
      • +
      • Added the field allows_revoting to the class Poll.
      • +
      • Added the parameter allows_revoting to the method sendPoll.
      • +
      • Added the parameter shuffle_options to the method sendPoll.
      • +
      • Added the parameter allow_adding_options to the method sendPoll.
      • +
      • Added the parameter hide_results_until_closes to the method sendPoll.
      • +
      • Added the fields description and description_entities to the class Poll.
      • +
      • Added the parameters description, description_parse_mode, and description_entities to the method sendPoll.
      • +
      • Added the field persistent_id to the class PollOption, representing a persistent identifier for the option.
      • +
      • Added the field option_persistent_ids to the class PollAnswer.
      • +
      • Added the fields added_by_user and added_by_chat to the class PollOption, denoting the user and the chat which added the option.
      • +
      • Added the field addition_date to the class PollOption, describing the date when the option was added.
      • +
      • Added the class PollOptionAdded and the field poll_option_added to the class Message.
      • +
      • Added the class PollOptionDeleted and the field poll_option_deleted to the class Message.
      • +
      • Added the field poll_option_id to the class ReplyParameters, allowing bots to reply to a specific poll option.
      • +
      • Added the field reply_to_poll_option_id to the class Message.
      • +
      • Allowed “date_time” entities in checklist title, checklist task text, TextQuote, ReplyParameters quote, sendGift, and giftPremiumSubscription.
      • +
      +

      March 1, 2026

      +

      Bot API 9.5

      + +

      February 9, 2026

      +

      Bot API 9.4

      +
        +
      • Allowed bots to use custom emoji in messages directly sent by the bot to private, group and supergroup chats if the owner of the bot has a Telegram Premium subscription.
      • +
      • Allowed bots to create topics in private chats using the method createForumTopic.
      • +
      • Allowed bots to prevent users from creating and deleting topics in private chats through a new setting in the @BotFather Mini App.
      • +
      • Added the field allows_users_to_create_topics to the class User.
      • +
      • Added the field icon_custom_emoji_id to the classes KeyboardButton and InlineKeyboardButton, allowing bots to show a custom emoji on buttons if they are able to use custom emoji in the message.
      • +
      • Added the field style to the classes KeyboardButton and InlineKeyboardButton, allowing bots to change the color of buttons.
      • +
      • Added the class ChatOwnerLeft and the field chat_owner_left to the class Message.
      • +
      • Added the class ChatOwnerChanged and the field chat_owner_changed to the class Message.
      • +
      • Added the methods setMyProfilePhoto and removeMyProfilePhoto, allowing bots to manage their profile picture.
      • +
      • Added the class VideoQuality and the field qualities to the class Video allowing bots to get information about other available qualities of a video.
      • +
      • Added the field first_profile_audio to the class ChatFullInfo.
      • +
      • Added the class UserProfileAudios and the method getUserProfileAudios, allowing bots to fetch a list of audios added to the profile of a user.
      • +
      • Added the field rarity to the class UniqueGiftModel.
      • +
      • Added the field is_burned to the class UniqueGift.
      • +
      +

      See earlier changes »

      +

      Authorizing your bot

      +

      Each bot is given a unique authentication token when it is created. The token looks something like 123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11, but we'll use simply <token> in this document instead. You can learn about obtaining tokens and generating new ones in this document.

      +

      Making requests

      +

      All queries to the Telegram Bot API must be served over HTTPS and need to be presented in this form: https://api.telegram.org/bot<token>/METHOD_NAME. Like this for example:

      +
      https://api.telegram.org/bot123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11/getMe
      +

      We support GET and POST HTTP methods. We support four ways of passing parameters in Bot API requests:

      +
        +
      • URL query string
      • +
      • application/x-www-form-urlencoded
      • +
      • application/json (except for uploading files)
      • +
      • multipart/form-data (use to upload files)
      • +
      +

      The response contains a JSON object, which always has a Boolean field 'ok' and may have an optional String field 'description' with a human-readable description of the result. If 'ok' equals True, the request was successful and the result of the query can be found in the 'result' field. In case of an unsuccessful request, 'ok' equals false and the error is explained in the 'description'. An Integer 'error_code' field is also returned, but its contents are subject to change in the future. Some errors may also have an optional field 'parameters' of the type ResponseParameters, which can help to automatically handle the error.

      +
        +
      • All methods in the Bot API are case-insensitive.
      • +
      • All queries must be made using UTF-8.
      • +
      +

      Making requests when getting updates

      +

      If you're using webhooks, you can perform a request to the Bot API while sending an answer to the webhook. Use either application/json or application/x-www-form-urlencoded or multipart/form-data response content type for passing parameters. Specify the method to be invoked in the method parameter of the request. It's not possible to know that such a request was successful or get its result.

      +
      +

      Please see our FAQ for examples.

      +
      +

      Using a Local Bot API Server

      +

      The Bot API server source code is available at telegram-bot-api. You can run it locally and send the requests to your own server instead of https://api.telegram.org. If you switch to a local Bot API server, your bot will be able to:

      +
        +
      • Download files without a size limit.
      • +
      • Upload files up to 2000 MB.
      • +
      • Upload files using their local path and the file URI scheme.
      • +
      • Use an HTTP URL for the webhook.
      • +
      • Use any local IP address for the webhook.
      • +
      • Use any port for the webhook.
      • +
      • Set max_webhook_connections up to 100000.
      • +
      • Receive the absolute local path as a value of the file_path field without the need to download the file after a getFile request.
      • +
      +

      Do I need a Local Bot API Server

      +

      The majority of bots will be OK with the default configuration, running on our servers. But if you feel that you need one of these features, you're welcome to switch to your own at any time.

      +

      Getting updates

      +

      There are two mutually exclusive ways of receiving updates for your bot - the getUpdates method on one hand and webhooks on the other. Incoming updates are stored on the server until the bot receives them either way, but they will not be kept longer than 24 hours.

      +

      Regardless of which option you choose, you will receive JSON-serialized Update objects as a result.

      +

      Update

      +

      This object represents an incoming update.
      At most one of the optional fields can be present in any given update.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      update_idIntegerThe update's unique identifier. Update identifiers start from a certain positive number and increase sequentially. This identifier becomes especially handy if you're using webhooks, since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order. If there are no new updates for at least a week, then identifier of the next update will be chosen randomly instead of sequentially.
      messageMessageOptional. New incoming message of any kind - text, photo, sticker, etc.
      edited_messageMessageOptional. New version of a message that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.
      channel_postMessageOptional. New incoming channel post of any kind - text, photo, sticker, etc.
      edited_channel_postMessageOptional. New version of a channel post that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.
      business_connectionBusinessConnectionOptional. The bot was connected to or disconnected from a business account, or a user edited an existing connection with the bot
      business_messageMessageOptional. New message from a connected business account
      edited_business_messageMessageOptional. New version of a message from a connected business account
      deleted_business_messagesBusinessMessagesDeletedOptional. Messages were deleted from a connected business account
      guest_messageMessageOptional. New guest message. The bot can use the field Message.guest_query_id and the method answerGuestQuery to send a message in response.
      message_reactionMessageReactionUpdatedOptional. A reaction to a message was changed by a user. The bot must be an administrator in the chat and must explicitly specify "message_reaction" in the list of allowed_updates to receive these updates. The update isn't received for reactions set by bots.
      message_reaction_countMessageReactionCountUpdatedOptional. Reactions to a message with anonymous reactions were changed. The bot must be an administrator in the chat and must explicitly specify "message_reaction_count" in the list of allowed_updates to receive these updates. The updates are grouped and can be sent with delay up to a few minutes.
      inline_queryInlineQueryOptional. New incoming inline query
      chosen_inline_resultChosenInlineResultOptional. The result of an inline query that was chosen by a user and sent to their chat partner. Please see our documentation on the feedback collecting for details on how to enable these updates for your bot.
      callback_queryCallbackQueryOptional. New incoming callback query
      shipping_queryShippingQueryOptional. New incoming shipping query. Only for invoices with flexible price
      pre_checkout_queryPreCheckoutQueryOptional. New incoming pre-checkout query. Contains full information about checkout
      purchased_paid_mediaPaidMediaPurchasedOptional. A user purchased paid media with a non-empty payload sent by the bot in a non-channel chat
      pollPollOptional. New poll state. Bots receive only updates about manually stopped polls and polls, which are sent by the bot
      poll_answerPollAnswerOptional. A user changed their answer in a non-anonymous poll. Bots receive new votes only in polls that were sent by the bot itself.
      my_chat_memberChatMemberUpdatedOptional. The bot's chat member status was updated in a chat. For private chats, this update is received only when the bot is blocked or unblocked by the user.
      chat_memberChatMemberUpdatedOptional. A chat member's status was updated in a chat. The bot must be an administrator in the chat and must explicitly specify "chat_member" in the list of allowed_updates to receive these updates.
      chat_join_requestChatJoinRequestOptional. A request to join the chat has been sent. The bot must have the can_invite_users administrator right in the chat to receive these updates.
      chat_boostChatBoostUpdatedOptional. A chat boost was added or changed. The bot must be an administrator in the chat to receive these updates.
      removed_chat_boostChatBoostRemovedOptional. A boost was removed from a chat. The bot must be an administrator in the chat to receive these updates.
      managed_botManagedBotUpdatedOptional. A new bot was created to be managed by the bot, or token or owner of a managed bot was changed
      +

      getUpdates

      +

      Use this method to receive incoming updates using long polling (wiki). Returns an Array of Update objects.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      offsetIntegerOptionalIdentifier of the first update to be returned. Must be greater by one than the highest among the identifiers of previously received updates. By default, updates starting with the earliest unconfirmed update are returned. An update is considered confirmed as soon as getUpdates is called with an offset higher than its update_id. The negative offset can be specified to retrieve updates starting from -offset update from the end of the updates queue. All previous updates will be forgotten.
      limitIntegerOptionalLimits the number of updates to be retrieved. Values between 1-100 are accepted. Defaults to 100.
      timeoutIntegerOptionalTimeout in seconds for long polling. Defaults to 0, i.e. usual short polling. Should be positive, short polling should be used for testing purposes only.
      allowed_updatesArray of StringOptionalA JSON-serialized list of the update types you want your bot to receive. For example, specify ["message", "edited_channel_post", "callback_query"] to only receive updates of these types. See Update for a complete list of available update types. Specify an empty list to receive all update types except chat_member, message_reaction, and message_reaction_count (default). If not specified, the previous setting will be used.

      Please note that this parameter doesn't affect updates created before the call to getUpdates, so unwanted updates may be received for a short period of time.
      +
      +

      Notes
      1. This method will not work if an outgoing webhook is set up.
      2. In order to avoid getting duplicate updates, recalculate offset after each server response.

      +
      +

      setWebhook

      +

      Use this method to specify a URL and receive incoming updates via an outgoing webhook. Whenever there is an update for the bot, we will send an HTTPS POST request to the specified URL, containing a JSON-serialized Update. In case of an unsuccessful request (a request with response HTTP status code different from 2XY), we will repeat the request and give up after a reasonable amount of attempts. Returns True on success.

      +

      If you'd like to make sure that the webhook was set by you, you can specify secret data in the parameter secret_token. If specified, the request will contain a header “X-Telegram-Bot-Api-Secret-Token” with the secret token as content.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      urlStringYesHTTPS URL to send updates to. Use an empty string to remove webhook integration
      certificateInputFileOptionalUpload your public key certificate so that the root certificate in use can be checked. See our self-signed guide for details.
      ip_addressStringOptionalThe fixed IP address which will be used to send webhook requests instead of the IP address resolved through DNS
      max_connectionsIntegerOptionalThe maximum allowed number of simultaneous HTTPS connections to the webhook for update delivery, 1-100. Defaults to 40. Use lower values to limit the load on your bot's server, and higher values to increase your bot's throughput.
      allowed_updatesArray of StringOptionalA JSON-serialized list of the update types you want your bot to receive. For example, specify ["message", "edited_channel_post", "callback_query"] to only receive updates of these types. See Update for a complete list of available update types. Specify an empty list to receive all update types except chat_member, message_reaction, and message_reaction_count (default). If not specified, the previous setting will be used.
      Please note that this parameter doesn't affect updates created before the call to the setWebhook, so unwanted updates may be received for a short period of time.
      drop_pending_updatesBooleanOptionalPass True to drop all pending updates
      secret_tokenStringOptionalA secret token to be sent in a header “X-Telegram-Bot-Api-Secret-Token” in every webhook request, 1-256 characters. Only characters A-Z, a-z, 0-9, _ and - are allowed. The header is useful to ensure that the request comes from a webhook set by you.
      +
      +

      Notes
      1. You will not be able to receive updates using getUpdates for as long as an outgoing webhook is set up.
      2. To use a self-signed certificate, you need to upload your public key certificate using certificate parameter. Please upload as InputFile, sending a String will not work.
      3. Ports currently supported for webhooks: 443, 80, 88, 8443.

      +

      If you're having any trouble setting up webhooks, please check out this amazing guide to webhooks.

      +
      +

      deleteWebhook

      +

      Use this method to remove webhook integration if you decide to switch back to getUpdates. Returns True on success.

      + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      drop_pending_updatesBooleanOptionalPass True to drop all pending updates
      +

      getWebhookInfo

      +

      Use this method to get current webhook status. Requires no parameters. On success, returns a WebhookInfo object. If the bot is using getUpdates, will return an object with the url field empty.

      +

      WebhookInfo

      +

      Describes the current status of a webhook.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      urlStringWebhook URL, may be empty if webhook is not set up
      has_custom_certificateBooleanTrue, if a custom certificate was provided for webhook certificate checks
      pending_update_countIntegerNumber of updates awaiting delivery
      ip_addressStringOptional. Currently used webhook IP address
      last_error_dateIntegerOptional. Unix time for the most recent error that happened when trying to deliver an update via webhook
      last_error_messageStringOptional. Error message in human-readable format for the most recent error that happened when trying to deliver an update via webhook
      last_synchronization_error_dateIntegerOptional. Unix time of the most recent error that happened when trying to synchronize available updates with Telegram datacenters
      max_connectionsIntegerOptional. The maximum allowed number of simultaneous HTTPS connections to the webhook for update delivery
      allowed_updatesArray of StringOptional. A list of update types the bot is subscribed to. Defaults to all update types except chat_member
      +

      Available types

      +

      All types used in the Bot API responses are represented as JSON-objects.

      +

      It is safe to use 32-bit signed integers for storing all Integer fields unless otherwise noted.

      +
      +

      Optional fields may be not returned when irrelevant.

      +
      +

      User

      +

      This object represents a Telegram user or bot.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      idIntegerUnique identifier for this user or bot. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a 64-bit integer or double-precision float type are safe for storing this identifier.
      is_botBooleanTrue, if this user is a bot
      first_nameStringUser's or bot's first name
      last_nameStringOptional. User's or bot's last name
      usernameStringOptional. User's or bot's username
      language_codeStringOptional. IETF language tag of the user's language
      is_premiumTrueOptional. True, if this user is a Telegram Premium user
      added_to_attachment_menuTrueOptional. True, if this user added the bot to the attachment menu
      can_join_groupsBooleanOptional. True, if the bot can be invited to groups. Returned only in getMe.
      can_read_all_group_messagesBooleanOptional. True, if privacy mode is disabled for the bot. Returned only in getMe.
      supports_guest_queriesBooleanOptional. True, if the bot supports guest queries from chats it is not a member of. Returned only in getMe.
      supports_inline_queriesBooleanOptional. True, if the bot supports inline queries. Returned only in getMe.
      can_connect_to_businessBooleanOptional. True, if the bot can be connected to a user account to manage it. Returned only in getMe.
      has_main_web_appBooleanOptional. True, if the bot has a main Web App. Returned only in getMe.
      has_topics_enabledBooleanOptional. True, if the bot has forum topic mode enabled in private chats. Returned only in getMe.
      allows_users_to_create_topicsBooleanOptional. True, if the bot allows users to create and delete topics in private chats. Returned only in getMe.
      can_manage_botsBooleanOptional. True, if other bots can be created to be controlled by the bot. Returned only in getMe.
      +

      Chat

      +

      This object represents a chat.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      idIntegerUnique identifier for this chat. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this identifier.
      typeStringType of the chat, can be either “private”, “group”, “supergroup” or “channel”
      titleStringOptional. Title, for supergroups, channels and group chats
      usernameStringOptional. Username, for private chats, supergroups and channels if available
      first_nameStringOptional. First name of the other party in a private chat
      last_nameStringOptional. Last name of the other party in a private chat
      is_forumTrueOptional. True, if the supergroup chat is a forum (has topics enabled)
      is_direct_messagesTrueOptional. True, if the chat is the direct messages chat of a channel
      +

      ChatFullInfo

      +

      This object contains full information about a chat.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      idIntegerUnique identifier for this chat. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this identifier.
      typeStringType of the chat, can be either “private”, “group”, “supergroup” or “channel”
      titleStringOptional. Title, for supergroups, channels and group chats
      usernameStringOptional. Username, for private chats, supergroups and channels if available
      first_nameStringOptional. First name of the other party in a private chat
      last_nameStringOptional. Last name of the other party in a private chat
      is_forumTrueOptional. True, if the supergroup chat is a forum (has topics enabled)
      is_direct_messagesTrueOptional. True, if the chat is the direct messages chat of a channel
      accent_color_idIntegerIdentifier of the accent color for the chat name and backgrounds of the chat photo, reply header, and link preview. See accent colors for more details.
      max_reaction_countIntegerThe maximum number of reactions that can be set on a message in the chat
      photoChatPhotoOptional. Chat photo
      active_usernamesArray of StringOptional. If non-empty, the list of all active chat usernames; for private chats, supergroups and channels
      birthdateBirthdateOptional. For private chats, the date of birth of the user
      business_introBusinessIntroOptional. For private chats with business accounts, the intro of the business
      business_locationBusinessLocationOptional. For private chats with business accounts, the location of the business
      business_opening_hoursBusinessOpeningHoursOptional. For private chats with business accounts, the opening hours of the business
      personal_chatChatOptional. For private chats, the personal channel of the user
      parent_chatChatOptional. Information about the corresponding channel chat; for direct messages chats only
      available_reactionsArray of ReactionTypeOptional. List of available reactions allowed in the chat. If omitted, then all emoji reactions are allowed.
      background_custom_emoji_idStringOptional. Custom emoji identifier of the emoji chosen by the chat for the reply header and link preview background
      profile_accent_color_idIntegerOptional. Identifier of the accent color for the chat's profile background. See profile accent colors for more details.
      profile_background_custom_emoji_idStringOptional. Custom emoji identifier of the emoji chosen by the chat for its profile background
      emoji_status_custom_emoji_idStringOptional. Custom emoji identifier of the emoji status of the chat or the other party in a private chat
      emoji_status_expiration_dateIntegerOptional. Expiration date of the emoji status of the chat or the other party in a private chat, in Unix time, if any
      bioStringOptional. Bio of the other party in a private chat
      has_private_forwardsTrueOptional. True, if privacy settings of the other party in the private chat allows to use tg://user?id=<user_id> links only in chats with the user
      has_restricted_voice_and_video_messagesTrueOptional. True, if the privacy settings of the other party restrict sending voice and video note messages in the private chat
      join_to_send_messagesTrueOptional. True, if users need to join the supergroup before they can send messages
      join_by_requestTrueOptional. True, if all users directly joining the supergroup without using an invite link need to be approved by supergroup administrators
      descriptionStringOptional. Description, for groups, supergroups and channel chats
      invite_linkStringOptional. Primary invite link, for groups, supergroups and channel chats
      pinned_messageMessageOptional. The most recent pinned message (by sending date)
      permissionsChatPermissionsOptional. Default chat member permissions, for groups and supergroups
      accepted_gift_typesAcceptedGiftTypesInformation about types of gifts that are accepted by the chat or by the corresponding user for private chats
      can_send_paid_mediaTrueOptional. True, if paid media messages can be sent or forwarded to the channel chat. The field is available only for channel chats.
      slow_mode_delayIntegerOptional. For supergroups, the minimum allowed delay between consecutive messages sent by each unprivileged user; in seconds
      unrestrict_boost_countIntegerOptional. For supergroups, the minimum number of boosts that a non-administrator user needs to add in order to ignore slow mode and chat permissions
      message_auto_delete_timeIntegerOptional. The time after which all messages sent to the chat will be automatically deleted; in seconds
      has_aggressive_anti_spam_enabledTrueOptional. True, if aggressive anti-spam checks are enabled in the supergroup. The field is only available to chat administrators.
      has_hidden_membersTrueOptional. True, if non-administrators can only get the list of bots and administrators in the chat
      has_protected_contentTrueOptional. True, if messages from the chat can't be forwarded to other chats
      has_visible_historyTrueOptional. True, if new chat members will have access to old messages; available only to chat administrators
      sticker_set_nameStringOptional. For supergroups, name of the group sticker set
      can_set_sticker_setTrueOptional. True, if the bot can change the group sticker set
      custom_emoji_sticker_set_nameStringOptional. For supergroups, the name of the group's custom emoji sticker set. Custom emoji from this set can be used by all users and bots in the group.
      linked_chat_idIntegerOptional. Unique identifier for the linked chat, i.e. the discussion group identifier for a channel and vice versa; for supergroups and channel chats. This identifier may be greater than 32 bits and some programming languages may have difficulty/silent defects in interpreting it. But it is smaller than 52 bits, so a signed 64 bit integer or double-precision float type are safe for storing this identifier.
      locationChatLocationOptional. For supergroups, the location to which the supergroup is connected
      ratingUserRatingOptional. For private chats, the rating of the user if any
      first_profile_audioAudioOptional. For private chats, the first audio added to the profile of the user
      unique_gift_colorsUniqueGiftColorsOptional. The color scheme based on a unique gift that must be used for the chat's name, message replies and link previews
      paid_message_star_countIntegerOptional. The number of Telegram Stars a general user have to pay to send a message to the chat
      +

      Message

      +

      This object represents a message.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      message_idIntegerUnique message identifier inside this chat. In specific instances (e.g., message containing a video sent to a big chat), the server might automatically schedule a message instead of sending it immediately. In such cases, this field will be 0 and the relevant message will be unusable until it is actually sent
      message_thread_idIntegerOptional. Unique identifier of a message thread or forum topic to which the message belongs; for supergroups and private chats only
      direct_messages_topicDirectMessagesTopicOptional. Information about the direct messages chat topic that contains the message
      fromUserOptional. Sender of the message; may be empty for messages sent to channels. For backward compatibility, if the message was sent on behalf of a chat, the field contains a fake sender user in non-channel chats
      sender_chatChatOptional. Sender of the message when sent on behalf of a chat. For example, the supergroup itself for messages sent by its anonymous administrators or a linked channel for messages automatically forwarded to the channel's discussion group. For backward compatibility, if the message was sent on behalf of a chat, the field from contains a fake sender user in non-channel chats.
      sender_boost_countIntegerOptional. If the sender of the message boosted the chat, the number of boosts added by the user
      sender_business_botUserOptional. The bot that actually sent the message on behalf of the business account. Available only for outgoing messages sent on behalf of the connected business account.
      sender_tagStringOptional. Tag or custom title of the sender of the message; for supergroups only
      dateIntegerDate the message was sent in Unix time. It is always a positive number, representing a valid date.
      guest_query_idStringOptional. The unique identifier for the guest query. Use this identifier with the method answerGuestQuery to send a response message. If non-empty, the message belongs to the chat where the guest bot was summoned, which may not coincide with other existing bot chats sharing the same identifier.
      business_connection_idStringOptional. Unique identifier of the business connection from which the message was received. If non-empty, the message belongs to a chat of the corresponding business account that is independent from any potential bot chat which might share the same identifier.
      chatChatChat the message belongs to
      forward_originMessageOriginOptional. Information about the original message for forwarded messages
      is_topic_messageTrueOptional. True, if the message is sent to a topic in a forum supergroup or a private chat with the bot
      is_automatic_forwardTrueOptional. True, if the message is a channel post that was automatically forwarded to the connected discussion group
      reply_to_messageMessageOptional. For replies in the same chat and message thread, the original message. Note that the Message object in this field will not contain further reply_to_message fields even if it itself is a reply.
      external_replyExternalReplyInfoOptional. Information about the message that is being replied to, which may come from another chat or forum topic
      quoteTextQuoteOptional. For replies that quote part of the original message, the quoted part of the message
      reply_to_storyStoryOptional. For replies to a story, the original story
      reply_to_checklist_task_idIntegerOptional. Identifier of the specific checklist task that is being replied to
      reply_to_poll_option_idStringOptional. Persistent identifier of the specific poll option that is being replied to
      via_botUserOptional. Bot through which the message was sent
      guest_bot_caller_userUserOptional. For a message sent by a guest bot, this is the user whose original message triggered the bot's response
      guest_bot_caller_chatChatOptional. For a message sent by a guest bot, this is the chat whose original message triggered the bot's response
      edit_dateIntegerOptional. Date the message was last edited in Unix time
      has_protected_contentTrueOptional. True, if the message can't be forwarded
      is_from_offlineTrueOptional. True, if the message was sent by an implicit action, for example, as an away or a greeting business message, or as a scheduled message
      is_paid_postTrueOptional. True, if the message is a paid post. Note that such posts must not be deleted for 24 hours to receive the payment and can't be edited.
      media_group_idStringOptional. The unique identifier inside this chat of a media message group this message belongs to
      author_signatureStringOptional. Signature of the post author for messages in channels, or the custom title of an anonymous group administrator
      paid_star_countIntegerOptional. The number of Telegram Stars that were paid by the sender of the message to send it
      textStringOptional. For text messages, the actual UTF-8 text of the message
      entitiesArray of MessageEntityOptional. For text messages, special entities like usernames, URLs, bot commands, etc. that appear in the text
      link_preview_optionsLinkPreviewOptionsOptional. Options used for link preview generation for the message, if it is a text message and link preview options were changed
      suggested_post_infoSuggestedPostInfoOptional. Information about suggested post parameters if the message is a suggested post in a channel direct messages chat. If the message is an approved or declined suggested post, then it can't be edited.
      effect_idStringOptional. Unique identifier of the message effect added to the message
      animationAnimationOptional. Message is an animation, information about the animation. For backward compatibility, when this field is set, the document field will also be set
      audioAudioOptional. Message is an audio file, information about the file
      documentDocumentOptional. Message is a general file, information about the file
      live_photoLivePhotoOptional. Message is a live photo, information about the live photo. For backward compatibility, when this field is set, the photo field will also be set
      paid_mediaPaidMediaInfoOptional. Message contains paid media; information about the paid media
      photoArray of PhotoSizeOptional. Message is a photo, available sizes of the photo
      stickerStickerOptional. Message is a sticker, information about the sticker
      storyStoryOptional. Message is a forwarded story
      videoVideoOptional. Message is a video, information about the video
      video_noteVideoNoteOptional. Message is a video note, information about the video message
      voiceVoiceOptional. Message is a voice message, information about the file
      captionStringOptional. Caption for the animation, audio, document, paid media, photo, video or voice
      caption_entitiesArray of MessageEntityOptional. For messages with a caption, special entities like usernames, URLs, bot commands, etc. that appear in the caption
      show_caption_above_mediaTrueOptional. True, if the caption must be shown above the message media
      has_media_spoilerTrueOptional. True, if the message media is covered by a spoiler animation
      checklistChecklistOptional. Message is a checklist
      contactContactOptional. Message is a shared contact, information about the contact
      diceDiceOptional. Message is a dice with random value
      gameGameOptional. Message is a game, information about the game. More about games »
      pollPollOptional. Message is a native poll, information about the poll
      venueVenueOptional. Message is a venue, information about the venue. For backward compatibility, when this field is set, the location field will also be set
      locationLocationOptional. Message is a shared location, information about the location
      new_chat_membersArray of UserOptional. New members that were added to the group or supergroup and information about them (the bot itself may be one of these members)
      left_chat_memberUserOptional. A member was removed from the group, information about them (this member may be the bot itself)
      chat_owner_leftChatOwnerLeftOptional. Service message: chat owner has left
      chat_owner_changedChatOwnerChangedOptional. Service message: chat owner has changed
      new_chat_titleStringOptional. A chat title was changed to this value
      new_chat_photoArray of PhotoSizeOptional. A chat photo was change to this value
      delete_chat_photoTrueOptional. Service message: the chat photo was deleted
      group_chat_createdTrueOptional. Service message: the group has been created
      supergroup_chat_createdTrueOptional. Service message: the supergroup has been created. This field can't be received in a message coming through updates, because bot can't be a member of a supergroup when it is created. It can only be found in reply_to_message if someone replies to a very first message in a directly created supergroup.
      channel_chat_createdTrueOptional. Service message: the channel has been created. This field can't be received in a message coming through updates, because bot can't be a member of a channel when it is created. It can only be found in reply_to_message if someone replies to a very first message in a channel.
      message_auto_delete_timer_changedMessageAutoDeleteTimerChangedOptional. Service message: auto-delete timer settings changed in the chat
      migrate_to_chat_idIntegerOptional. The group has been migrated to a supergroup with the specified identifier. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this identifier.
      migrate_from_chat_idIntegerOptional. The supergroup has been migrated from a group with the specified identifier. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this identifier.
      pinned_messageMaybeInaccessibleMessageOptional. Specified message was pinned. Note that the Message object in this field will not contain further reply_to_message fields even if it itself is a reply.
      invoiceInvoiceOptional. Message is an invoice for a payment, information about the invoice. More about payments »
      successful_paymentSuccessfulPaymentOptional. Message is a service message about a successful payment, information about the payment. More about payments »
      refunded_paymentRefundedPaymentOptional. Message is a service message about a refunded payment, information about the payment. More about payments »
      users_sharedUsersSharedOptional. Service message: users were shared with the bot
      chat_sharedChatSharedOptional. Service message: a chat was shared with the bot
      giftGiftInfoOptional. Service message: a regular gift was sent or received
      unique_giftUniqueGiftInfoOptional. Service message: a unique gift was sent or received
      gift_upgrade_sentGiftInfoOptional. Service message: upgrade of a gift was purchased after the gift was sent
      connected_websiteStringOptional. The domain name of the website on which the user has logged in. More about Telegram Login »
      write_access_allowedWriteAccessAllowedOptional. Service message: the user allowed the bot to write messages after adding it to the attachment or side menu, launching a Web App from a link, or accepting an explicit request from a Web App sent by the method requestWriteAccess
      passport_dataPassportDataOptional. Telegram Passport data
      proximity_alert_triggeredProximityAlertTriggeredOptional. Service message. A user in the chat triggered another user's proximity alert while sharing Live Location.
      boost_addedChatBoostAddedOptional. Service message: user boosted the chat
      chat_background_setChatBackgroundOptional. Service message: chat background set
      checklist_tasks_doneChecklistTasksDoneOptional. Service message: some tasks in a checklist were marked as done or not done
      checklist_tasks_addedChecklistTasksAddedOptional. Service message: tasks were added to a checklist
      direct_message_price_changedDirectMessagePriceChangedOptional. Service message: the price for paid messages in the corresponding direct messages chat of a channel has changed
      forum_topic_createdForumTopicCreatedOptional. Service message: forum topic created
      forum_topic_editedForumTopicEditedOptional. Service message: forum topic edited
      forum_topic_closedForumTopicClosedOptional. Service message: forum topic closed
      forum_topic_reopenedForumTopicReopenedOptional. Service message: forum topic reopened
      general_forum_topic_hiddenGeneralForumTopicHiddenOptional. Service message: the 'General' forum topic hidden
      general_forum_topic_unhiddenGeneralForumTopicUnhiddenOptional. Service message: the 'General' forum topic unhidden
      giveaway_createdGiveawayCreatedOptional. Service message: a scheduled giveaway was created
      giveawayGiveawayOptional. The message is a scheduled giveaway message
      giveaway_winnersGiveawayWinnersOptional. A giveaway with public winners was completed
      giveaway_completedGiveawayCompletedOptional. Service message: a giveaway without public winners was completed
      managed_bot_createdManagedBotCreatedOptional. Service message: user created a bot that will be managed by the current bot
      paid_message_price_changedPaidMessagePriceChangedOptional. Service message: the price for paid messages has changed in the chat
      poll_option_addedPollOptionAddedOptional. Service message: answer option was added to a poll
      poll_option_deletedPollOptionDeletedOptional. Service message: answer option was deleted from a poll
      suggested_post_approvedSuggestedPostApprovedOptional. Service message: a suggested post was approved
      suggested_post_approval_failedSuggestedPostApprovalFailedOptional. Service message: approval of a suggested post has failed
      suggested_post_declinedSuggestedPostDeclinedOptional. Service message: a suggested post was declined
      suggested_post_paidSuggestedPostPaidOptional. Service message: payment for a suggested post was received
      suggested_post_refundedSuggestedPostRefundedOptional. Service message: payment for a suggested post was refunded
      video_chat_scheduledVideoChatScheduledOptional. Service message: video chat scheduled
      video_chat_startedVideoChatStartedOptional. Service message: video chat started
      video_chat_endedVideoChatEndedOptional. Service message: video chat ended
      video_chat_participants_invitedVideoChatParticipantsInvitedOptional. Service message: new participants invited to a video chat
      web_app_dataWebAppDataOptional. Service message: data sent by a Web App
      reply_markupInlineKeyboardMarkupOptional. Inline keyboard attached to the message. login_url buttons are represented as ordinary url buttons.
      +

      MessageId

      +

      This object represents a unique message identifier.

      + + + + + + + + + + + + + + + +
      FieldTypeDescription
      message_idIntegerUnique message identifier. In specific instances (e.g., message containing a video sent to a big chat), the server might automatically schedule a message instead of sending it immediately. In such cases, this field will be 0 and the relevant message will be unusable until it is actually sent
      +

      InaccessibleMessage

      +

      This object describes a message that was deleted or is otherwise inaccessible to the bot.

      + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      chatChatChat the message belonged to
      message_idIntegerUnique message identifier inside the chat
      dateIntegerAlways 0. The field can be used to differentiate regular and inaccessible messages.
      +

      MaybeInaccessibleMessage

      +

      This object describes a message that can be inaccessible to the bot. It can be one of

      + +

      MessageEntity

      +

      This object represents one special entity in a text message. For example, hashtags, usernames, URLs, etc.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringType of the entity. Currently, can be “mention” (@username), “hashtag” (#hashtag or #hashtag@chatusername), “cashtag” ($USD or $USD@chatusername), “bot_command” (/start@jobs_bot), “url” (https://telegram.org), “email” (do-not-reply@telegram.org), “phone_number” (+1-212-555-0123), “bold” (bold text), “italic” (italic text), “underline” (underlined text), “strikethrough” (strikethrough text), “spoiler” (spoiler message), “blockquote” (block quotation), “expandable_blockquote” (collapsed-by-default block quotation), “code” (monowidth string), “pre” (monowidth block), “text_link” (for clickable text URLs), “text_mention” (for users without usernames), “custom_emoji” (for inline custom emoji stickers), or “date_time” (for formatted date and time)
      offsetIntegerOffset in UTF-16 code units to the start of the entity
      lengthIntegerLength of the entity in UTF-16 code units
      urlStringOptional. For “text_link” only, URL that will be opened after user taps on the text
      userUserOptional. For “text_mention” only, the mentioned user
      languageStringOptional. For “pre” only, the programming language of the entity text
      custom_emoji_idStringOptional. For “custom_emoji” only, unique identifier of the custom emoji. Use getCustomEmojiStickers to get full information about the sticker
      unix_timeIntegerOptional. For “date_time” only, the Unix time associated with the entity
      date_time_formatStringOptional. For “date_time” only, the string that defines the formatting of the date and time. See date-time entity formatting for more details.
      +

      TextQuote

      +

      This object contains information about the quoted part of a message that is replied to by the given message.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      textStringText of the quoted part of a message that is replied to by the given message
      entitiesArray of MessageEntityOptional. Special entities that appear in the quote. Currently, only bold, italic, underline, strikethrough, spoiler, custom_emoji, and date_time entities are kept in quotes.
      positionIntegerApproximate quote position in the original message in UTF-16 code units as specified by the sender
      is_manualTrueOptional. True, if the quote was chosen manually by the message sender. Otherwise, the quote was added automatically by the server.
      +

      ExternalReplyInfo

      +

      This object contains information about a message that is being replied to, which may come from another chat or forum topic.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      originMessageOriginOrigin of the message replied to by the given message
      chatChatOptional. Chat the original message belongs to. Available only if the chat is a supergroup or a channel.
      message_idIntegerOptional. Unique message identifier inside the original chat. Available only if the original chat is a supergroup or a channel.
      link_preview_optionsLinkPreviewOptionsOptional. Options used for link preview generation for the original message, if it is a text message
      animationAnimationOptional. Message is an animation, information about the animation
      audioAudioOptional. Message is an audio file, information about the file
      documentDocumentOptional. Message is a general file, information about the file
      live_photoLivePhotoOptional. Message is a live photo, information about the live photo
      paid_mediaPaidMediaInfoOptional. Message contains paid media; information about the paid media
      photoArray of PhotoSizeOptional. Message is a photo, available sizes of the photo
      stickerStickerOptional. Message is a sticker, information about the sticker
      storyStoryOptional. Message is a forwarded story
      videoVideoOptional. Message is a video, information about the video
      video_noteVideoNoteOptional. Message is a video note, information about the video message
      voiceVoiceOptional. Message is a voice message, information about the file
      has_media_spoilerTrueOptional. True, if the message media is covered by a spoiler animation
      checklistChecklistOptional. Message is a checklist
      contactContactOptional. Message is a shared contact, information about the contact
      diceDiceOptional. Message is a dice with random value
      gameGameOptional. Message is a game, information about the game. More about games »
      giveawayGiveawayOptional. Message is a scheduled giveaway, information about the giveaway
      giveaway_winnersGiveawayWinnersOptional. A giveaway with public winners was completed
      invoiceInvoiceOptional. Message is an invoice for a payment, information about the invoice. More about payments »
      locationLocationOptional. Message is a shared location, information about the location
      pollPollOptional. Message is a native poll, information about the poll
      venueVenueOptional. Message is a venue, information about the venue
      +

      ReplyParameters

      +

      Describes reply parameters for the message that is being sent.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      message_idIntegerIdentifier of the message that will be replied to in the current chat, or in the chat chat_id if it is specified
      chat_idInteger or StringOptional. If the message to be replied to is from a different chat, unique identifier for the chat or username of the bot, supergroup or channel in the format @username. Not supported for messages sent on behalf of a business account and messages from channel direct messages chats.
      allow_sending_without_replyBooleanOptional. Pass True if the message should be sent even if the specified message to be replied to is not found. Always False for replies in another chat or forum topic. Always True for messages sent on behalf of a business account.
      quoteStringOptional. Quoted part of the message to be replied to; 0-1024 characters after entities parsing. The quote must be an exact substring of the message to be replied to, including bold, italic, underline, strikethrough, spoiler, custom_emoji, and date_time entities. The message will fail to send if the quote isn't found in the original message.
      quote_parse_modeStringOptional. Mode for parsing entities in the quote. See formatting options for more details.
      quote_entitiesArray of MessageEntityOptional. A JSON-serialized list of special entities that appear in the quote. It can be specified instead of quote_parse_mode.
      quote_positionIntegerOptional. Position of the quote in the original message in UTF-16 code units
      checklist_task_idIntegerOptional. Identifier of the specific checklist task to be replied to
      poll_option_idStringOptional. Persistent identifier of the specific poll option to be replied to
      +

      MessageOrigin

      +

      This object describes the origin of a message. It can be one of

      + +

      MessageOriginUser

      +

      The message was originally sent by a known user.

      + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringType of the message origin, always “user”
      dateIntegerDate the message was sent originally in Unix time
      sender_userUserUser that sent the message originally
      +

      MessageOriginHiddenUser

      +

      The message was originally sent by an unknown user.

      + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringType of the message origin, always “hidden_user”
      dateIntegerDate the message was sent originally in Unix time
      sender_user_nameStringName of the user that sent the message originally
      +

      MessageOriginChat

      +

      The message was originally sent on behalf of a chat to a group chat.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringType of the message origin, always “chat”
      dateIntegerDate the message was sent originally in Unix time
      sender_chatChatChat that sent the message originally
      author_signatureStringOptional. For messages originally sent by an anonymous chat administrator, original message author signature
      +

      MessageOriginChannel

      +

      The message was originally sent to a channel chat.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringType of the message origin, always “channel”
      dateIntegerDate the message was sent originally in Unix time
      chatChatChannel chat to which the message was originally sent
      message_idIntegerUnique message identifier inside the chat
      author_signatureStringOptional. Signature of the original post author
      +

      PhotoSize

      +

      This object represents one size of a photo or a file / sticker thumbnail.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      file_idStringIdentifier for this file, which can be used to download or reuse the file
      file_unique_idStringUnique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file.
      widthIntegerPhoto width
      heightIntegerPhoto height
      file_sizeIntegerOptional. File size in bytes
      +

      Animation

      +

      This object represents an animation file (GIF or H.264/MPEG-4 AVC video without sound).

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      file_idStringIdentifier for this file, which can be used to download or reuse the file
      file_unique_idStringUnique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file.
      widthIntegerVideo width as defined by the sender
      heightIntegerVideo height as defined by the sender
      durationIntegerDuration of the video in seconds as defined by the sender
      thumbnailPhotoSizeOptional. Animation thumbnail as defined by the sender
      file_nameStringOptional. Original animation filename as defined by the sender
      mime_typeStringOptional. MIME type of the file as defined by the sender
      file_sizeIntegerOptional. File size in bytes. It can be bigger than 2^31 and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this value.
      +

      Audio

      +

      This object represents an audio file to be treated as music by the Telegram clients.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      file_idStringIdentifier for this file, which can be used to download or reuse the file
      file_unique_idStringUnique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file.
      durationIntegerDuration of the audio in seconds as defined by the sender
      performerStringOptional. Performer of the audio as defined by the sender or by audio tags
      titleStringOptional. Title of the audio as defined by the sender or by audio tags
      file_nameStringOptional. Original filename as defined by the sender
      mime_typeStringOptional. MIME type of the file as defined by the sender
      file_sizeIntegerOptional. File size in bytes. It can be bigger than 2^31 and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this value.
      thumbnailPhotoSizeOptional. Thumbnail of the album cover to which the music file belongs
      +

      Document

      +

      This object represents a general file (as opposed to photos, voice messages and audio files).

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      file_idStringIdentifier for this file, which can be used to download or reuse the file
      file_unique_idStringUnique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file.
      thumbnailPhotoSizeOptional. Document thumbnail as defined by the sender
      file_nameStringOptional. Original filename as defined by the sender
      mime_typeStringOptional. MIME type of the file as defined by the sender
      file_sizeIntegerOptional. File size in bytes. It can be bigger than 2^31 and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this value.
      +

      LivePhoto

      +

      This object represents a live photo.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      photoArray of PhotoSizeOptional. Available sizes of the corresponding static photo
      file_idStringIdentifier for the video file which can be used to download or reuse the file
      file_unique_idStringUnique identifier for the video file which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file.
      widthIntegerVideo width as defined by the sender
      heightIntegerVideo height as defined by the sender
      durationIntegerDuration of the video in seconds as defined by the sender
      mime_typeStringOptional. MIME type of the file as defined by the sender
      file_sizeIntegerOptional. File size in bytes. It can be bigger than 2^31 and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this value.
      +

      Story

      +

      This object represents a story.

      + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      chatChatChat that posted the story
      idIntegerUnique identifier for the story in the chat
      +

      VideoQuality

      +

      This object represents a video file of a specific quality.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      file_idStringIdentifier for this file, which can be used to download or reuse the file
      file_unique_idStringUnique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file.
      widthIntegerVideo width
      heightIntegerVideo height
      codecStringCodec that was used to encode the video, for example, “h264”, “h265”, or “av01”
      file_sizeIntegerOptional. File size in bytes. It can be bigger than 2^31 and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this value.
      +

      Video

      +

      This object represents a video file.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      file_idStringIdentifier for this file, which can be used to download or reuse the file
      file_unique_idStringUnique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file.
      widthIntegerVideo width as defined by the sender
      heightIntegerVideo height as defined by the sender
      durationIntegerDuration of the video in seconds as defined by the sender
      thumbnailPhotoSizeOptional. Video thumbnail
      coverArray of PhotoSizeOptional. Available sizes of the cover of the video in the message
      start_timestampIntegerOptional. Timestamp in seconds from which the video will play in the message
      qualitiesArray of VideoQualityOptional. List of available qualities of the video
      file_nameStringOptional. Original filename as defined by the sender
      mime_typeStringOptional. MIME type of the file as defined by the sender
      file_sizeIntegerOptional. File size in bytes. It can be bigger than 2^31 and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this value.
      +

      VideoNote

      +

      This object represents a video message (available in Telegram apps as of v.4.0).

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      file_idStringIdentifier for this file, which can be used to download or reuse the file
      file_unique_idStringUnique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file.
      lengthIntegerVideo width and height (diameter of the video message) as defined by the sender
      durationIntegerDuration of the video in seconds as defined by the sender
      thumbnailPhotoSizeOptional. Video thumbnail
      file_sizeIntegerOptional. File size in bytes
      +

      Voice

      +

      This object represents a voice note.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      file_idStringIdentifier for this file, which can be used to download or reuse the file
      file_unique_idStringUnique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file.
      durationIntegerDuration of the audio in seconds as defined by the sender
      mime_typeStringOptional. MIME type of the file as defined by the sender
      file_sizeIntegerOptional. File size in bytes. It can be bigger than 2^31 and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this value.
      +

      PaidMediaInfo

      +

      Describes the paid media added to a message.

      + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      star_countIntegerThe number of Telegram Stars that must be paid to buy access to the media
      paid_mediaArray of PaidMediaInformation about the paid media
      +

      PaidMedia

      +

      This object describes paid media. Currently, it can be one of

      + +

      PaidMediaLivePhoto

      +

      The paid media is a live photo.

      + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringType of the paid media, always “live_photo”
      live_photoLivePhotoThe photo
      +

      PaidMediaPhoto

      +

      The paid media is a photo.

      + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringType of the paid media, always “photo”
      photoArray of PhotoSizeThe photo
      +

      PaidMediaPreview

      +

      The paid media isn't available before the payment.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringType of the paid media, always “preview”
      widthIntegerOptional. Media width as defined by the sender
      heightIntegerOptional. Media height as defined by the sender
      durationIntegerOptional. Duration of the media in seconds as defined by the sender
      +

      PaidMediaVideo

      +

      The paid media is a video.

      + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringType of the paid media, always “video”
      videoVideoThe video
      +

      Contact

      +

      This object represents a phone contact.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      phone_numberStringContact's phone number
      first_nameStringContact's first name
      last_nameStringOptional. Contact's last name
      user_idIntegerOptional. Contact's user identifier in Telegram. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a 64-bit integer or double-precision float type are safe for storing this identifier.
      vcardStringOptional. Additional data about the contact in the form of a vCard
      +

      Dice

      +

      This object represents an animated emoji that displays a random value.

      + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      emojiStringEmoji on which the dice throw animation is based
      valueIntegerValue of the dice, 1-6 for “🎲”, “🎯” and “🎳” base emoji, 1-5 for “🏀” and “⚽” base emoji, 1-64 for “🎰” base emoji
      +

      PollMedia

      +

      At most one of the optional fields can be present in any given object.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      animationAnimationOptional. Media is an animation, information about the animation
      audioAudioOptional. Media is an audio file, information about the file; currently, can't be received in a poll option
      documentDocumentOptional. Media is a general file, information about the file; currently, can't be received in a poll option
      live_photoLivePhotoOptional. Media is a live photo, information about the live photo
      locationLocationOptional. Media is a shared location, information about the location
      photoArray of PhotoSizeOptional. Media is a photo, available sizes of the photo
      stickerStickerOptional. Media is a sticker, information about the sticker; currently, for poll options only
      venueVenueOptional. Media is a venue, information about the venue
      videoVideoOptional. Media is a video, information about the video
      +

      InputPollMedia

      +

      This object represents the content of a poll description or a quiz explanation to be sent. It should be one of

      + +

      InputPollOptionMedia

      +

      This object represents the content of a poll option to be sent. It should be one of

      + +

      PollOption

      +

      This object contains information about one answer option in a poll.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      persistent_idStringUnique identifier of the option, persistent on option addition and deletion
      textStringOption text, 1-100 characters
      text_entitiesArray of MessageEntityOptional. Special entities that appear in the option text. Currently, only custom emoji entities are allowed in poll option texts
      mediaPollMediaOptional. Media added to the poll option
      voter_countIntegerNumber of users who voted for this option; may be 0 if unknown
      added_by_userUserOptional. User who added the option; omitted if the option wasn't added by a user after poll creation
      added_by_chatChatOptional. Chat that added the option; omitted if the option wasn't added by a chat after poll creation
      addition_dateIntegerOptional. Point in time (Unix timestamp) when the option was added; omitted if the option existed in the original poll
      +

      InputPollOption

      +

      This object contains information about one answer option in a poll to be sent.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      textStringOption text, 1-100 characters
      text_parse_modeStringOptional. Mode for parsing entities in the text. See formatting options for more details. Currently, only custom emoji entities are allowed
      text_entitiesArray of MessageEntityOptional. A JSON-serialized list of special entities that appear in the poll option text. It can be specified instead of text_parse_mode
      mediaInputPollOptionMediaOptional. Media added to the poll option
      +

      PollAnswer

      +

      This object represents an answer of a user in a non-anonymous poll.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      poll_idStringUnique poll identifier
      voter_chatChatOptional. The chat that changed the answer to the poll, if the voter is anonymous
      userUserOptional. The user that changed the answer to the poll, if the voter isn't anonymous
      option_idsArray of Integer0-based identifiers of chosen answer options. May be empty if the vote was retracted.
      option_persistent_idsArray of StringPersistent identifiers of the chosen answer options. May be empty if the vote was retracted.
      +

      Poll

      +

      This object contains information about a poll.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      idStringUnique poll identifier
      questionStringPoll question, 1-300 characters
      question_entitiesArray of MessageEntityOptional. Special entities that appear in the question. Currently, only custom emoji entities are allowed in poll questions
      optionsArray of PollOptionList of poll options
      total_voter_countIntegerTotal number of users that voted in the poll
      is_closedBooleanTrue, if the poll is closed
      is_anonymousBooleanTrue, if the poll is anonymous
      typeStringPoll type, currently can be “regular” or “quiz”
      allows_multiple_answersBooleanTrue, if the poll allows multiple answers
      allows_revotingBooleanTrue, if the poll allows to change the chosen answer options
      members_onlyBooleanTrue if voting is limited to users who have been members of the chat where the poll was originally sent for more than 24 hours
      country_codesArray of StringOptional. A list of two-letter ISO 3166-1 alpha-2 country codes indicating the countries from which users can vote in the poll. If omitted, then users from any country can participate in the poll.
      correct_option_idsArray of IntegerOptional. Array of 0-based identifiers of the correct answer options. Available only for polls in quiz mode which are closed or were sent (not forwarded) by the bot or to the private chat with the bot.
      explanationStringOptional. Text that is shown when a user chooses an incorrect answer or taps on the lamp icon in a quiz-style poll, 0-200 characters
      explanation_entitiesArray of MessageEntityOptional. Special entities like usernames, URLs, bot commands, etc. that appear in the explanation
      explanation_mediaPollMediaOptional. Media added to the quiz explanation
      open_periodIntegerOptional. Amount of time in seconds the poll will be active after creation
      close_dateIntegerOptional. Point in time (Unix timestamp) when the poll will be automatically closed
      descriptionStringOptional. Description of the poll; for polls inside the Message object only
      description_entitiesArray of MessageEntityOptional. Special entities like usernames, URLs, bot commands, etc. that appear in the description
      mediaPollMediaOptional. Media added to the poll description; for polls inside the Message object only
      +

      ChecklistTask

      +

      Describes a task in a checklist.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      idIntegerUnique identifier of the task
      textStringText of the task
      text_entitiesArray of MessageEntityOptional. Special entities that appear in the task text
      completed_by_userUserOptional. User that completed the task; omitted if the task wasn't completed by a user
      completed_by_chatChatOptional. Chat that completed the task; omitted if the task wasn't completed by a chat
      completion_dateIntegerOptional. Point in time (Unix timestamp) when the task was completed; 0 if the task wasn't completed
      +

      Checklist

      +

      Describes a checklist.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      titleStringTitle of the checklist
      title_entitiesArray of MessageEntityOptional. Special entities that appear in the checklist title
      tasksArray of ChecklistTaskList of tasks in the checklist
      others_can_add_tasksTrueOptional. True, if users other than the creator of the list can add tasks to the list
      others_can_mark_tasks_as_doneTrueOptional. True, if users other than the creator of the list can mark tasks as done or not done
      +

      InputChecklistTask

      +

      Describes a task to add to a checklist.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      idIntegerUnique identifier of the task; must be positive and unique among all task identifiers currently present in the checklist
      textStringText of the task; 1-100 characters after entities parsing
      parse_modeStringOptional. Mode for parsing entities in the text. See formatting options for more details.
      text_entitiesArray of MessageEntityOptional. List of special entities that appear in the text, which can be specified instead of parse_mode. Currently, only bold, italic, underline, strikethrough, spoiler, custom_emoji, and date_time entities are allowed.
      +

      InputChecklist

      +

      Describes a checklist to create.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      titleStringTitle of the checklist; 1-255 characters after entities parsing
      parse_modeStringOptional. Mode for parsing entities in the title. See formatting options for more details.
      title_entitiesArray of MessageEntityOptional. List of special entities that appear in the title, which can be specified instead of parse_mode. Currently, only bold, italic, underline, strikethrough, spoiler, custom_emoji, and date_time entities are allowed.
      tasksArray of InputChecklistTaskList of 1-30 tasks in the checklist
      others_can_add_tasksBooleanOptional. Pass True if other users can add tasks to the checklist
      others_can_mark_tasks_as_doneBooleanOptional. Pass True if other users can mark tasks as done or not done in the checklist
      +

      ChecklistTasksDone

      +

      Describes a service message about checklist tasks marked as done or not done.

      + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      checklist_messageMessageOptional. Message containing the checklist whose tasks were marked as done or not done. Note that the Message object in this field will not contain the reply_to_message field even if it itself is a reply.
      marked_as_done_task_idsArray of IntegerOptional. Identifiers of the tasks that were marked as done
      marked_as_not_done_task_idsArray of IntegerOptional. Identifiers of the tasks that were marked as not done
      +

      ChecklistTasksAdded

      +

      Describes a service message about tasks added to a checklist.

      + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      checklist_messageMessageOptional. Message containing the checklist to which the tasks were added. Note that the Message object in this field will not contain the reply_to_message field even if it itself is a reply.
      tasksArray of ChecklistTaskList of tasks added to the checklist
      +

      Location

      +

      This object represents a point on the map.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      latitudeFloatLatitude as defined by the sender
      longitudeFloatLongitude as defined by the sender
      horizontal_accuracyFloatOptional. The radius of uncertainty for the location, measured in meters; 0-1500
      live_periodIntegerOptional. Time relative to the message sending date, during which the location can be updated; in seconds. For active live locations only.
      headingIntegerOptional. The direction in which user is moving, in degrees; 1-360. For active live locations only.
      proximity_alert_radiusIntegerOptional. The maximum distance for proximity alerts about approaching another chat member, in meters. For sent live locations only.
      +

      Venue

      +

      This object represents a venue.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      locationLocationVenue location. Can't be a live location
      titleStringName of the venue
      addressStringAddress of the venue
      foursquare_idStringOptional. Foursquare identifier of the venue
      foursquare_typeStringOptional. Foursquare type of the venue. (For example, “arts_entertainment/default”, “arts_entertainment/aquarium” or “food/icecream”.)
      google_place_idStringOptional. Google Places identifier of the venue
      google_place_typeStringOptional. Google Places type of the venue. (See supported types.)
      +

      WebAppData

      +

      Describes data sent from a Web App to the bot.

      + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      dataStringThe data. Be aware that a bad client can send arbitrary data in this field.
      button_textStringText of the web_app keyboard button from which the Web App was opened. Be aware that a bad client can send arbitrary data in this field.
      +

      ProximityAlertTriggered

      +

      This object represents the content of a service message, sent whenever a user in the chat triggers a proximity alert set by another user.

      + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      travelerUserUser that triggered the alert
      watcherUserUser that set the alert
      distanceIntegerThe distance between the users
      +

      MessageAutoDeleteTimerChanged

      +

      This object represents a service message about a change in auto-delete timer settings.

      + + + + + + + + + + + + + + + +
      FieldTypeDescription
      message_auto_delete_timeIntegerNew auto-delete time for messages in the chat; in seconds
      +

      ManagedBotCreated

      +

      This object contains information about the bot that was created to be managed by the current bot.

      + + + + + + + + + + + + + + + +
      FieldTypeDescription
      botUserInformation about the bot. The bot's token can be fetched using the method getManagedBotToken.
      +

      ManagedBotUpdated

      +

      This object contains information about the creation, token update, or owner update of a bot that is managed by the current bot.

      + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      userUserUser that created the bot
      botUserInformation about the bot. Token of the bot can be fetched using the method getManagedBotToken.
      +

      PollOptionAdded

      +

      Describes a service message about an option added to a poll.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      poll_messageMaybeInaccessibleMessageOptional. Message containing the poll to which the option was added, if known. Note that the Message object in this field will not contain the reply_to_message field even if it itself is a reply.
      option_persistent_idStringUnique identifier of the added option
      option_textStringOption text
      option_text_entitiesArray of MessageEntityOptional. Special entities that appear in the option_text
      +

      PollOptionDeleted

      +

      Describes a service message about an option deleted from a poll.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      poll_messageMaybeInaccessibleMessageOptional. Message containing the poll from which the option was deleted, if known. Note that the Message object in this field will not contain the reply_to_message field even if it itself is a reply.
      option_persistent_idStringUnique identifier of the deleted option
      option_textStringOption text
      option_text_entitiesArray of MessageEntityOptional. Special entities that appear in the option_text
      +

      ChatBoostAdded

      +

      This object represents a service message about a user boosting a chat.

      + + + + + + + + + + + + + + + +
      FieldTypeDescription
      boost_countIntegerNumber of boosts added by the user
      +

      BackgroundFill

      +

      This object describes the way a background is filled based on the selected colors. Currently, it can be one of

      + +

      BackgroundFillSolid

      +

      The background is filled using the selected color.

      + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringType of the background fill, always “solid”
      colorIntegerThe color of the background fill in the RGB24 format
      +

      BackgroundFillGradient

      +

      The background is a gradient fill.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringType of the background fill, always “gradient”
      top_colorIntegerTop color of the gradient in the RGB24 format
      bottom_colorIntegerBottom color of the gradient in the RGB24 format
      rotation_angleIntegerClockwise rotation angle of the background fill in degrees; 0-359
      +

      BackgroundFillFreeformGradient

      +

      The background is a freeform gradient that rotates after every message in the chat.

      + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringType of the background fill, always “freeform_gradient”
      colorsArray of IntegerA list of the 3 or 4 base colors that are used to generate the freeform gradient in the RGB24 format
      +

      BackgroundType

      +

      This object describes the type of a background. Currently, it can be one of

      + +

      BackgroundTypeFill

      +

      The background is automatically filled based on the selected colors.

      + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringType of the background, always “fill”
      fillBackgroundFillThe background fill
      dark_theme_dimmingIntegerDimming of the background in dark themes, as a percentage; 0-100
      +

      BackgroundTypeWallpaper

      +

      The background is a wallpaper in the JPEG format.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringType of the background, always “wallpaper”
      documentDocumentDocument with the wallpaper
      dark_theme_dimmingIntegerDimming of the background in dark themes, as a percentage; 0-100
      is_blurredTrueOptional. True, if the wallpaper is downscaled to fit in a 450x450 square and then box-blurred with radius 12
      is_movingTrueOptional. True, if the background moves slightly when the device is tilted
      +

      BackgroundTypePattern

      +

      The background is a .PNG or .TGV (gzipped subset of SVG with MIME type “application/x-tgwallpattern”) pattern to be combined with the background fill chosen by the user.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringType of the background, always “pattern”
      documentDocumentDocument with the pattern
      fillBackgroundFillThe background fill that is combined with the pattern
      intensityIntegerIntensity of the pattern when it is shown above the filled background; 0-100
      is_invertedTrueOptional. True, if the background fill must be applied only to the pattern itself. All other pixels are black in this case. For dark themes only
      is_movingTrueOptional. True, if the background moves slightly when the device is tilted
      +

      BackgroundTypeChatTheme

      +

      The background is taken directly from a built-in chat theme.

      + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringType of the background, always “chat_theme”
      theme_nameStringName of the chat theme, which is usually an emoji
      +

      ChatBackground

      +

      This object represents a chat background.

      + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeBackgroundTypeType of the background
      +

      ForumTopicCreated

      +

      This object represents a service message about a new forum topic created in the chat.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      nameStringName of the topic
      icon_colorIntegerColor of the topic icon in RGB format
      icon_custom_emoji_idStringOptional. Unique identifier of the custom emoji shown as the topic icon
      is_name_implicitTrueOptional. True, if the name of the topic wasn't specified explicitly by its creator and likely needs to be changed by the bot
      +

      ForumTopicClosed

      +

      This object represents a service message about a forum topic closed in the chat. Currently holds no information.

      +

      ForumTopicEdited

      +

      This object represents a service message about an edited forum topic.

      + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      nameStringOptional. New name of the topic, if it was edited
      icon_custom_emoji_idStringOptional. New identifier of the custom emoji shown as the topic icon, if it was edited; an empty string if the icon was removed
      +

      ForumTopicReopened

      +

      This object represents a service message about a forum topic reopened in the chat. Currently holds no information.

      +

      GeneralForumTopicHidden

      +

      This object represents a service message about General forum topic hidden in the chat. Currently holds no information.

      +

      GeneralForumTopicUnhidden

      +

      This object represents a service message about General forum topic unhidden in the chat. Currently holds no information.

      +

      SharedUser

      +

      This object contains information about a user that was shared with the bot using a KeyboardButtonRequestUsers button.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      user_idIntegerIdentifier of the shared user. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so 64-bit integers or double-precision float types are safe for storing these identifiers. The bot may not have access to the user and could be unable to use this identifier, unless the user is already known to the bot by some other means.
      first_nameStringOptional. First name of the user, if the name was requested by the bot
      last_nameStringOptional. Last name of the user, if the name was requested by the bot
      usernameStringOptional. Username of the user, if the username was requested by the bot
      photoArray of PhotoSizeOptional. Available sizes of the chat photo, if the photo was requested by the bot
      +

      UsersShared

      +

      This object contains information about the users whose identifiers were shared with the bot using a KeyboardButtonRequestUsers button.

      + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      request_idIntegerIdentifier of the request
      usersArray of SharedUserInformation about users shared with the bot.
      +

      ChatShared

      +

      This object contains information about a chat that was shared with the bot using a KeyboardButtonRequestChat button.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      request_idIntegerIdentifier of the request
      chat_idIntegerIdentifier of the shared chat. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a 64-bit integer or double-precision float type are safe for storing this identifier. The bot may not have access to the chat and could be unable to use this identifier, unless the chat is already known to the bot by some other means.
      titleStringOptional. Title of the chat, if the title was requested by the bot.
      usernameStringOptional. Username of the chat, if the username was requested by the bot and available.
      photoArray of PhotoSizeOptional. Available sizes of the chat photo, if the photo was requested by the bot
      +

      WriteAccessAllowed

      +

      This object represents a service message about a user allowing a bot to write messages after adding it to the attachment menu, launching a Web App from a link, or accepting an explicit request from a Web App sent by the method requestWriteAccess.

      + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      from_requestBooleanOptional. True, if the access was granted after the user accepted an explicit request from a Web App sent by the method requestWriteAccess
      web_app_nameStringOptional. Name of the Web App, if the access was granted when the Web App was launched from a link
      from_attachment_menuBooleanOptional. True, if the access was granted when the bot was added to the attachment or side menu
      +

      VideoChatScheduled

      +

      This object represents a service message about a video chat scheduled in the chat.

      + + + + + + + + + + + + + + + +
      FieldTypeDescription
      start_dateIntegerPoint in time (Unix timestamp) when the video chat is supposed to be started by a chat administrator
      +

      VideoChatStarted

      +

      This object represents a service message about a video chat started in the chat. Currently holds no information.

      +

      VideoChatEnded

      +

      This object represents a service message about a video chat ended in the chat.

      + + + + + + + + + + + + + + + +
      FieldTypeDescription
      durationIntegerVideo chat duration in seconds
      +

      VideoChatParticipantsInvited

      +

      This object represents a service message about new members invited to a video chat.

      + + + + + + + + + + + + + + + +
      FieldTypeDescription
      usersArray of UserNew members that were invited to the video chat
      +

      PaidMessagePriceChanged

      +

      Describes a service message about a change in the price of paid messages within a chat.

      + + + + + + + + + + + + + + + +
      FieldTypeDescription
      paid_message_star_countIntegerThe new number of Telegram Stars that must be paid by non-administrator users of the supergroup chat for each sent message
      +

      DirectMessagePriceChanged

      +

      Describes a service message about a change in the price of direct messages sent to a channel chat.

      + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      are_direct_messages_enabledBooleanTrue, if direct messages are enabled for the channel chat; false otherwise
      direct_message_star_countIntegerOptional. The new number of Telegram Stars that must be paid by users for each direct message sent to the channel. Does not apply to users who have been exempted by administrators. Defaults to 0.
      +

      SuggestedPostApproved

      +

      Describes a service message about the approval of a suggested post.

      + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      suggested_post_messageMessageOptional. Message containing the suggested post. Note that the Message object in this field will not contain the reply_to_message field even if it itself is a reply.
      priceSuggestedPostPriceOptional. Amount paid for the post
      send_dateIntegerDate when the post will be published
      +

      SuggestedPostApprovalFailed

      +

      Describes a service message about the failed approval of a suggested post. Currently, only caused by insufficient user funds at the time of approval.

      + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      suggested_post_messageMessageOptional. Message containing the suggested post whose approval has failed. Note that the Message object in this field will not contain the reply_to_message field even if it itself is a reply.
      priceSuggestedPostPriceExpected price of the post
      +

      SuggestedPostDeclined

      +

      Describes a service message about the rejection of a suggested post.

      + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      suggested_post_messageMessageOptional. Message containing the suggested post. Note that the Message object in this field will not contain the reply_to_message field even if it itself is a reply.
      commentStringOptional. Comment with which the post was declined
      +

      SuggestedPostPaid

      +

      Describes a service message about a successful payment for a suggested post.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      suggested_post_messageMessageOptional. Message containing the suggested post. Note that the Message object in this field will not contain the reply_to_message field even if it itself is a reply.
      currencyStringCurrency in which the payment was made. Currently, one of “XTR” for Telegram Stars or “TON” for toncoins
      amountIntegerOptional. The amount of the currency that was received by the channel in nanotoncoins; for payments in toncoins only
      star_amountStarAmountOptional. The amount of Telegram Stars that was received by the channel; for payments in Telegram Stars only
      +

      SuggestedPostRefunded

      +

      Describes a service message about a payment refund for a suggested post.

      + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      suggested_post_messageMessageOptional. Message containing the suggested post. Note that the Message object in this field will not contain the reply_to_message field even if it itself is a reply.
      reasonStringReason for the refund. Currently, one of “post_deleted” if the post was deleted within 24 hours of being posted or removed from scheduled messages without being posted, or “payment_refunded” if the payer refunded their payment.
      +

      GiveawayCreated

      +

      This object represents a service message about the creation of a scheduled giveaway.

      + + + + + + + + + + + + + + + +
      FieldTypeDescription
      prize_star_countIntegerOptional. The number of Telegram Stars to be split between giveaway winners; for Telegram Star giveaways only
      +

      Giveaway

      +

      This object represents a message about a scheduled giveaway.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      chatsArray of ChatThe list of chats which the user must join to participate in the giveaway
      winners_selection_dateIntegerPoint in time (Unix timestamp) when winners of the giveaway will be selected
      winner_countIntegerThe number of users which are supposed to be selected as winners of the giveaway
      only_new_membersTrueOptional. True, if only users who join the chats after the giveaway started should be eligible to win
      has_public_winnersTrueOptional. True, if the list of giveaway winners will be visible to everyone
      prize_descriptionStringOptional. Description of additional giveaway prize
      country_codesArray of StringOptional. A list of two-letter ISO 3166-1 alpha-2 country codes indicating the countries from which eligible users for the giveaway must come. If empty, then all users can participate in the giveaway. Users with a phone number that was bought on Fragment can always participate in giveaways.
      prize_star_countIntegerOptional. The number of Telegram Stars to be split between giveaway winners; for Telegram Star giveaways only
      premium_subscription_month_countIntegerOptional. The number of months the Telegram Premium subscription won from the giveaway will be active for; for Telegram Premium giveaways only
      +

      GiveawayWinners

      +

      This object represents a message about the completion of a giveaway with public winners.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      chatChatThe chat that created the giveaway
      giveaway_message_idIntegerIdentifier of the message with the giveaway in the chat
      winners_selection_dateIntegerPoint in time (Unix timestamp) when winners of the giveaway were selected
      winner_countIntegerTotal number of winners in the giveaway
      winnersArray of UserList of up to 100 winners of the giveaway
      additional_chat_countIntegerOptional. The number of other chats the user had to join in order to be eligible for the giveaway
      prize_star_countIntegerOptional. The number of Telegram Stars that were split between giveaway winners; for Telegram Star giveaways only
      premium_subscription_month_countIntegerOptional. The number of months the Telegram Premium subscription won from the giveaway will be active for; for Telegram Premium giveaways only
      unclaimed_prize_countIntegerOptional. Number of undistributed prizes
      only_new_membersTrueOptional. True, if only users who had joined the chats after the giveaway started were eligible to win
      was_refundedTrueOptional. True, if the giveaway was canceled because the payment for it was refunded
      prize_descriptionStringOptional. Description of additional giveaway prize
      +

      GiveawayCompleted

      +

      This object represents a service message about the completion of a giveaway without public winners.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      winner_countIntegerNumber of winners in the giveaway
      unclaimed_prize_countIntegerOptional. Number of undistributed prizes
      giveaway_messageMessageOptional. Message with the giveaway that was completed, if it wasn't deleted
      is_star_giveawayTrueOptional. True, if the giveaway is a Telegram Star giveaway. Otherwise, currently, the giveaway is a Telegram Premium giveaway.
      +

      LinkPreviewOptions

      +

      Describes the options used for link preview generation.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      is_disabledBooleanOptional. True, if the link preview is disabled
      urlStringOptional. URL to use for the link preview. If empty, then the first URL found in the message text will be used
      prefer_small_mediaBooleanOptional. True, if the media in the link preview is supposed to be shrunk; ignored if the URL isn't explicitly specified or media size change isn't supported for the preview
      prefer_large_mediaBooleanOptional. True, if the media in the link preview is supposed to be enlarged; ignored if the URL isn't explicitly specified or media size change isn't supported for the preview
      show_above_textBooleanOptional. True, if the link preview must be shown above the message text; otherwise, the link preview will be shown below the message text
      +

      SuggestedPostPrice

      +

      Describes the price of a suggested post.

      + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      currencyStringCurrency in which the post will be paid. Currently, must be one of “XTR” for Telegram Stars or “TON” for toncoins
      amountIntegerThe amount of the currency that will be paid for the post in the smallest units of the currency, i.e. Telegram Stars or nanotoncoins. Currently, price in Telegram Stars must be between 5 and 100000, and price in nanotoncoins must be between 10000000 and 10000000000000.
      +

      SuggestedPostInfo

      +

      Contains information about a suggested post.

      + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      stateStringState of the suggested post. Currently, it can be one of “pending”, “approved”, “declined”.
      priceSuggestedPostPriceOptional. Proposed price of the post. If the field is omitted, then the post is unpaid.
      send_dateIntegerOptional. Proposed send date of the post. If the field is omitted, then the post can be published at any time within 30 days at the sole discretion of the user or administrator who approves it.
      +

      SuggestedPostParameters

      +

      Contains parameters of a post that is being suggested by the bot.

      + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      priceSuggestedPostPriceOptional. Proposed price for the post. If the field is omitted, then the post is unpaid.
      send_dateIntegerOptional. Proposed send date of the post. If specified, then the date must be between 300 second and 2678400 seconds (30 days) in the future. If the field is omitted, then the post can be published at any time within 30 days at the sole discretion of the user who approves it.
      +

      DirectMessagesTopic

      +

      Describes a topic of a direct messages chat.

      + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      topic_idIntegerUnique identifier of the topic. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a 64-bit integer or double-precision float type are safe for storing this identifier.
      userUserOptional. Information about the user that created the topic. Currently, it is always present
      +

      UserProfilePhotos

      +

      This object represent a user's profile pictures.

      + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      total_countIntegerTotal number of profile pictures the target user has
      photosArray of Array of PhotoSizeRequested profile pictures (in up to 4 sizes each)
      +

      UserProfileAudios

      +

      This object represents the audios displayed on a user's profile.

      + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      total_countIntegerTotal number of profile audios for the target user
      audiosArray of AudioRequested profile audios
      +

      File

      +

      This object represents a file ready to be downloaded. The file can be downloaded via the link https://api.telegram.org/file/bot<token>/<file_path>. It is guaranteed that the link will be valid for at least 1 hour. When the link expires, a new one can be requested by calling getFile.

      +
      +

      The maximum file size to download is 20 MB

      +
      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      file_idStringIdentifier for this file, which can be used to download or reuse the file
      file_unique_idStringUnique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file.
      file_sizeIntegerOptional. File size in bytes. It can be bigger than 2^31 and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this value.
      file_pathStringOptional. File path. Use https://api.telegram.org/file/bot<token>/<file_path> to get the file.
      +

      WebAppInfo

      +

      Describes a Web App.

      + + + + + + + + + + + + + + + +
      FieldTypeDescription
      urlStringAn HTTPS URL of a Web App to be opened with additional data as specified in Initializing Web Apps
      +

      ReplyKeyboardMarkup

      +

      This object represents a custom keyboard with reply options (see Introduction to bots for details and examples). Not supported in channels and for messages sent on behalf of a business account.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      keyboardArray of Array of KeyboardButtonArray of button rows, each represented by an Array of KeyboardButton objects
      is_persistentBooleanOptional. Requests clients to always show the keyboard when the regular keyboard is hidden. Defaults to false, in which case the custom keyboard can be hidden and opened with a keyboard icon.
      resize_keyboardBooleanOptional. Requests clients to resize the keyboard vertically for optimal fit (e.g., make the keyboard smaller if there are just two rows of buttons). Defaults to false, in which case the custom keyboard is always of the same height as the app's standard keyboard.
      one_time_keyboardBooleanOptional. Requests clients to hide the keyboard as soon as it's been used. The keyboard will still be available, but clients will automatically display the usual letter-keyboard in the chat - the user can press a special button in the input field to see the custom keyboard again. Defaults to false.
      input_field_placeholderStringOptional. The placeholder to be shown in the input field when the keyboard is active; 1-64 characters
      selectiveBooleanOptional. Use this parameter if you want to show the keyboard to specific users only. Targets: 1) users that are @mentioned in the text of the Message object; 2) if the bot's message is a reply to a message in the same chat and forum topic, sender of the original message.

      Example: A user requests to change the bot's language, bot replies to the request with a keyboard to select the new language. Other users in the group don't see the keyboard.
      +

      KeyboardButton

      +

      This object represents one button of the reply keyboard. At most one of the fields other than text, icon_custom_emoji_id, and style must be used to specify the type of the button. For simple text buttons, String can be used instead of this object to specify the button text.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      textStringText of the button. If none of the fields other than text, icon_custom_emoji_id, and style are used, it will be sent as a message when the button is pressed
      icon_custom_emoji_idStringOptional. Unique identifier of the custom emoji shown before the text of the button. Can only be used by bots that purchased additional usernames on Fragment or in the messages directly sent by the bot to private, group and supergroup chats if the owner of the bot has a Telegram Premium subscription.
      styleStringOptional. Style of the button. Must be one of “danger” (red), “success” (green) or “primary” (blue). If omitted, then an app-specific style is used.
      request_usersKeyboardButtonRequestUsersOptional. If specified, pressing the button will open a list of suitable users. Identifiers of selected users will be sent to the bot in a “users_shared” service message. Available in private chats only.
      request_chatKeyboardButtonRequestChatOptional. If specified, pressing the button will open a list of suitable chats. Tapping on a chat will send its identifier to the bot in a “chat_shared” service message. Available in private chats only.
      request_managed_botKeyboardButtonRequestManagedBotOptional. If specified, pressing the button will ask the user to create and share a bot that will be managed by the current bot. Available for bots that enabled management of other bots in the @BotFather Mini App. Available in private chats only.
      request_contactBooleanOptional. If True, the user's phone number will be sent as a contact when the button is pressed. Available in private chats only.
      request_locationBooleanOptional. If True, the user's current location will be sent when the button is pressed. Available in private chats only.
      request_pollKeyboardButtonPollTypeOptional. If specified, the user will be asked to create a poll and send it to the bot when the button is pressed. Available in private chats only.
      web_appWebAppInfoOptional. If specified, the described Web App will be launched when the button is pressed. The Web App will be able to send a “web_app_data” service message. Available in private chats only.
      +

      KeyboardButtonRequestUsers

      +

      This object defines the criteria used to request suitable users. Information about the selected users will be shared with the bot when the corresponding button is pressed. More about requesting users »

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      request_idIntegerSigned 32-bit identifier of the request that will be received back in the UsersShared object. Must be unique within the message
      user_is_botBooleanOptional. Pass True to request bots, pass False to request regular users. If not specified, no additional restrictions are applied.
      user_is_premiumBooleanOptional. Pass True to request premium users, pass False to request non-premium users. If not specified, no additional restrictions are applied.
      max_quantityIntegerOptional. The maximum number of users to be selected; 1-10. Defaults to 1.
      request_nameBooleanOptional. Pass True to request the users' first and last names
      request_usernameBooleanOptional. Pass True to request the users' usernames
      request_photoBooleanOptional. Pass True to request the users' photos
      +

      KeyboardButtonRequestChat

      +

      This object defines the criteria used to request a suitable chat. Information about the selected chat will be shared with the bot when the corresponding button is pressed. The bot will be granted requested rights in the chat if appropriate. More about requesting chats ».

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      request_idIntegerSigned 32-bit identifier of the request, which will be received back in the ChatShared object. Must be unique within the message
      chat_is_channelBooleanPass True to request a channel chat, pass False to request a group or a supergroup chat.
      chat_is_forumBooleanOptional. Pass True to request a forum supergroup, pass False to request a non-forum chat. If not specified, no additional restrictions are applied.
      chat_has_usernameBooleanOptional. Pass True to request a supergroup or a channel with a username, pass False to request a chat without a username. If not specified, no additional restrictions are applied.
      chat_is_createdBooleanOptional. Pass True to request a chat owned by the user. Otherwise, no additional restrictions are applied.
      user_administrator_rightsChatAdministratorRightsOptional. A JSON-serialized object listing the required administrator rights of the user in the chat. The rights must be a superset of bot_administrator_rights. If not specified, no additional restrictions are applied.
      bot_administrator_rightsChatAdministratorRightsOptional. A JSON-serialized object listing the required administrator rights of the bot in the chat. The rights must be a subset of user_administrator_rights. If not specified, no additional restrictions are applied.
      bot_is_memberBooleanOptional. Pass True to request a chat with the bot as a member. Otherwise, no additional restrictions are applied.
      request_titleBooleanOptional. Pass True to request the chat's title
      request_usernameBooleanOptional. Pass True to request the chat's username
      request_photoBooleanOptional. Pass True to request the chat's photo
      +

      KeyboardButtonRequestManagedBot

      +

      This object defines the parameters for the creation of a managed bot. Information about the created bot will be shared with the bot using the update managed_bot and a Message with the field managed_bot_created.

      + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      request_idIntegerSigned 32-bit identifier of the request. Must be unique within the message
      suggested_nameStringOptional. Suggested name for the bot
      suggested_usernameStringOptional. Suggested username for the bot
      +

      KeyboardButtonPollType

      +

      This object represents type of a poll, which is allowed to be created and sent when the corresponding button is pressed.

      + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringOptional. If quiz is passed, the user will be allowed to create only polls in the quiz mode. If regular is passed, only regular polls will be allowed. Otherwise, the user will be allowed to create a poll of any type.
      +

      ReplyKeyboardRemove

      +

      Upon receiving a message with this object, Telegram clients will remove the current custom keyboard and display the default letter-keyboard. By default, custom keyboards are displayed until a new keyboard is sent by a bot. An exception is made for one-time keyboards that are hidden immediately after the user presses a button (see ReplyKeyboardMarkup). Not supported in channels and for messages sent on behalf of a business account.

      + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      remove_keyboardTrueRequests clients to remove the custom keyboard (user will not be able to summon this keyboard; if you want to hide the keyboard from sight but keep it accessible, use one_time_keyboard in ReplyKeyboardMarkup)
      selectiveBooleanOptional. Use this parameter if you want to remove the keyboard for specific users only. Targets: 1) users that are @mentioned in the text of the Message object; 2) if the bot's message is a reply to a message in the same chat and forum topic, sender of the original message.

      Example: A user votes in a poll, bot returns confirmation message in reply to the vote and removes the keyboard for that user, while still showing the keyboard with poll options to users who haven't voted yet.
      +

      InlineKeyboardMarkup

      +

      This object represents an inline keyboard that appears right next to the message it belongs to.

      + + + + + + + + + + + + + + + +
      FieldTypeDescription
      inline_keyboardArray of Array of InlineKeyboardButtonArray of button rows, each represented by an Array of InlineKeyboardButton objects
      +

      InlineKeyboardButton

      +

      This object represents one button of an inline keyboard. Exactly one of the fields other than text, icon_custom_emoji_id, and style must be used to specify the type of the button.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      textStringLabel text on the button
      icon_custom_emoji_idStringOptional. Unique identifier of the custom emoji shown before the text of the button. Can only be used by bots that purchased additional usernames on Fragment or in the messages directly sent by the bot to private, group and supergroup chats if the owner of the bot has a Telegram Premium subscription.
      styleStringOptional. Style of the button. Must be one of “danger” (red), “success” (green) or “primary” (blue). If omitted, then an app-specific style is used.
      urlStringOptional. HTTP or tg:// URL to be opened when the button is pressed. Links tg://user?id=<user_id> can be used to mention a user by their identifier without using a username, if this is allowed by their privacy settings.
      callback_dataStringOptional. Data to be sent in a callback query to the bot when the button is pressed, 1-64 bytes
      web_appWebAppInfoOptional. Description of the Web App that will be launched when the user presses the button. The Web App will be able to send an arbitrary message on behalf of the user using the method answerWebAppQuery. Available only in private chats between a user and the bot. Not supported for messages sent on behalf of a business account.
      login_urlLoginUrlOptional. An HTTPS URL used to automatically authorize the user. Can be used as a replacement for the Telegram Login Widget.
      switch_inline_queryStringOptional. If set, pressing the button will prompt the user to select one of their chats, open that chat and insert the bot's username and the specified inline query in the input field. May be empty, in which case just the bot's username will be inserted. Not supported for messages sent in channel direct messages chats and on behalf of a business account.
      switch_inline_query_current_chatStringOptional. If set, pressing the button will insert the bot's username and the specified inline query in the current chat's input field. May be empty, in which case only the bot's username will be inserted.

      This offers a quick way for the user to open your bot in inline mode in the same chat - good for selecting something from multiple options. Not supported in channels and for messages sent in channel direct messages chats and on behalf of a business account.
      switch_inline_query_chosen_chatSwitchInlineQueryChosenChatOptional. If set, pressing the button will prompt the user to select one of their chats of the specified type, open that chat and insert the bot's username and the specified inline query in the input field. Not supported for messages sent in channel direct messages chats and on behalf of a business account.
      copy_textCopyTextButtonOptional. Description of the button that copies the specified text to the clipboard.
      callback_gameCallbackGameOptional. Description of the game that will be launched when the user presses the button.

      NOTE: This type of button must always be the first button in the first row.
      payBooleanOptional. Specify True, to send a Pay button. Substrings “⭐” and “XTR” in the buttons's text will be replaced with a Telegram Star icon.

      NOTE: This type of button must always be the first button in the first row and can only be used in invoice messages.
      +

      LoginUrl

      +

      This object represents a parameter of the inline keyboard button used to automatically authorize a user. Serves as a great replacement for the Telegram Login Widget when the user is coming from Telegram. All the user needs to do is tap/click a button and confirm that they want to log in:

      +
      + TITLE +
      + +

      Telegram apps support these buttons as of version 5.7.

      +
      +

      Sample bot: @discussbot

      +
      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      urlStringAn HTTPS URL to be opened with user authorization data added to the query string when the button is pressed. If the user refuses to provide authorization data, the original URL without information about the user will be opened. The data added is the same as described in Receiving authorization data.

      NOTE: You must always check the hash of the received data to verify the authentication and the integrity of the data as described in Checking authorization.
      forward_textStringOptional. New text of the button in forwarded messages.
      bot_usernameStringOptional. Username of a bot, which will be used for user authorization. See Setting up a bot for more details. If not specified, the current bot's username will be assumed. The url's domain must be the same as the domain linked with the bot. See Linking your domain to the bot for more details.
      request_write_accessBooleanOptional. Pass True to request the permission for your bot to send messages to the user.
      +

      SwitchInlineQueryChosenChat

      +

      This object represents an inline button that switches the current user to inline mode in a chosen chat, with an optional default inline query.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      queryStringOptional. The default inline query to be inserted in the input field. If left empty, only the bot's username will be inserted
      allow_user_chatsBooleanOptional. True, if private chats with users can be chosen
      allow_bot_chatsBooleanOptional. True, if private chats with bots can be chosen
      allow_group_chatsBooleanOptional. True, if group and supergroup chats can be chosen
      allow_channel_chatsBooleanOptional. True, if channel chats can be chosen
      +

      CopyTextButton

      +

      This object represents an inline keyboard button that copies specified text to the clipboard.

      + + + + + + + + + + + + + + + +
      FieldTypeDescription
      textStringThe text to be copied to the clipboard; 1-256 characters
      +

      CallbackQuery

      +

      This object represents an incoming callback query from a callback button in an inline keyboard. If the button that originated the query was attached to a message sent by the bot, the field message will be present. If the button was attached to a message sent via the bot (in inline mode), the field inline_message_id will be present. Exactly one of the fields data or game_short_name will be present.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      idStringUnique identifier for this query
      fromUserSender
      messageMaybeInaccessibleMessageOptional. Message sent by the bot with the callback button that originated the query
      inline_message_idStringOptional. Identifier of the message sent via the bot in inline mode, that originated the query.
      chat_instanceStringGlobal identifier, uniquely corresponding to the chat to which the message with the callback button was sent. Useful for high scores in games.
      dataStringOptional. Data associated with the callback button. Be aware that the message originated the query can contain no callback buttons with this data.
      game_short_nameStringOptional. Short name of a Game to be returned, serves as the unique identifier for the game
      +
      +

      NOTE: After the user presses a callback button, Telegram clients will display a progress bar until you call answerCallbackQuery. It is, therefore, necessary to react by calling answerCallbackQuery even if no notification to the user is needed (e.g., without specifying any of the optional parameters).

      +
      +

      ForceReply

      +

      Upon receiving a message with this object, Telegram clients will display a reply interface to the user (act as if the user has selected the bot's message and tapped 'Reply'). This can be extremely useful if you want to create user-friendly step-by-step interfaces without having to sacrifice privacy mode. Not supported in channels and for messages sent on behalf of a user account.

      + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      force_replyTrueShows reply interface to the user, as if they manually selected the bot's message and tapped 'Reply'
      input_field_placeholderStringOptional. The placeholder to be shown in the input field when the reply is active; 1-64 characters
      selectiveBooleanOptional. Use this parameter if you want to force reply from specific users only. Targets: 1) users that are @mentioned in the text of the Message object; 2) if the bot's message is a reply to a message in the same chat and forum topic, sender of the original message.
      +
      +

      Example: A poll bot for groups runs in privacy mode (only receives commands, replies to its messages and mentions). There could be two ways to create a new poll:

      +
        +
      • Explain the user how to send a command with parameters (e.g. /newpoll question answer1 answer2). May be appealing for hardcore users but lacks modern day polish.
      • +
      • Guide the user through a step-by-step process. 'Please send me your question', 'Cool, now let's add the first answer option', 'Great. Keep adding answer options, then send /done when you're ready'.
      • +
      +

      The last option is definitely more attractive. And if you use ForceReply in your bot's questions, it will receive the user's answers even if it only receives replies, commands and mentions - without any extra work for the user.

      +
      +

      ChatPhoto

      +

      This object represents a chat photo.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      small_file_idStringFile identifier of small (160x160) chat photo. This file_id can be used only for photo download and only for as long as the photo is not changed.
      small_file_unique_idStringUnique file identifier of small (160x160) chat photo, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file.
      big_file_idStringFile identifier of big (640x640) chat photo. This file_id can be used only for photo download and only for as long as the photo is not changed.
      big_file_unique_idStringUnique file identifier of big (640x640) chat photo, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file.
      +

      ChatInviteLink

      +

      Represents an invite link for a chat.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      invite_linkStringThe invite link. If the link was created by another chat administrator, then the second part of the link will be replaced with “…”.
      creatorUserCreator of the link
      creates_join_requestBooleanTrue, if users joining the chat via the link need to be approved by chat administrators
      is_primaryBooleanTrue, if the link is primary
      is_revokedBooleanTrue, if the link is revoked
      nameStringOptional. Invite link name
      expire_dateIntegerOptional. Point in time (Unix timestamp) when the link will expire or has been expired
      member_limitIntegerOptional. The maximum number of users that can be members of the chat simultaneously after joining the chat via this invite link; 1-99999
      pending_join_request_countIntegerOptional. Number of pending join requests created using this link
      subscription_periodIntegerOptional. The number of seconds the subscription will be active for before the next payment
      subscription_priceIntegerOptional. The amount of Telegram Stars a user must pay initially and after each subsequent subscription period to be a member of the chat using the link
      +

      ChatAdministratorRights

      +

      Represents the rights of an administrator in a chat.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      is_anonymousBooleanTrue, if the user's presence in the chat is hidden
      can_manage_chatBooleanTrue, if the administrator can access the chat event log, get boost list, see hidden supergroup and channel members, report spam messages, ignore slow mode, and send messages to the chat without paying Telegram Stars. Implied by any other administrator privilege.
      can_delete_messagesBooleanTrue, if the administrator can delete messages of other users
      can_manage_video_chatsBooleanTrue, if the administrator can manage video chats
      can_restrict_membersBooleanTrue, if the administrator can restrict, ban or unban chat members, or access supergroup statistics
      can_promote_membersBooleanTrue, if the administrator can add new administrators with a subset of their own privileges or demote administrators that they have promoted, directly or indirectly (promoted by administrators that were appointed by the user)
      can_change_infoBooleanTrue, if the user is allowed to change the chat title, photo and other settings
      can_invite_usersBooleanTrue, if the user is allowed to invite new users to the chat
      can_post_storiesBooleanTrue, if the administrator can post stories to the chat
      can_edit_storiesBooleanTrue, if the administrator can edit stories posted by other users, post stories to the chat page, pin chat stories, and access the chat's story archive
      can_delete_storiesBooleanTrue, if the administrator can delete stories posted by other users
      can_post_messagesBooleanOptional. True, if the administrator can post messages in the channel, approve suggested posts, or access channel statistics; for channels only
      can_edit_messagesBooleanOptional. True, if the administrator can edit messages of other users and can pin messages; for channels only
      can_pin_messagesBooleanOptional. True, if the user is allowed to pin messages; for groups and supergroups only
      can_manage_topicsBooleanOptional. True, if the user is allowed to create, rename, close, and reopen forum topics; for supergroups only
      can_manage_direct_messagesBooleanOptional. True, if the administrator can manage direct messages of the channel and decline suggested posts; for channels only
      can_manage_tagsBooleanOptional. True, if the administrator can edit the tags of regular members; for groups and supergroups only. If omitted defaults to the value of can_pin_messages.
      +

      ChatMemberUpdated

      +

      This object represents changes in the status of a chat member.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      chatChatChat the user belongs to
      fromUserPerformer of the action, which resulted in the change
      dateIntegerDate the change was done in Unix time
      old_chat_memberChatMemberPrevious information about the chat member
      new_chat_memberChatMemberNew information about the chat member
      invite_linkChatInviteLinkOptional. Chat invite link, which was used by the user to join the chat; for joining by invite link events only.
      via_join_requestBooleanOptional. True, if the user joined the chat after sending a direct join request without using an invite link and being approved by an administrator
      via_chat_folder_invite_linkBooleanOptional. True, if the user joined the chat via a chat folder invite link
      +

      ChatMember

      +

      This object contains information about one member of a chat. Currently, the following 6 types of chat members are supported:

      + +

      ChatMemberOwner

      +

      Represents a chat member that owns the chat and has all administrator privileges.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      statusStringThe member's status in the chat, always “creator”
      userUserInformation about the user
      is_anonymousBooleanTrue, if the user's presence in the chat is hidden
      custom_titleStringOptional. Custom title for this user
      +

      ChatMemberAdministrator

      +

      Represents a chat member that has some additional privileges.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      statusStringThe member's status in the chat, always “administrator”
      userUserInformation about the user
      can_be_editedBooleanTrue, if the bot is allowed to edit administrator privileges of that user
      is_anonymousBooleanTrue, if the user's presence in the chat is hidden
      can_manage_chatBooleanTrue, if the administrator can access the chat event log, get boost list, see hidden supergroup and channel members, report spam messages, ignore slow mode, and send messages to the chat without paying Telegram Stars. Implied by any other administrator privilege.
      can_delete_messagesBooleanTrue, if the administrator can delete messages of other users
      can_manage_video_chatsBooleanTrue, if the administrator can manage video chats
      can_restrict_membersBooleanTrue, if the administrator can restrict, ban or unban chat members, or access supergroup statistics
      can_promote_membersBooleanTrue, if the administrator can add new administrators with a subset of their own privileges or demote administrators that they have promoted, directly or indirectly (promoted by administrators that were appointed by the user)
      can_change_infoBooleanTrue, if the user is allowed to change the chat title, photo and other settings
      can_invite_usersBooleanTrue, if the user is allowed to invite new users to the chat
      can_post_storiesBooleanTrue, if the administrator can post stories to the chat
      can_edit_storiesBooleanTrue, if the administrator can edit stories posted by other users, post stories to the chat page, pin chat stories, and access the chat's story archive
      can_delete_storiesBooleanTrue, if the administrator can delete stories posted by other users
      can_post_messagesBooleanOptional. True, if the administrator can post messages in the channel, approve suggested posts, or access channel statistics; for channels only
      can_edit_messagesBooleanOptional. True, if the administrator can edit messages of other users and can pin messages; for channels only
      can_pin_messagesBooleanOptional. True, if the user is allowed to pin messages; for groups and supergroups only
      can_manage_topicsBooleanOptional. True, if the user is allowed to create, rename, close, and reopen forum topics; for supergroups only
      can_manage_direct_messagesBooleanOptional. True, if the administrator can manage direct messages of the channel and decline suggested posts; for channels only
      can_manage_tagsBooleanOptional. True, if the administrator can edit the tags of regular members; for groups and supergroups only. If omitted defaults to the value of can_pin_messages.
      custom_titleStringOptional. Custom title for this user
      +

      ChatMemberMember

      +

      Represents a chat member that has no additional privileges or restrictions.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      statusStringThe member's status in the chat, always “member”
      tagStringOptional. Tag of the member
      userUserInformation about the user
      until_dateIntegerOptional. Date when the user's subscription will expire; Unix time
      +

      ChatMemberRestricted

      +

      Represents a chat member that is under certain restrictions in the chat. Supergroups only.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      statusStringThe member's status in the chat, always “restricted”
      tagStringOptional. Tag of the member
      userUserInformation about the user
      is_memberBooleanTrue, if the user is a member of the chat at the moment of the request
      can_send_messagesBooleanTrue, if the user is allowed to send text messages, contacts, giveaways, giveaway winners, invoices, locations and venues
      can_send_audiosBooleanTrue, if the user is allowed to send audios
      can_send_documentsBooleanTrue, if the user is allowed to send documents
      can_send_photosBooleanTrue, if the user is allowed to send photos
      can_send_videosBooleanTrue, if the user is allowed to send videos
      can_send_video_notesBooleanTrue, if the user is allowed to send video notes
      can_send_voice_notesBooleanTrue, if the user is allowed to send voice notes
      can_send_pollsBooleanTrue, if the user is allowed to send polls and checklists
      can_send_other_messagesBooleanTrue, if the user is allowed to send animations, games, stickers and use inline bots
      can_add_web_page_previewsBooleanTrue, if the user is allowed to add web page previews to their messages
      can_react_to_messagesBooleanTrue, if the user is allowed to react to messages
      can_edit_tagBooleanTrue, if the user is allowed to edit their own tag
      can_change_infoBooleanTrue, if the user is allowed to change the chat title, photo and other settings
      can_invite_usersBooleanTrue, if the user is allowed to invite new users to the chat
      can_pin_messagesBooleanTrue, if the user is allowed to pin messages
      can_manage_topicsBooleanTrue, if the user is allowed to create forum topics
      until_dateIntegerDate when restrictions will be lifted for this user; Unix time. If 0, then the user is restricted forever
      +

      ChatMemberLeft

      +

      Represents a chat member that isn't currently a member of the chat, but may join it themselves.

      + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      statusStringThe member's status in the chat, always “left”
      userUserInformation about the user
      +

      ChatMemberBanned

      +

      Represents a chat member that was banned in the chat and can't return to the chat or view chat messages.

      + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      statusStringThe member's status in the chat, always “kicked”
      userUserInformation about the user
      until_dateIntegerDate when restrictions will be lifted for this user; Unix time. If 0, then the user is banned forever
      +

      ChatJoinRequest

      +

      Represents a join request sent to a chat.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      chatChatChat to which the request was sent
      fromUserUser that sent the join request
      user_chat_idIntegerIdentifier of a private chat with the user who sent the join request. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a 64-bit integer or double-precision float type are safe for storing this identifier. The bot can use this identifier for 5 minutes to send messages until the join request is processed, assuming no other administrator contacted the user.
      dateIntegerDate the request was sent in Unix time
      bioStringOptional. Bio of the user.
      invite_linkChatInviteLinkOptional. Chat invite link that was used by the user to send the join request
      +

      ChatPermissions

      +

      Describes actions that a non-administrator user is allowed to take in a chat.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      can_send_messagesBooleanOptional. True, if the user is allowed to send text messages, contacts, giveaways, giveaway winners, invoices, locations and venues
      can_send_audiosBooleanOptional. True, if the user is allowed to send audios
      can_send_documentsBooleanOptional. True, if the user is allowed to send documents
      can_send_photosBooleanOptional. True, if the user is allowed to send photos
      can_send_videosBooleanOptional. True, if the user is allowed to send videos
      can_send_video_notesBooleanOptional. True, if the user is allowed to send video notes
      can_send_voice_notesBooleanOptional. True, if the user is allowed to send voice notes
      can_send_pollsBooleanOptional. True, if the user is allowed to send polls and checklists
      can_send_other_messagesBooleanOptional. True, if the user is allowed to send animations, games, stickers and use inline bots
      can_add_web_page_previewsBooleanOptional. True, if the user is allowed to add web page previews to their messages
      can_react_to_messagesBooleanOptional. True, if the user is allowed to react to messages. If omitted, defaults to the value of can_send_messages.
      can_edit_tagBooleanOptional. True, if the user is allowed to edit their own tag. If omitted, defaults to the value of can_pin_messages.
      can_change_infoBooleanOptional. True, if the user is allowed to change the chat title, photo and other settings. Ignored in public supergroups
      can_invite_usersBooleanOptional. True, if the user is allowed to invite new users to the chat
      can_pin_messagesBooleanOptional. True, if the user is allowed to pin messages. Ignored in public supergroups
      can_manage_topicsBooleanOptional. True, if the user is allowed to create forum topics. If omitted defaults to the value of can_pin_messages
      +

      Birthdate

      +

      Describes the birthdate of a user.

      + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      dayIntegerDay of the user's birth; 1-31
      monthIntegerMonth of the user's birth; 1-12
      yearIntegerOptional. Year of the user's birth
      +

      BusinessIntro

      +

      Contains information about the start page settings of a Telegram Business account.

      + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      titleStringOptional. Title text of the business intro
      messageStringOptional. Message text of the business intro
      stickerStickerOptional. Sticker of the business intro
      +

      BusinessLocation

      +

      Contains information about the location of a Telegram Business account.

      + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      addressStringAddress of the business
      locationLocationOptional. Location of the business
      +

      BusinessOpeningHoursInterval

      +

      Describes an interval of time during which a business is open.

      + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      opening_minuteIntegerThe minute's sequence number in a week, starting on Monday, marking the start of the time interval during which the business is open; 0 - 7 * 24 * 60
      closing_minuteIntegerThe minute's sequence number in a week, starting on Monday, marking the end of the time interval during which the business is open; 0 - 8 * 24 * 60
      +

      BusinessOpeningHours

      +

      Describes the opening hours of a business.

      + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      time_zone_nameStringUnique name of the time zone for which the opening hours are defined
      opening_hoursArray of BusinessOpeningHoursIntervalList of time intervals describing business opening hours
      +

      UserRating

      +

      This object describes the rating of a user based on their Telegram Star spendings.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      levelIntegerCurrent level of the user, indicating their reliability when purchasing digital goods and services. A higher level suggests a more trustworthy customer; a negative level is likely reason for concern.
      ratingIntegerNumerical value of the user's rating; the higher the rating, the better
      current_level_ratingIntegerThe rating value required to get the current level
      next_level_ratingIntegerOptional. The rating value required to get to the next level; omitted if the maximum level was reached
      +

      StoryAreaPosition

      +

      Describes the position of a clickable area within a story.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      x_percentageFloatThe abscissa of the area's center, as a percentage of the media width
      y_percentageFloatThe ordinate of the area's center, as a percentage of the media height
      width_percentageFloatThe width of the area's rectangle, as a percentage of the media width
      height_percentageFloatThe height of the area's rectangle, as a percentage of the media height
      rotation_angleFloatThe clockwise rotation angle of the rectangle, in degrees; 0-360
      corner_radius_percentageFloatThe radius of the rectangle corner rounding, as a percentage of the media width
      +

      LocationAddress

      +

      Describes the physical address of a location.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      country_codeStringThe two-letter ISO 3166-1 alpha-2 country code of the country where the location is located
      stateStringOptional. State of the location
      cityStringOptional. City of the location
      streetStringOptional. Street address of the location
      +

      StoryAreaType

      +

      Describes the type of a clickable area on a story. Currently, it can be one of

      + +

      StoryAreaTypeLocation

      +

      Describes a story area pointing to a location. Currently, a story can have up to 10 location areas.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringType of the area, always “location”
      latitudeFloatLocation latitude in degrees
      longitudeFloatLocation longitude in degrees
      addressLocationAddressOptional. Address of the location
      +

      StoryAreaTypeSuggestedReaction

      +

      Describes a story area pointing to a suggested reaction. Currently, a story can have up to 5 suggested reaction areas.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringType of the area, always “suggested_reaction”
      reaction_typeReactionTypeType of the reaction
      is_darkBooleanOptional. Pass True if the reaction area has a dark background
      is_flippedBooleanOptional. Pass True if reaction area corner is flipped
      +

      StoryAreaTypeLink

      +

      Describes a story area pointing to an HTTP or tg:// link. Currently, a story can have up to 3 link areas.

      + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringType of the area, always “link”
      urlStringHTTP or tg:// URL to be opened when the area is clicked
      +

      StoryAreaTypeWeather

      +

      Describes a story area containing weather information. Currently, a story can have up to 3 weather areas.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringType of the area, always “weather”
      temperatureFloatTemperature, in degree Celsius
      emojiStringEmoji representing the weather
      background_colorIntegerA color of the area background in the ARGB format
      +

      StoryAreaTypeUniqueGift

      +

      Describes a story area pointing to a unique gift. Currently, a story can have at most 1 unique gift area.

      + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringType of the area, always “unique_gift”
      nameStringUnique name of the gift
      +

      StoryArea

      +

      Describes a clickable area on a story media.

      + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      positionStoryAreaPositionPosition of the area
      typeStoryAreaTypeType of the area
      +

      ChatLocation

      +

      Represents a location to which a chat is connected.

      + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      locationLocationThe location to which the supergroup is connected. Can't be a live location.
      addressStringLocation address; 1-64 characters, as defined by the chat owner
      +

      ReactionType

      +

      This object describes the type of a reaction. Currently, it can be one of

      + +

      ReactionTypeEmoji

      +

      The reaction is based on an emoji.

      + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringType of the reaction, always “emoji”
      emojiStringReaction emoji. Currently, it can be one of "❤", "👍", "👎", "🔥", "🥰", "👏", "😁", "🤔", "🤯", "😱", "🤬", "😢", "🎉", "🤩", "🤮", "💩", "🙏", "👌", "🕊", "🤡", "🥱", "🥴", "😍", "🐳", "❤‍🔥", "🌚", "🌭", "💯", "🤣", "⚡", "🍌", "🏆", "💔", "🤨", "😐", "🍓", "🍾", "💋", "🖕", "😈", "😴", "😭", "🤓", "👻", "👨‍💻", "👀", "🎃", "🙈", "😇", "😨", "🤝", "✍", "🤗", "🫡", "🎅", "🎄", "☃", "💅", "🤪", "🗿", "🆒", "💘", "🙉", "🦄", "😘", "💊", "🙊", "😎", "👾", "🤷‍♂", "🤷", "🤷‍♀", "😡"
      +

      ReactionTypeCustomEmoji

      +

      The reaction is based on a custom emoji.

      + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringType of the reaction, always “custom_emoji”
      custom_emoji_idStringCustom emoji identifier
      +

      ReactionTypePaid

      +

      The reaction is paid.

      + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringType of the reaction, always “paid”
      +

      ReactionCount

      +

      Represents a reaction added to a message along with the number of times it was added.

      + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeReactionTypeType of the reaction
      total_countIntegerNumber of times the reaction was added
      +

      MessageReactionUpdated

      +

      This object represents a change of a reaction on a message performed by a user.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      chatChatThe chat containing the message the user reacted to
      message_idIntegerUnique identifier of the message inside the chat
      userUserOptional. The user that changed the reaction, if the user isn't anonymous
      actor_chatChatOptional. The chat on behalf of which the reaction was changed, if the user is anonymous
      dateIntegerDate of the change in Unix time
      old_reactionArray of ReactionTypePrevious list of reaction types that were set by the user
      new_reactionArray of ReactionTypeNew list of reaction types that have been set by the user
      +

      MessageReactionCountUpdated

      +

      This object represents reaction changes on a message with anonymous reactions.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      chatChatThe chat containing the message
      message_idIntegerUnique message identifier inside the chat
      dateIntegerDate of the change in Unix time
      reactionsArray of ReactionCountList of reactions that are present on the message
      +

      ForumTopic

      +

      This object represents a forum topic.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      message_thread_idIntegerUnique identifier of the forum topic
      nameStringName of the topic
      icon_colorIntegerColor of the topic icon in RGB format
      icon_custom_emoji_idStringOptional. Unique identifier of the custom emoji shown as the topic icon
      is_name_implicitTrueOptional. True, if the name of the topic wasn't specified explicitly by its creator and likely needs to be changed by the bot
      +

      GiftBackground

      +

      This object describes the background of a gift.

      + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      center_colorIntegerCenter color of the background in RGB format
      edge_colorIntegerEdge color of the background in RGB format
      text_colorIntegerText color of the background in RGB format
      +

      Gift

      +

      This object represents a gift that can be sent by the bot.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      idStringUnique identifier of the gift
      stickerStickerThe sticker that represents the gift
      star_countIntegerThe number of Telegram Stars that must be paid to send the sticker
      upgrade_star_countIntegerOptional. The number of Telegram Stars that must be paid to upgrade the gift to a unique one
      is_premiumTrueOptional. True, if the gift can only be purchased by Telegram Premium subscribers
      has_colorsTrueOptional. True, if the gift can be used (after being upgraded) to customize a user's appearance
      total_countIntegerOptional. The total number of gifts of this type that can be sent by all users; for limited gifts only
      remaining_countIntegerOptional. The number of remaining gifts of this type that can be sent by all users; for limited gifts only
      personal_total_countIntegerOptional. The total number of gifts of this type that can be sent by the bot; for limited gifts only
      personal_remaining_countIntegerOptional. The number of remaining gifts of this type that can be sent by the bot; for limited gifts only
      backgroundGiftBackgroundOptional. Background of the gift
      unique_gift_variant_countIntegerOptional. The total number of different unique gifts that can be obtained by upgrading the gift
      publisher_chatChatOptional. Information about the chat that published the gift
      +

      Gifts

      +

      This object represent a list of gifts.

      + + + + + + + + + + + + + + + +
      FieldTypeDescription
      giftsArray of GiftThe list of gifts
      +

      UniqueGiftModel

      +

      This object describes the model of a unique gift.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      nameStringName of the model
      stickerStickerThe sticker that represents the unique gift
      rarity_per_milleIntegerThe number of unique gifts that receive this model for every 1000 gift upgrades. Always 0 for crafted gifts.
      rarityStringOptional. Rarity of the model if it is a crafted model. Currently, can be “uncommon”, “rare”, “epic”, or “legendary”.
      +

      UniqueGiftSymbol

      +

      This object describes the symbol shown on the pattern of a unique gift.

      + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      nameStringName of the symbol
      stickerStickerThe sticker that represents the unique gift
      rarity_per_milleIntegerThe number of unique gifts that receive this model for every 1000 gifts upgraded
      +

      UniqueGiftBackdropColors

      +

      This object describes the colors of the backdrop of a unique gift.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      center_colorIntegerThe color in the center of the backdrop in RGB format
      edge_colorIntegerThe color on the edges of the backdrop in RGB format
      symbol_colorIntegerThe color to be applied to the symbol in RGB format
      text_colorIntegerThe color for the text on the backdrop in RGB format
      +

      UniqueGiftBackdrop

      +

      This object describes the backdrop of a unique gift.

      + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      nameStringName of the backdrop
      colorsUniqueGiftBackdropColorsColors of the backdrop
      rarity_per_milleIntegerThe number of unique gifts that receive this backdrop for every 1000 gifts upgraded
      +

      UniqueGiftColors

      +

      This object contains information about the color scheme for a user's name, message replies and link previews based on a unique gift.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      model_custom_emoji_idStringCustom emoji identifier of the unique gift's model
      symbol_custom_emoji_idStringCustom emoji identifier of the unique gift's symbol
      light_theme_main_colorIntegerMain color used in light themes; RGB format
      light_theme_other_colorsArray of IntegerList of 1-3 additional colors used in light themes; RGB format
      dark_theme_main_colorIntegerMain color used in dark themes; RGB format
      dark_theme_other_colorsArray of IntegerList of 1-3 additional colors used in dark themes; RGB format
      +

      UniqueGift

      +

      This object describes a unique gift that was upgraded from a regular gift.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      gift_idStringIdentifier of the regular gift from which the gift was upgraded
      base_nameStringHuman-readable name of the regular gift from which this unique gift was upgraded
      nameStringUnique name of the gift. This name can be used in https://t.me/nft/... links and story areas
      numberIntegerUnique number of the upgraded gift among gifts upgraded from the same regular gift
      modelUniqueGiftModelModel of the gift
      symbolUniqueGiftSymbolSymbol of the gift
      backdropUniqueGiftBackdropBackdrop of the gift
      is_premiumTrueOptional. True, if the original regular gift was exclusively purchaseable by Telegram Premium subscribers
      is_burnedTrueOptional. True, if the gift was used to craft another gift and isn't available anymore
      is_from_blockchainTrueOptional. True, if the gift is assigned from the TON blockchain and can't be resold or transferred in Telegram
      colorsUniqueGiftColorsOptional. The color scheme that can be used by the gift's owner for the chat's name, replies to messages and link previews; for business account gifts and gifts that are currently on sale only
      publisher_chatChatOptional. Information about the chat that published the gift
      +

      GiftInfo

      +

      Describes a service message about a regular gift that was sent or received.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      giftGiftInformation about the gift
      owned_gift_idStringOptional. Unique identifier of the received gift for the bot; only present for gifts received on behalf of business accounts
      convert_star_countIntegerOptional. Number of Telegram Stars that can be claimed by the receiver by converting the gift; omitted if conversion to Telegram Stars is impossible
      prepaid_upgrade_star_countIntegerOptional. Number of Telegram Stars that were prepaid for the ability to upgrade the gift
      is_upgrade_separateTrueOptional. True, if the gift's upgrade was purchased after the gift was sent
      can_be_upgradedTrueOptional. True, if the gift can be upgraded to a unique gift
      textStringOptional. Text of the message that was added to the gift
      entitiesArray of MessageEntityOptional. Special entities that appear in the text
      is_privateTrueOptional. True, if the sender and gift text are shown only to the gift receiver; otherwise, everyone will be able to see them
      unique_gift_numberIntegerOptional. Unique number reserved for this gift when upgraded. See the number field in UniqueGift
      +

      UniqueGiftInfo

      +

      Describes a service message about a unique gift that was sent or received.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      giftUniqueGiftInformation about the gift
      originStringOrigin of the gift. Currently, either “upgrade” for gifts upgraded from regular gifts, “transfer” for gifts transferred from other users or channels, “resale” for gifts bought from other users, “gifted_upgrade” for upgrades purchased after the gift was sent, or “offer” for gifts bought or sold through gift purchase offers
      last_resale_currencyStringOptional. For gifts bought from other users, the currency in which the payment for the gift was done. Currently, one of “XTR” for Telegram Stars or “TON” for toncoins.
      last_resale_amountIntegerOptional. For gifts bought from other users, the price paid for the gift in either Telegram Stars or nanotoncoins
      owned_gift_idStringOptional. Unique identifier of the received gift for the bot; only present for gifts received on behalf of business accounts
      transfer_star_countIntegerOptional. Number of Telegram Stars that must be paid to transfer the gift; omitted if the bot cannot transfer the gift
      next_transfer_dateIntegerOptional. Point in time (Unix timestamp) when the gift can be transferred. If it is in the past, then the gift can be transferred now
      +

      OwnedGift

      +

      This object describes a gift received and owned by a user or a chat. Currently, it can be one of

      + +

      OwnedGiftRegular

      +

      Describes a regular gift owned by a user or a chat.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringType of the gift, always “regular”
      giftGiftInformation about the regular gift
      owned_gift_idStringOptional. Unique identifier of the gift for the bot; for gifts received on behalf of business accounts only
      sender_userUserOptional. Sender of the gift if it is a known user
      send_dateIntegerDate the gift was sent in Unix time
      textStringOptional. Text of the message that was added to the gift
      entitiesArray of MessageEntityOptional. Special entities that appear in the text
      is_privateTrueOptional. True, if the sender and gift text are shown only to the gift receiver; otherwise, everyone will be able to see them
      is_savedTrueOptional. True, if the gift is displayed on the account's profile page; for gifts received on behalf of business accounts only
      can_be_upgradedTrueOptional. True, if the gift can be upgraded to a unique gift; for gifts received on behalf of business accounts only
      was_refundedTrueOptional. True, if the gift was refunded and isn't available anymore
      convert_star_countIntegerOptional. Number of Telegram Stars that can be claimed by the receiver instead of the gift; omitted if the gift cannot be converted to Telegram Stars; for gifts received on behalf of business accounts only
      prepaid_upgrade_star_countIntegerOptional. Number of Telegram Stars that were paid for the ability to upgrade the gift
      is_upgrade_separateTrueOptional. True, if the gift's upgrade was purchased after the gift was sent; for gifts received on behalf of business accounts only
      unique_gift_numberIntegerOptional. Unique number reserved for this gift when upgraded. See the number field in UniqueGift
      +

      OwnedGiftUnique

      +

      Describes a unique gift received and owned by a user or a chat.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringType of the gift, always “unique”
      giftUniqueGiftInformation about the unique gift
      owned_gift_idStringOptional. Unique identifier of the received gift for the bot; for gifts received on behalf of business accounts only
      sender_userUserOptional. Sender of the gift if it is a known user
      send_dateIntegerDate the gift was sent in Unix time
      is_savedTrueOptional. True, if the gift is displayed on the account's profile page; for gifts received on behalf of business accounts only
      can_be_transferredTrueOptional. True, if the gift can be transferred to another owner; for gifts received on behalf of business accounts only
      transfer_star_countIntegerOptional. Number of Telegram Stars that must be paid to transfer the gift; omitted if the bot cannot transfer the gift
      next_transfer_dateIntegerOptional. Point in time (Unix timestamp) when the gift can be transferred. If it is in the past, then the gift can be transferred now
      +

      OwnedGifts

      +

      Contains the list of gifts received and owned by a user or a chat.

      + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      total_countIntegerThe total number of gifts owned by the user or the chat
      giftsArray of OwnedGiftThe list of gifts
      next_offsetStringOptional. Offset for the next request. If empty, then there are no more results
      +

      BotAccessSettings

      +

      This object describes the access settings of a bot.

      + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      is_access_restrictedBooleanTrue, if only selected users can access the bot. The bot's owner can always access it.
      added_usersArray of UserOptional. The list of other users who have access to the bot if the access is restricted
      +

      AcceptedGiftTypes

      +

      This object describes the types of gifts that can be gifted to a user or a chat.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      unlimited_giftsBooleanTrue, if unlimited regular gifts are accepted
      limited_giftsBooleanTrue, if limited regular gifts are accepted
      unique_giftsBooleanTrue, if unique gifts or gifts that can be upgraded to unique for free are accepted
      premium_subscriptionBooleanTrue, if a Telegram Premium subscription is accepted
      gifts_from_channelsBooleanTrue, if transfers of unique gifts from channels are accepted
      +

      StarAmount

      +

      Describes an amount of Telegram Stars.

      + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      amountIntegerInteger amount of Telegram Stars, rounded to 0; can be negative
      nanostar_amountIntegerOptional. The number of 1/1000000000 shares of Telegram Stars; from -999999999 to 999999999; can be negative if and only if amount is non-positive
      +

      BotCommand

      +

      This object represents a bot command.

      + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      commandStringText of the command; 1-32 characters. Can contain only lowercase English letters, digits and underscores.
      descriptionStringDescription of the command; 1-256 characters.
      +

      BotCommandScope

      +

      This object represents the scope to which bot commands are applied. Currently, the following 7 scopes are supported:

      + +

      Determining list of commands

      +

      The following algorithm is used to determine the list of commands for a particular user viewing the bot menu. The first list of commands which is set is returned:

      +

      Commands in the chat with the bot

      +
        +
      • botCommandScopeChat + language_code
      • +
      • botCommandScopeChat
      • +
      • botCommandScopeAllPrivateChats + language_code
      • +
      • botCommandScopeAllPrivateChats
      • +
      • botCommandScopeDefault + language_code
      • +
      • botCommandScopeDefault
      • +
      +

      Commands in group and supergroup chats

      +
        +
      • botCommandScopeChatMember + language_code
      • +
      • botCommandScopeChatMember
      • +
      • botCommandScopeChatAdministrators + language_code (administrators only)
      • +
      • botCommandScopeChatAdministrators (administrators only)
      • +
      • botCommandScopeChat + language_code
      • +
      • botCommandScopeChat
      • +
      • botCommandScopeAllChatAdministrators + language_code (administrators only)
      • +
      • botCommandScopeAllChatAdministrators (administrators only)
      • +
      • botCommandScopeAllGroupChats + language_code
      • +
      • botCommandScopeAllGroupChats
      • +
      • botCommandScopeDefault + language_code
      • +
      • botCommandScopeDefault
      • +
      +

      BotCommandScopeDefault

      +

      Represents the default scope of bot commands. Default commands are used if no commands with a narrower scope are specified for the user.

      + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringScope type, must be default
      +

      BotCommandScopeAllPrivateChats

      +

      Represents the scope of bot commands, covering all private chats.

      + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringScope type, must be all_private_chats
      +

      BotCommandScopeAllGroupChats

      +

      Represents the scope of bot commands, covering all group and supergroup chats.

      + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringScope type, must be all_group_chats
      +

      BotCommandScopeAllChatAdministrators

      +

      Represents the scope of bot commands, covering all group and supergroup chat administrators.

      + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringScope type, must be all_chat_administrators
      +

      BotCommandScopeChat

      +

      Represents the scope of bot commands, covering a specific chat.

      + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringScope type, must be chat
      chat_idInteger or StringUnique identifier for the target chat or username of the target supergroup in the format @username. Channel direct messages chats and channel chats aren't supported.
      +

      BotCommandScopeChatAdministrators

      +

      Represents the scope of bot commands, covering all administrators of a specific group or supergroup chat.

      + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringScope type, must be chat_administrators
      chat_idInteger or StringUnique identifier for the target chat or username of the target supergroup in the format @username. Channel direct messages chats and channel chats aren't supported.
      +

      BotCommandScopeChatMember

      +

      Represents the scope of bot commands, covering a specific member of a group or supergroup chat.

      + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringScope type, must be chat_member
      chat_idInteger or StringUnique identifier for the target chat or username of the target supergroup in the format @username. Channel direct messages chats and channel chats aren't supported.
      user_idIntegerUnique identifier of the target user
      +

      BotName

      +

      This object represents the bot's name.

      + + + + + + + + + + + + + + + +
      FieldTypeDescription
      nameStringThe bot's name
      +

      BotDescription

      +

      This object represents the bot's description.

      + + + + + + + + + + + + + + + +
      FieldTypeDescription
      descriptionStringThe bot's description
      +

      BotShortDescription

      +

      This object represents the bot's short description.

      + + + + + + + + + + + + + + + +
      FieldTypeDescription
      short_descriptionStringThe bot's short description
      +

      MenuButton

      +

      This object describes the bot's menu button in a private chat. It should be one of

      + +

      If a menu button other than MenuButtonDefault is set for a private chat, then it is applied in the chat. Otherwise the default menu button is applied. By default, the menu button opens the list of bot commands.

      +

      MenuButtonCommands

      +

      Represents a menu button, which opens the bot's list of commands.

      + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringType of the button, must be commands
      +

      MenuButtonWebApp

      +

      Represents a menu button, which launches a Web App.

      + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringType of the button, must be web_app
      textStringText on the button
      web_appWebAppInfoDescription of the Web App that will be launched when the user presses the button. The Web App will be able to send an arbitrary message on behalf of the user using the method answerWebAppQuery. Alternatively, a t.me link to a Web App of the bot can be specified in the object instead of the Web App's URL, in which case the Web App will be opened as if the user pressed the link.
      +

      MenuButtonDefault

      +

      Describes that no specific value for the menu button was set.

      + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringType of the button, must be default
      +

      ChatBoostSource

      +

      This object describes the source of a chat boost. It can be one of

      + +

      ChatBoostSourcePremium

      +

      The boost was obtained by subscribing to Telegram Premium or by gifting a Telegram Premium subscription to another user.

      + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      sourceStringSource of the boost, always “premium”
      userUserUser that boosted the chat
      +

      ChatBoostSourceGiftCode

      +

      The boost was obtained by the creation of Telegram Premium gift codes to boost a chat. Each such code boosts the chat 4 times for the duration of the corresponding Telegram Premium subscription.

      + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      sourceStringSource of the boost, always “gift_code”
      userUserUser for which the gift code was created
      +

      ChatBoostSourceGiveaway

      +

      The boost was obtained by the creation of a Telegram Premium or a Telegram Star giveaway. This boosts the chat 4 times for the duration of the corresponding Telegram Premium subscription for Telegram Premium giveaways and prize_star_count / 500 times for one year for Telegram Star giveaways.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      sourceStringSource of the boost, always “giveaway”
      giveaway_message_idIntegerIdentifier of a message in the chat with the giveaway; the message could have been deleted already. May be 0 if the message isn't sent yet.
      userUserOptional. User that won the prize in the giveaway if any; for Telegram Premium giveaways only
      prize_star_countIntegerOptional. The number of Telegram Stars to be split between giveaway winners; for Telegram Star giveaways only
      is_unclaimedTrueOptional. True, if the giveaway was completed, but there was no user to win the prize
      +

      ChatBoost

      +

      This object contains information about a chat boost.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      boost_idStringUnique identifier of the boost
      add_dateIntegerPoint in time (Unix timestamp) when the chat was boosted
      expiration_dateIntegerPoint in time (Unix timestamp) when the boost will automatically expire, unless the booster's Telegram Premium subscription is prolonged
      sourceChatBoostSourceSource of the added boost
      +

      ChatBoostUpdated

      +

      This object represents a boost added to a chat or changed.

      + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      chatChatChat which was boosted
      boostChatBoostInformation about the chat boost
      +

      ChatBoostRemoved

      +

      This object represents a boost removed from a chat.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      chatChatChat which was boosted
      boost_idStringUnique identifier of the boost
      remove_dateIntegerPoint in time (Unix timestamp) when the boost was removed
      sourceChatBoostSourceSource of the removed boost
      +

      ChatOwnerLeft

      +

      Describes a service message about the chat owner leaving the chat.

      + + + + + + + + + + + + + + + +
      FieldTypeDescription
      new_ownerUserOptional. The user who will become the new owner of the chat if the previous owner does not return to the chat
      +

      ChatOwnerChanged

      +

      Describes a service message about an ownership change in the chat.

      + + + + + + + + + + + + + + + +
      FieldTypeDescription
      new_ownerUserThe new owner of the chat
      +

      UserChatBoosts

      +

      This object represents a list of boosts added to a chat by a user.

      + + + + + + + + + + + + + + + +
      FieldTypeDescription
      boostsArray of ChatBoostThe list of boosts added to the chat by the user
      +

      BusinessBotRights

      +

      Represents the rights of a business bot.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      can_replyTrueOptional. True, if the bot can send and edit messages in the private chats that had incoming messages in the last 24 hours
      can_read_messagesTrueOptional. True, if the bot can mark incoming private messages as read
      can_delete_sent_messagesTrueOptional. True, if the bot can delete messages sent by the bot
      can_delete_all_messagesTrueOptional. True, if the bot can delete all private messages in managed chats
      can_edit_nameTrueOptional. True, if the bot can edit the first and last name of the business account
      can_edit_bioTrueOptional. True, if the bot can edit the bio of the business account
      can_edit_profile_photoTrueOptional. True, if the bot can edit the profile photo of the business account
      can_edit_usernameTrueOptional. True, if the bot can edit the username of the business account
      can_change_gift_settingsTrueOptional. True, if the bot can change the privacy settings pertaining to gifts for the business account
      can_view_gifts_and_starsTrueOptional. True, if the bot can view gifts and the amount of Telegram Stars owned by the business account
      can_convert_gifts_to_starsTrueOptional. True, if the bot can convert regular gifts owned by the business account to Telegram Stars
      can_transfer_and_upgrade_giftsTrueOptional. True, if the bot can transfer and upgrade gifts owned by the business account
      can_transfer_starsTrueOptional. True, if the bot can transfer Telegram Stars received by the business account to its own account, or use them to upgrade and transfer gifts
      can_manage_storiesTrueOptional. True, if the bot can post, edit and delete stories on behalf of the business account
      +

      BusinessConnection

      +

      Describes the connection of the bot with a business account.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      idStringUnique identifier of the business connection
      userUserBusiness account user that created the business connection
      user_chat_idIntegerIdentifier of a private chat with the user who created the business connection. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a 64-bit integer or double-precision float type are safe for storing this identifier.
      dateIntegerDate the connection was established in Unix time
      rightsBusinessBotRightsOptional. Rights of the business bot
      is_enabledBooleanTrue, if the connection is active
      +

      BusinessMessagesDeleted

      +

      This object is received when messages are deleted from a connected business account.

      + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      business_connection_idStringUnique identifier of the business connection
      chatChatInformation about a chat in the business account. The bot may not have access to the chat or the corresponding user.
      message_idsArray of IntegerThe list of identifiers of deleted messages in the chat of the business account
      +

      SentWebAppMessage

      +

      Describes an inline message sent by a Web App on behalf of a user.

      + + + + + + + + + + + + + + + +
      FieldTypeDescription
      inline_message_idStringOptional. Identifier of the sent inline message. Available only if there is an inline keyboard attached to the message.
      +

      SentGuestMessage

      +

      Describes an inline message sent by a guest bot.

      + + + + + + + + + + + + + + + +
      FieldTypeDescription
      inline_message_idStringIdentifier of the sent inline message
      +

      PreparedInlineMessage

      +

      Describes an inline message to be sent by a user of a Mini App.

      + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      idStringUnique identifier of the prepared message
      expiration_dateIntegerExpiration date of the prepared message, in Unix time. Expired prepared messages can no longer be used
      +

      PreparedKeyboardButton

      +

      Describes a keyboard button to be used by a user of a Mini App.

      + + + + + + + + + + + + + + + +
      FieldTypeDescription
      idStringUnique identifier of the keyboard button
      +

      ResponseParameters

      +

      Describes why a request was unsuccessful.

      + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      migrate_to_chat_idIntegerOptional. The group has been migrated to a supergroup with the specified identifier. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this identifier.
      retry_afterIntegerOptional. In case of exceeding flood control, the number of seconds left to wait before the request can be repeated
      +

      InputMedia

      +

      This object represents the content of a media message to be sent. It should be one of

      + +

      InputMediaAnimation

      +

      Represents an animation file (GIF or H.264/MPEG-4 AVC video without sound) to be sent.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringType of the result, must be animation
      mediaStringFile to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet, or pass “attach://<file_attach_name>” to upload a new one using multipart/form-data under <file_attach_name> name. More information on Sending Files »
      thumbnailStringOptional. Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://<file_attach_name>” if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files »
      captionStringOptional. Caption of the animation to be sent, 0-1024 characters after entities parsing
      parse_modeStringOptional. Mode for parsing entities in the animation caption. See formatting options for more details.
      caption_entitiesArray of MessageEntityOptional. List of special entities that appear in the caption, which can be specified instead of parse_mode
      show_caption_above_mediaBooleanOptional. Pass True, if the caption must be shown above the message media
      widthIntegerOptional. Animation width
      heightIntegerOptional. Animation height
      durationIntegerOptional. Animation duration in seconds
      has_spoilerBooleanOptional. Pass True if the animation needs to be covered with a spoiler animation
      +

      InputMediaAudio

      +

      Represents an audio file to be treated as music to be sent.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringType of the result, must be audio
      mediaStringFile to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet, or pass “attach://<file_attach_name>” to upload a new one using multipart/form-data under <file_attach_name> name. More information on Sending Files »
      thumbnailStringOptional. Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://<file_attach_name>” if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files »
      captionStringOptional. Caption of the audio to be sent, 0-1024 characters after entities parsing
      parse_modeStringOptional. Mode for parsing entities in the audio caption. See formatting options for more details.
      caption_entitiesArray of MessageEntityOptional. List of special entities that appear in the caption, which can be specified instead of parse_mode
      durationIntegerOptional. Duration of the audio in seconds
      performerStringOptional. Performer of the audio
      titleStringOptional. Title of the audio
      +

      InputMediaDocument

      +

      Represents a general file to be sent.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringType of the result, must be document
      mediaStringFile to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet, or pass “attach://<file_attach_name>” to upload a new one using multipart/form-data under <file_attach_name> name. More information on Sending Files »
      thumbnailStringOptional. Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://<file_attach_name>” if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files »
      captionStringOptional. Caption of the document to be sent, 0-1024 characters after entities parsing
      parse_modeStringOptional. Mode for parsing entities in the document caption. See formatting options for more details.
      caption_entitiesArray of MessageEntityOptional. List of special entities that appear in the caption, which can be specified instead of parse_mode
      disable_content_type_detectionBooleanOptional. Disables automatic server-side content type detection for files uploaded using multipart/form-data. Always True, if the document is sent as part of an album.
      +

      InputMediaLivePhoto

      +

      Represents a live photo to be sent.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringType of the result, must be live_photo
      mediaStringVideo of the live photo to send. Pass a file_id to send a file that exists on the Telegram servers (recommended) or pass “attach://<file_attach_name>” to upload a new one using multipart/form-data under <file_attach_name> name. More information on Sending Files ». Sending live photos by a URL is currently unsupported.
      photoStringThe static photo to send. Pass a file_id to send a file that exists on the Telegram servers (recommended) or pass “attach://<file_attach_name>” to upload a new one using multipart/form-data under <file_attach_name> name. More information on Sending Files ». Sending live photos by a URL is currently unsupported.
      captionStringOptional. Caption of the live photo to be sent, 0-1024 characters after entities parsing
      parse_modeStringOptional. Mode for parsing entities in the live photo caption. See formatting options for more details.
      caption_entitiesArray of MessageEntityOptional. List of special entities that appear in the caption, which can be specified instead of parse_mode
      show_caption_above_mediaBooleanOptional. Pass True, if the caption must be shown above the message media
      has_spoilerBooleanOptional. Pass True if the live photo needs to be covered with a spoiler animation
      +

      InputMediaLocation

      +

      Represents a location to be sent.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringType of the result, must be location
      latitudeFloatLatitude of the location
      longitudeFloatLongitude of the location
      horizontal_accuracyFloatOptional. The radius of uncertainty for the location, measured in meters; 0-1500
      +

      InputMediaPhoto

      +

      Represents a photo to be sent.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringType of the result, must be photo
      mediaStringFile to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet, or pass “attach://<file_attach_name>” to upload a new one using multipart/form-data under <file_attach_name> name. More information on Sending Files »
      captionStringOptional. Caption of the photo to be sent, 0-1024 characters after entities parsing
      parse_modeStringOptional. Mode for parsing entities in the photo caption. See formatting options for more details.
      caption_entitiesArray of MessageEntityOptional. List of special entities that appear in the caption, which can be specified instead of parse_mode
      show_caption_above_mediaBooleanOptional. Pass True, if the caption must be shown above the message media
      has_spoilerBooleanOptional. Pass True if the photo needs to be covered with a spoiler animation
      +

      InputMediaSticker

      +

      Represents a sticker file to be sent.

      + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringType of the result, must be sticker
      mediaStringFile to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for Telegram to get a .WEBP sticker from the Internet, or pass “attach://<file_attach_name>” to upload a new .WEBP, .TGS, or .WEBM sticker using multipart/form-data under <file_attach_name> name. More information on Sending Files »
      emojiStringOptional. Emoji associated with the sticker; only for just uploaded stickers
      +

      InputMediaVenue

      +

      Represents a venue to be sent.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringType of the result, must be venue
      latitudeFloatLatitude of the location
      longitudeFloatLongitude of the location
      titleStringName of the venue
      addressStringAddress of the venue
      foursquare_idStringOptional. Foursquare identifier of the venue
      foursquare_typeStringOptional. Foursquare type of the venue, if known. (For example, “arts_entertainment/default”, “arts_entertainment/aquarium” or “food/icecream”.)
      google_place_idStringOptional. Google Places identifier of the venue
      google_place_typeStringOptional. Google Places type of the venue. (See supported types.)
      +

      InputMediaVideo

      +

      Represents a video to be sent.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringType of the result, must be video
      mediaStringFile to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet, or pass “attach://<file_attach_name>” to upload a new one using multipart/form-data under <file_attach_name> name. More information on Sending Files »
      thumbnailStringOptional. Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://<file_attach_name>” if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files »
      coverStringOptional. Cover for the video in the message. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet, or pass “attach://<file_attach_name>” to upload a new one using multipart/form-data under <file_attach_name> name. More information on Sending Files »
      start_timestampIntegerOptional. Start timestamp for the video in the message
      captionStringOptional. Caption of the video to be sent, 0-1024 characters after entities parsing
      parse_modeStringOptional. Mode for parsing entities in the video caption. See formatting options for more details.
      caption_entitiesArray of MessageEntityOptional. List of special entities that appear in the caption, which can be specified instead of parse_mode
      show_caption_above_mediaBooleanOptional. Pass True, if the caption must be shown above the message media
      widthIntegerOptional. Video width
      heightIntegerOptional. Video height
      durationIntegerOptional. Video duration in seconds
      supports_streamingBooleanOptional. Pass True if the uploaded video is suitable for streaming
      has_spoilerBooleanOptional. Pass True if the video needs to be covered with a spoiler animation
      +

      InputFile

      +

      This object represents the contents of a file to be uploaded. Must be posted using multipart/form-data in the usual way that files are uploaded via the browser.

      +

      InputPaidMedia

      +

      This object describes the paid media to be sent. Currently, it can be one of

      + +

      InputPaidMediaLivePhoto

      +

      The paid media to send is a live photo.

      + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringType of the media, must be live_photo
      mediaStringVideo of the live photo to send. Pass a file_id to send a file that exists on the Telegram servers (recommended) or pass “attach://<file_attach_name>” to upload a new one using multipart/form-data under <file_attach_name> name. More information on Sending Files ». Sending live photos by a URL is currently unsupported.
      photoStringThe static photo to send. Pass a file_id to send a file that exists on the Telegram servers (recommended) or pass “attach://<file_attach_name>” to upload a new one using multipart/form-data under <file_attach_name> name. More information on Sending Files ». Sending live photos by a URL is currently unsupported.
      +

      InputPaidMediaPhoto

      +

      The paid media to send is a photo.

      + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringType of the media, must be photo
      mediaStringFile to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet, or pass “attach://<file_attach_name>” to upload a new one using multipart/form-data under <file_attach_name> name. More information on Sending Files »
      +

      InputPaidMediaVideo

      +

      The paid media to send is a video.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringType of the media, must be video
      mediaStringFile to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet, or pass “attach://<file_attach_name>” to upload a new one using multipart/form-data under <file_attach_name> name. More information on Sending Files »
      thumbnailStringOptional. Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://<file_attach_name>” if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files »
      coverStringOptional. Cover for the video in the message. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet, or pass “attach://<file_attach_name>” to upload a new one using multipart/form-data under <file_attach_name> name. More information on Sending Files »
      start_timestampIntegerOptional. Start timestamp for the video in the message
      widthIntegerOptional. Video width
      heightIntegerOptional. Video height
      durationIntegerOptional. Video duration in seconds
      supports_streamingBooleanOptional. Pass True if the uploaded video is suitable for streaming
      +

      InputProfilePhoto

      +

      This object describes a profile photo to set. Currently, it can be one of

      + +

      InputProfilePhotoStatic

      +

      A static profile photo in the .JPG format.

      + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringType of the profile photo, must be static
      photoStringThe static profile photo. Profile photos can't be reused and can only be uploaded as a new file, so you can pass “attach://<file_attach_name>” if the photo was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files »
      +

      InputProfilePhotoAnimated

      +

      An animated profile photo in the MPEG4 format.

      + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringType of the profile photo, must be animated
      animationStringThe animated profile photo. Profile photos can't be reused and can only be uploaded as a new file, so you can pass “attach://<file_attach_name>” if the photo was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files »
      main_frame_timestampFloatOptional. Timestamp in seconds of the frame that will be used as the static profile photo. Defaults to 0.0.
      +

      InputStoryContent

      +

      This object describes the content of a story to post. Currently, it can be one of

      + +

      InputStoryContentPhoto

      +

      Describes a photo to post as a story.

      + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringType of the content, must be photo
      photoStringThe photo to post as a story. The photo must be of the size 1080x1920 and must not exceed 10 MB. The photo can't be reused and can only be uploaded as a new file, so you can pass “attach://<file_attach_name>” if the photo was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files »
      +

      InputStoryContentVideo

      +

      Describes a video to post as a story.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringType of the content, must be video
      videoStringThe video to post as a story. The video must be of the size 720x1280, streamable, encoded with H.265 codec, with key frames added each second in the MPEG4 format, and must not exceed 30 MB. The video can't be reused and can only be uploaded as a new file, so you can pass “attach://<file_attach_name>” if the video was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files »
      durationFloatOptional. Precise duration of the video in seconds; 0-60
      cover_frame_timestampFloatOptional. Timestamp in seconds of the frame that will be used as the static cover for the story. Defaults to 0.0.
      is_animationBooleanOptional. Pass True if the video has no sound
      +

      Sending files

      +

      There are three ways to send files (photos, stickers, audio, media, etc.):

      +
        +
      1. If the file is already stored somewhere on the Telegram servers, you don't need to reupload it: each file object has a file_id field, simply pass this file_id as a parameter instead of uploading. There are no limits for files sent this way.
      2. +
      3. Provide Telegram with an HTTP URL for the file to be sent. Telegram will download and send the file. 5 MB max size for photos and 20 MB max for other types of content.
      4. +
      5. Post the file using multipart/form-data in the usual way that files are uploaded via the browser. 10 MB max size for photos, 50 MB for other files.
      6. +
      +

      Sending by file_id

      +
        +
      • It is not possible to change the file type when resending by file_id. I.e. a video can't be sent as a photo, a photo can't be sent as a document, etc.
      • +
      • It is not possible to resend thumbnails.
      • +
      • Resending a photo by file_id will send all of its sizes.
      • +
      • file_id is unique for each individual bot and can't be transferred from one bot to another.
      • +
      • file_id uniquely identifies a file, but a file can have different valid file_ids even for the same bot.
      • +
      +

      Sending by URL

      +
        +
      • When sending by URL the target file must have the correct MIME type (e.g., audio/mpeg for sendAudio, etc.).
      • +
      • In sendDocument, sending by URL will currently only work for .PDF and .ZIP files.
      • +
      • To use sendVoice, the file must have the type audio/ogg and be no more than 1MB in size. 1-20MB voice notes will be sent as files.
      • +
      • Other configurations may work but we can't guarantee that they will.
      • +
      +

      Accent colors

      +

      Colors with identifiers 0 (red), 1 (orange), 2 (purple/violet), 3 (green), 4 (cyan), 5 (blue), 6 (pink) can be customized by app themes. Additionally, the following colors in RGB format are currently in use.

      +

      + + + + + + + + + + + + + + + + + + + +
      Color identifierLight colorsDark colors
      7E15052 F9AE63FF9380 992F37
      8E0802B FAC534ECB04E C35714
      9A05FF3 F48FFFC697FF 5E31C8
      1027A910 A7DC57A7EB6E 167E2D
      1127ACCE 82E8D640D8D0 045C7F
      123391D4 7DD3F052BFFF 0B5494
      13DD4371 FFBE9FFF86A6 8E366E
      14247BED F04856 FFFFFF3FA2FE E5424F FFFFFF
      15D67722 1EA011 FFFFFFFF905E 32A527 FFFFFF
      16179E42 E84A3F FFFFFF66D364 D5444F FFFFFF
      172894AF 6FC456 FFFFFF22BCE2 3DA240 FFFFFF
      180C9AB3 FFAD95 FFE6B522BCE2 FF9778 FFDA6B
      197757D6 F79610 FFDE8E9791FF F2731D FFDB59
      201585CF F2AB1D FFFFFF3DA6EB EEA51D FFFFFF

      +

      Profile accent colors

      +

      Currently, the following colors in RGB format are in use for profile backgrounds.

      +

      + + + + + + + + + + + + + + + + + + + + + +
      Color identifierLight colorsDark colors
      0BA56509C4540
      1C27C3E945E2C
      2956AC8715099
      349A35533713B
      43E97AD387E87
      55A8FBB477194
      6B85378944763
      77F8B95435261
      8C9565D D97C57994343 AC583E
      9CF7244 CC94338F552F A17232
      109662D4 B966B6634691 9250A2
      113D9755 89A650296A43 5F8F44
      123D95BA 50AD98306C7C 3E987E
      13538BC2 4DA8BD38618C 458BA1
      14B04F74 D1666D884160 A65259
      15637482 7B8A9753606E 384654

      +

      Inline mode objects

      +

      Objects and methods used in the inline mode are described in the Inline mode section.

      +

      Available methods

      +
      +

      All methods in the Bot API are case-insensitive. We support GET and POST HTTP methods. Use either URL query string or application/json or application/x-www-form-urlencoded or multipart/form-data for passing parameters in Bot API requests.
      On successful call, a JSON-object containing the result will be returned.

      +
      +

      getMe

      +

      A simple method for testing your bot's authentication token. Requires no parameters. Returns basic information about the bot in form of a User object.

      +

      logOut

      +

      Use this method to log out from the cloud Bot API server before launching the bot locally. You must log out the bot before running it locally, otherwise there is no guarantee that the bot will receive updates. After a successful call, you can immediately log in on a local server, but will not be able to log in back to the cloud Bot API server for 10 minutes. Returns True on success. Requires no parameters.

      +

      close

      +

      Use this method to close the bot instance before moving it from one local server to another. You need to delete the webhook before calling this method to ensure that the bot isn't launched again after server restart. The method will return error 429 in the first 10 minutes after the bot is launched. Returns True on success. Requires no parameters.

      +

      sendMessage

      +

      Use this method to send text messages. On success, the sent Message is returned.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      business_connection_idStringOptionalUnique identifier of the business connection on behalf of which the message will be sent
      chat_idInteger or StringYesUnique identifier for the target chat or username of the target bot, supergroup or channel in the format @username
      message_thread_idIntegerOptionalUnique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only
      direct_messages_topic_idIntegerOptionalIdentifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat
      textStringYesText of the message to be sent, 1-4096 characters after entities parsing
      parse_modeStringOptionalMode for parsing entities in the message text. See formatting options for more details.
      entitiesArray of MessageEntityOptionalA JSON-serialized list of special entities that appear in message text, which can be specified instead of parse_mode
      link_preview_optionsLinkPreviewOptionsOptionalLink preview generation options for the message
      disable_notificationBooleanOptionalSends the message silently. Users will receive a notification with no sound.
      protect_contentBooleanOptionalProtects the contents of the sent message from forwarding and saving
      allow_paid_broadcastBooleanOptionalPass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance.
      message_effect_idStringOptionalUnique identifier of the message effect to be added to the message; for private chats only
      suggested_post_parametersSuggestedPostParametersOptionalA JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined.
      reply_parametersReplyParametersOptionalDescription of the message to reply to
      reply_markupInlineKeyboardMarkup or ReplyKeyboardMarkup or ReplyKeyboardRemove or ForceReplyOptionalAdditional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user
      +

      Formatting options

      +

      The Bot API supports basic formatting for messages. You can use bold, italic, underlined, strikethrough, spoiler text, block quotations as well as inline links and pre-formatted code in your bots' messages. Telegram clients will render them accordingly. You can specify text entities directly, or use markdown-style or HTML-style formatting.

      +

      Note that Telegram clients will display an alert to the user before opening an inline link ('Open this link?' together with the full URL).

      +

      Message entities can be nested, providing following restrictions are met:
      - If two entities have common characters, then one of them is fully contained inside another.
      - bold, italic, underline, strikethrough, and spoiler entities can contain and can be part of any other entities, except pre and code.
      - blockquote and expandable_blockquote entities can't be nested.
      - All other entities can't contain each other.

      +

      Links tg://user?id=<user_id> can be used to mention a user by their identifier without using a username. Please note:

      +
        +
      • These links will work only if they are used inside an inline link or in an inline keyboard button. For example, they will not work, when used in a message text.
      • +
      • Unless the user is a member of the chat where they were mentioned, these mentions are only guaranteed to work if the user has contacted the bot in private in the past or has sent a callback query to the bot via an inline button and doesn't have Forwarded Messages privacy enabled for the bot.
      • +
      +

      You can find the list of programming and markup languages for which syntax highlighting is supported at libprisma#supported-languages.

      +
      Date-time entity formatting
      +

      Date-time entity formatting is specified by a format string, which must adhere to the following regular expression: r|w?[dD]?[tT]?.

      +

      If the format string is empty, the underlying text is displayed as-is; however, the user can still receive the underlying date in their local format. When populated, the format string determines the output based on the presence of the following control characters:

      +
        +
      • r: Displays the time relative to the current time. Cannot be combined with any other control characters.
      • +
      • w: Displays the day of the week in the user's localized language.
      • +
      • d: Displays the date in short form (e.g., “17.03.22”).
      • +
      • D: Displays the date in long form (e.g., “March 17, 2022”).
      • +
      • t: Displays the time in short form (e.g., “22:45”).
      • +
      • T: Displays the time in long form (e.g., “22:45:00”).
      • +
      +
      MarkdownV2 style
      +

      To use this mode, pass MarkdownV2 in the parse_mode field. Use the following syntax in your message:

      +
      *bold \*text*
      +_italic \*text_
      +__underline__
      +~strikethrough~
      +||spoiler||
      +*bold _italic bold ~italic bold strikethrough ||italic bold strikethrough spoiler||~ __underline italic bold___ bold*
      +[inline URL](http://www.example.com/)
      +[inline mention of a user](tg://user?id=123456789)
      +![👍](tg://emoji?id=5368324170671202286)
      +![22:45 tomorrow](tg://time?unix=1647531900&format=wDT)
      +![22:45 tomorrow](tg://time?unix=1647531900&format=t)
      +![22:45 tomorrow](tg://time?unix=1647531900&format=r)
      +![22:45 tomorrow](tg://time?unix=1647531900)
      +`inline fixed-width code`
      +```
      +pre-formatted fixed-width code block
      +```
      +```python
      +pre-formatted fixed-width code block written in the Python programming language
      +```
      +>Block quotation started
      +>Block quotation continued
      +>Block quotation continued
      +>Block quotation continued
      +>The last line of the block quotation
      +**>The expandable block quotation started right after the previous block quotation
      +>It is separated from the previous block quotation by an empty bold entity
      +>Expandable block quotation continued
      +>Hidden by default part of the expandable block quotation started
      +>Expandable block quotation continued
      +>The last line of the expandable block quotation with the expandability mark||
      +

      Please note:

      +
        +
      • Any character with code between 1 and 126 inclusively can be escaped anywhere with a preceding '\' character, in which case it is treated as an ordinary character and not a part of the markup. This implies that '\' character usually must be escaped with a preceding '\' character.
      • +
      • Inside pre and code entities, all '`' and '\' characters must be escaped with a preceding '\' character.
      • +
      • Inside the (...) part of the inline link and custom emoji definition, all ')' and '\' must be escaped with a preceding '\' character.
      • +
      • In all other places characters '_', '*', '[', ']', '(', ')', '~', '`', '>', '#', '+', '-', '=', '|', '{', '}', '.', '!' must be escaped with the preceding character '\'.
      • +
      • In case of ambiguity between italic and underline entities __ is always greedily treated from left to right as beginning or end of an underline entity, so instead of ___italic underline___ use ___italic underline_**__, adding an empty bold entity as a separator.
      • +
      • A valid emoji must be provided as an alternative value for the custom emoji. The emoji will be shown instead of the custom emoji in places where a custom emoji cannot be displayed (e.g., system notifications) or if the message is forwarded by a non-premium user. It is recommended to use the emoji from the emoji field of the custom emoji sticker.
      • +
      • Custom emoji entities can only be used by bots that purchased additional usernames on Fragment or in the messages directly sent by the bot to private, group and supergroup chats if the owner of the bot has a Telegram Premium subscription.
      • +
      • See date-time entity formatting for more details about supported date-time formats.
      • +
      +
      HTML style
      +

      To use this mode, pass HTML in the parse_mode field. The following tags are currently supported:

      +
      <b>bold</b>, <strong>bold</strong>
      +<i>italic</i>, <em>italic</em>
      +<u>underline</u>, <ins>underline</ins>
      +<s>strikethrough</s>, <strike>strikethrough</strike>, <del>strikethrough</del>
      +<span class="tg-spoiler">spoiler</span>, <tg-spoiler>spoiler</tg-spoiler>
      +<b>bold <i>italic bold <s>italic bold strikethrough <span class="tg-spoiler">italic bold strikethrough spoiler</span></s> <u>underline italic bold</u></i> bold</b>
      +<a href="http://www.example.com/">inline URL</a>
      +<a href="tg://user?id=123456789">inline mention of a user</a>
      +<tg-emoji emoji-id="5368324170671202286">👍</tg-emoji>
      +<tg-time unix="1647531900" format="wDT">22:45 tomorrow</tg-time>
      +<tg-time unix="1647531900" format="t">22:45 tomorrow</tg-time>
      +<tg-time unix="1647531900" format="r">22:45 tomorrow</tg-time>
      +<tg-time unix="1647531900">22:45 tomorrow</tg-time>
      +<code>inline fixed-width code</code>
      +<pre>pre-formatted fixed-width code block</pre>
      +<pre><code class="language-python">pre-formatted fixed-width code block written in the Python programming language</code></pre>
      +<blockquote>Block quotation started\nBlock quotation continued\nThe last line of the block quotation</blockquote>
      +<blockquote expandable>Expandable block quotation started\nExpandable block quotation continued\nExpandable block quotation continued\nHidden by default part of the block quotation started\nExpandable block quotation continued\nThe last line of the block quotation</blockquote>
      +

      Please note:

      +
        +
      • Only the tags mentioned above are currently supported.
      • +
      • All <, > and & symbols that are not a part of a tag or an HTML entity must be replaced with the corresponding HTML entities (< with &lt;, > with &gt; and & with &amp;).
      • +
      • All numerical HTML entities are supported.
      • +
      • The API currently supports only the following named HTML entities: &lt;, &gt;, &amp; and &quot;.
      • +
      • Use nested pre and code tags, to define programming language for pre entity.
      • +
      • Programming language can't be specified for standalone code tags.
      • +
      • A valid emoji must be used as the content of the tg-emoji tag. The emoji will be shown instead of the custom emoji in places where a custom emoji cannot be displayed (e.g., system notifications) or if the message is forwarded by a non-premium user. It is recommended to use the emoji from the emoji field of the custom emoji sticker.
      • +
      • Custom emoji entities can only be used by bots that purchased additional usernames on Fragment or in the messages directly sent by the bot to private, group and supergroup chats if the owner of the bot has a Telegram Premium subscription.
      • +
      • See date-time entity formatting for more details about supported date-time formats.
      • +
      +
      Markdown style
      +

      This is a legacy mode, retained for backward compatibility. To use this mode, pass Markdown in the parse_mode field. Use the following syntax in your message:

      +
      *bold text*
      +_italic text_
      +[inline URL](http://www.example.com/)
      +[inline mention of a user](tg://user?id=123456789)
      +`inline fixed-width code`
      +```
      +pre-formatted fixed-width code block
      +```
      +```python
      +pre-formatted fixed-width code block written in the Python programming language
      +```
      +

      Please note:

      +
        +
      • Entities must not be nested, use parse mode MarkdownV2 instead.
      • +
      • There is no way to specify “underline”, “strikethrough”, “spoiler”, “blockquote”, “expandable_blockquote”, “custom_emoji”, and “date_time” entities, use parse mode MarkdownV2 instead.
      • +
      • To escape characters '_', '*', '`', '[' outside of an entity, prepend the character '\' before them.
      • +
      • Escaping inside entities is not allowed, so entity must be closed first and reopened again: use _snake_\__case_ for italic snake_case and *2*\**2=4* for bold 2*2=4.
      • +
      +

      Paid Broadcasts

      +

      By default, all bots are able to broadcast up to 30 messages per second to their users. Developers can increase this limit by enabling Paid Broadcasts in @BotFather - allowing their bot to broadcast up to 1000 messages per second.

      +

      Each message broadcasted over the free amount of 30 messages per second incurs a cost of 0.1 Stars per message, paid with Telegram Stars from the bot's balance. In order to use this feature, a bot must have at least 10,000 Stars on its balance.

      +
      +

      Bots with increased limits are only charged for messages that are broadcasted successfully.

      +
      +

      forwardMessage

      +

      Use this method to forward messages of any kind. Service messages and messages with protected content can't be forwarded. On success, the sent Message is returned.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      chat_idInteger or StringYesUnique identifier for the target chat or username of the target bot, supergroup or channel in the format @username
      message_thread_idIntegerOptionalUnique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only
      direct_messages_topic_idIntegerOptionalIdentifier of the direct messages topic to which the message will be forwarded; required if the message is forwarded to a direct messages chat
      from_chat_idInteger or StringYesUnique identifier for the chat where the original message was sent (or username of the target bot, supergroup or channel in the format @username)
      video_start_timestampIntegerOptionalNew start timestamp for the forwarded video in the message
      disable_notificationBooleanOptionalSends the message silently. Users will receive a notification with no sound.
      protect_contentBooleanOptionalProtects the contents of the forwarded message from forwarding and saving
      message_effect_idStringOptionalUnique identifier of the message effect to be added to the message; only available when forwarding to private chats
      suggested_post_parametersSuggestedPostParametersOptionalA JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only
      message_idIntegerYesMessage identifier in the chat specified in from_chat_id
      +

      forwardMessages

      +

      Use this method to forward multiple messages of any kind. If some of the specified messages can't be found or forwarded, they are skipped. Service messages and messages with protected content can't be forwarded. Album grouping is kept for forwarded messages. On success, an array of MessageId of the sent messages is returned.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      chat_idInteger or StringYesUnique identifier for the target chat or username of the target bot, supergroup or channel in the format @username
      message_thread_idIntegerOptionalUnique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only
      direct_messages_topic_idIntegerOptionalIdentifier of the direct messages topic to which the messages will be forwarded; required if the messages are forwarded to a direct messages chat
      from_chat_idInteger or StringYesUnique identifier for the chat where the original messages were sent (or username of the target bot, supergroup or channel in the format @username)
      message_idsArray of IntegerYesA JSON-serialized list of 1-100 identifiers of messages in the chat from_chat_id to forward. The identifiers must be specified in a strictly increasing order.
      disable_notificationBooleanOptionalSends the messages silently. Users will receive a notification with no sound.
      protect_contentBooleanOptionalProtects the contents of the forwarded messages from forwarding and saving
      +

      copyMessage

      +

      Use this method to copy messages of any kind. Service messages, paid media messages, giveaway messages, giveaway winners messages, and invoice messages can't be copied. A quiz poll can be copied only if the value of the field correct_option_id is known to the bot. The method is analogous to the method forwardMessage, but the copied message doesn't have a link to the original message. Returns the MessageId of the sent message on success.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      chat_idInteger or StringYesUnique identifier for the target chat or username of the target bot, supergroup or channel in the format @username
      message_thread_idIntegerOptionalUnique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only
      direct_messages_topic_idIntegerOptionalIdentifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat
      from_chat_idInteger or StringYesUnique identifier for the chat where the original message was sent (or username of the target bot, supergroup or channel in the format @username)
      message_idIntegerYesMessage identifier in the chat specified in from_chat_id
      video_start_timestampIntegerOptionalNew start timestamp for the copied video in the message
      captionStringOptionalNew caption for media, 0-1024 characters after entities parsing. If not specified, the original caption is kept
      parse_modeStringOptionalMode for parsing entities in the new caption. See formatting options for more details.
      caption_entitiesArray of MessageEntityOptionalA JSON-serialized list of special entities that appear in the new caption, which can be specified instead of parse_mode
      show_caption_above_mediaBooleanOptionalPass True, if the caption must be shown above the message media. Ignored if a new caption isn't specified.
      disable_notificationBooleanOptionalSends the message silently. Users will receive a notification with no sound.
      protect_contentBooleanOptionalProtects the contents of the sent message from forwarding and saving
      allow_paid_broadcastBooleanOptionalPass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance.
      message_effect_idStringOptionalUnique identifier of the message effect to be added to the message; only available when copying to private chats
      suggested_post_parametersSuggestedPostParametersOptionalA JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined.
      reply_parametersReplyParametersOptionalDescription of the message to reply to
      reply_markupInlineKeyboardMarkup or ReplyKeyboardMarkup or ReplyKeyboardRemove or ForceReplyOptionalAdditional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user
      +

      copyMessages

      +

      Use this method to copy messages of any kind. If some of the specified messages can't be found or copied, they are skipped. Service messages, paid media messages, giveaway messages, giveaway winners messages, and invoice messages can't be copied. A quiz poll can be copied only if the value of the field correct_option_id is known to the bot. The method is analogous to the method forwardMessages, but the copied messages don't have a link to the original message. Album grouping is kept for copied messages. On success, an array of MessageId of the sent messages is returned.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      chat_idInteger or StringYesUnique identifier for the target chat or username of the target bot, supergroup or channel in the format @username
      message_thread_idIntegerOptionalUnique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only
      direct_messages_topic_idIntegerOptionalIdentifier of the direct messages topic to which the messages will be sent; required if the messages are sent to a direct messages chat
      from_chat_idInteger or StringYesUnique identifier for the chat where the original messages were sent (or username of the target bot, supergroup or channel in the format @username)
      message_idsArray of IntegerYesA JSON-serialized list of 1-100 identifiers of messages in the chat from_chat_id to copy. The identifiers must be specified in a strictly increasing order.
      disable_notificationBooleanOptionalSends the messages silently. Users will receive a notification with no sound.
      protect_contentBooleanOptionalProtects the contents of the sent messages from forwarding and saving
      remove_captionBooleanOptionalPass True to copy the messages without their captions
      +

      sendPhoto

      +

      Use this method to send photos. On success, the sent Message is returned.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      business_connection_idStringOptionalUnique identifier of the business connection on behalf of which the message will be sent
      chat_idInteger or StringYesUnique identifier for the target chat or username of the target bot, supergroup or channel in the format @username
      message_thread_idIntegerOptionalUnique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only
      direct_messages_topic_idIntegerOptionalIdentifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat
      photoInputFile or StringYesPhoto to send. Pass a file_id as String to send a photo that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a photo from the Internet, or upload a new photo using multipart/form-data. The photo must be at most 10 MB in size. The photo's width and height must not exceed 10000 in total. Width and height ratio must be at most 20. More information on Sending Files »
      captionStringOptionalPhoto caption (may also be used when resending photos by file_id), 0-1024 characters after entities parsing
      parse_modeStringOptionalMode for parsing entities in the photo caption. See formatting options for more details.
      caption_entitiesArray of MessageEntityOptionalA JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode
      show_caption_above_mediaBooleanOptionalPass True, if the caption must be shown above the message media
      has_spoilerBooleanOptionalPass True if the photo needs to be covered with a spoiler animation
      disable_notificationBooleanOptionalSends the message silently. Users will receive a notification with no sound.
      protect_contentBooleanOptionalProtects the contents of the sent message from forwarding and saving
      allow_paid_broadcastBooleanOptionalPass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance.
      message_effect_idStringOptionalUnique identifier of the message effect to be added to the message; for private chats only
      suggested_post_parametersSuggestedPostParametersOptionalA JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined.
      reply_parametersReplyParametersOptionalDescription of the message to reply to
      reply_markupInlineKeyboardMarkup or ReplyKeyboardMarkup or ReplyKeyboardRemove or ForceReplyOptionalAdditional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user
      +

      sendLivePhoto

      +

      Use this method to send live photos. On success, the sent Message is returned.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      business_connection_idStringOptionalUnique identifier of the business connection on behalf of which the message will be sent
      chat_idInteger or StringYesUnique identifier for the target chat or username of the target channel (in the format @channelusername)
      message_thread_idIntegerOptionalUnique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only
      direct_messages_topic_idIntegerOptionalIdentifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat
      live_photoInputFile or StringYesLive photo video to send. The video must be no longer than 10 seconds and must not exceed 10 MB in size. Pass a file_id as String to send a video that exists on the Telegram servers (recommended) or upload a new video using multipart/form-data. More information on Sending Files ». Sending live photos by a URL is currently unsupported.
      photoInputFile or StringYesThe static photo to send. Pass a file_id as String to send a photo that exists on the Telegram servers (recommended) or upload a new video using multipart/form-data. More information on Sending Files ». Sending live photos by a URL is currently unsupported.
      captionStringOptionalVideo caption (may also be used when resending videos by file_id), 0-1024 characters after entities parsing
      parse_modeStringOptionalMode for parsing entities in the video caption. See formatting options for more details.
      caption_entitiesArray of MessageEntityOptionalA JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode
      show_caption_above_mediaBooleanOptionalPass True, if the caption must be shown above the message media
      has_spoilerBooleanOptionalPass True if the video needs to be covered with a spoiler animation
      disable_notificationBooleanOptionalSends the message silently. Users will receive a notification with no sound.
      protect_contentBooleanOptionalProtects the contents of the sent message from forwarding and saving
      allow_paid_broadcastBooleanOptionalPass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance.
      message_effect_idStringOptionalUnique identifier of the message effect to be added to the message; for private chats only
      suggested_post_parametersSuggestedPostParametersOptionalA JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined.
      reply_parametersReplyParametersOptionalDescription of the message to reply to
      reply_markupInlineKeyboardMarkup or ReplyKeyboardMarkup or ReplyKeyboardRemove or ForceReplyOptionalAdditional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user.
      +

      sendAudio

      +

      Use this method to send audio files, if you want Telegram clients to display them in the music player. Your audio must be in the .MP3 or .M4A format. On success, the sent Message is returned. Bots can currently send audio files of up to 50 MB in size, this limit may be changed in the future.

      +

      For sending voice messages, use the sendVoice method instead.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      business_connection_idStringOptionalUnique identifier of the business connection on behalf of which the message will be sent
      chat_idInteger or StringYesUnique identifier for the target chat or username of the target bot, supergroup or channel in the format @username
      message_thread_idIntegerOptionalUnique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only
      direct_messages_topic_idIntegerOptionalIdentifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat
      audioInputFile or StringYesAudio file to send. Pass a file_id as String to send an audio file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an audio file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files »
      captionStringOptionalAudio caption, 0-1024 characters after entities parsing
      parse_modeStringOptionalMode for parsing entities in the audio caption. See formatting options for more details.
      caption_entitiesArray of MessageEntityOptionalA JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode
      durationIntegerOptionalDuration of the audio in seconds
      performerStringOptionalPerformer
      titleStringOptionalTrack name
      thumbnailInputFile or StringOptionalThumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://<file_attach_name>” if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files »
      disable_notificationBooleanOptionalSends the message silently. Users will receive a notification with no sound.
      protect_contentBooleanOptionalProtects the contents of the sent message from forwarding and saving
      allow_paid_broadcastBooleanOptionalPass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance.
      message_effect_idStringOptionalUnique identifier of the message effect to be added to the message; for private chats only
      suggested_post_parametersSuggestedPostParametersOptionalA JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined.
      reply_parametersReplyParametersOptionalDescription of the message to reply to
      reply_markupInlineKeyboardMarkup or ReplyKeyboardMarkup or ReplyKeyboardRemove or ForceReplyOptionalAdditional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user
      +

      sendDocument

      +

      Use this method to send general files. On success, the sent Message is returned. Bots can currently send files of any type of up to 50 MB in size, this limit may be changed in the future.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      business_connection_idStringOptionalUnique identifier of the business connection on behalf of which the message will be sent
      chat_idInteger or StringYesUnique identifier for the target chat or username of the target bot, supergroup or channel in the format @username
      message_thread_idIntegerOptionalUnique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only
      direct_messages_topic_idIntegerOptionalIdentifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat
      documentInputFile or StringYesFile to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files »
      thumbnailInputFile or StringOptionalThumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://<file_attach_name>” if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files »
      captionStringOptionalDocument caption (may also be used when resending documents by file_id), 0-1024 characters after entities parsing
      parse_modeStringOptionalMode for parsing entities in the document caption. See formatting options for more details.
      caption_entitiesArray of MessageEntityOptionalA JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode
      disable_content_type_detectionBooleanOptionalDisables automatic server-side content type detection for files uploaded using multipart/form-data
      disable_notificationBooleanOptionalSends the message silently. Users will receive a notification with no sound.
      protect_contentBooleanOptionalProtects the contents of the sent message from forwarding and saving
      allow_paid_broadcastBooleanOptionalPass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance.
      message_effect_idStringOptionalUnique identifier of the message effect to be added to the message; for private chats only
      suggested_post_parametersSuggestedPostParametersOptionalA JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined.
      reply_parametersReplyParametersOptionalDescription of the message to reply to
      reply_markupInlineKeyboardMarkup or ReplyKeyboardMarkup or ReplyKeyboardRemove or ForceReplyOptionalAdditional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user
      +

      sendVideo

      +

      Use this method to send video files, Telegram clients support MPEG4 videos (other formats may be sent as Document). On success, the sent Message is returned. Bots can currently send video files of up to 50 MB in size, this limit may be changed in the future.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      business_connection_idStringOptionalUnique identifier of the business connection on behalf of which the message will be sent
      chat_idInteger or StringYesUnique identifier for the target chat or username of the target bot, supergroup or channel in the format @username
      message_thread_idIntegerOptionalUnique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only
      direct_messages_topic_idIntegerOptionalIdentifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat
      videoInputFile or StringYesVideo to send. Pass a file_id as String to send a video that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a video from the Internet, or upload a new video using multipart/form-data. More information on Sending Files »
      durationIntegerOptionalDuration of sent video in seconds
      widthIntegerOptionalVideo width
      heightIntegerOptionalVideo height
      thumbnailInputFile or StringOptionalThumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://<file_attach_name>” if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files »
      coverInputFile or StringOptionalCover for the video in the message. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet, or pass “attach://<file_attach_name>” to upload a new one using multipart/form-data under <file_attach_name> name. More information on Sending Files »
      start_timestampIntegerOptionalStart timestamp for the video in the message
      captionStringOptionalVideo caption (may also be used when resending videos by file_id), 0-1024 characters after entities parsing
      parse_modeStringOptionalMode for parsing entities in the video caption. See formatting options for more details.
      caption_entitiesArray of MessageEntityOptionalA JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode
      show_caption_above_mediaBooleanOptionalPass True, if the caption must be shown above the message media
      has_spoilerBooleanOptionalPass True if the video needs to be covered with a spoiler animation
      supports_streamingBooleanOptionalPass True if the uploaded video is suitable for streaming
      disable_notificationBooleanOptionalSends the message silently. Users will receive a notification with no sound.
      protect_contentBooleanOptionalProtects the contents of the sent message from forwarding and saving
      allow_paid_broadcastBooleanOptionalPass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance.
      message_effect_idStringOptionalUnique identifier of the message effect to be added to the message; for private chats only
      suggested_post_parametersSuggestedPostParametersOptionalA JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined.
      reply_parametersReplyParametersOptionalDescription of the message to reply to
      reply_markupInlineKeyboardMarkup or ReplyKeyboardMarkup or ReplyKeyboardRemove or ForceReplyOptionalAdditional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user
      +

      sendAnimation

      +

      Use this method to send animation files (GIF or H.264/MPEG-4 AVC video without sound). On success, the sent Message is returned. Bots can currently send animation files of up to 50 MB in size, this limit may be changed in the future.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      business_connection_idStringOptionalUnique identifier of the business connection on behalf of which the message will be sent
      chat_idInteger or StringYesUnique identifier for the target chat or username of the target bot, supergroup or channel in the format @username
      message_thread_idIntegerOptionalUnique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only
      direct_messages_topic_idIntegerOptionalIdentifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat
      animationInputFile or StringYesAnimation to send. Pass a file_id as String to send an animation that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an animation from the Internet, or upload a new animation using multipart/form-data. More information on Sending Files »
      durationIntegerOptionalDuration of sent animation in seconds
      widthIntegerOptionalAnimation width
      heightIntegerOptionalAnimation height
      thumbnailInputFile or StringOptionalThumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://<file_attach_name>” if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files »
      captionStringOptionalAnimation caption (may also be used when resending animation by file_id), 0-1024 characters after entities parsing
      parse_modeStringOptionalMode for parsing entities in the animation caption. See formatting options for more details.
      caption_entitiesArray of MessageEntityOptionalA JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode
      show_caption_above_mediaBooleanOptionalPass True, if the caption must be shown above the message media
      has_spoilerBooleanOptionalPass True if the animation needs to be covered with a spoiler animation
      disable_notificationBooleanOptionalSends the message silently. Users will receive a notification with no sound.
      protect_contentBooleanOptionalProtects the contents of the sent message from forwarding and saving
      allow_paid_broadcastBooleanOptionalPass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance.
      message_effect_idStringOptionalUnique identifier of the message effect to be added to the message; for private chats only
      suggested_post_parametersSuggestedPostParametersOptionalA JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined.
      reply_parametersReplyParametersOptionalDescription of the message to reply to
      reply_markupInlineKeyboardMarkup or ReplyKeyboardMarkup or ReplyKeyboardRemove or ForceReplyOptionalAdditional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user
      +

      sendVoice

      +

      Use this method to send audio files, if you want Telegram clients to display the file as a playable voice message. For this to work, your audio must be in an .OGG file encoded with OPUS, or in .MP3 format, or in .M4A format (other formats may be sent as Audio or Document). On success, the sent Message is returned. Bots can currently send voice messages of up to 50 MB in size, this limit may be changed in the future.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      business_connection_idStringOptionalUnique identifier of the business connection on behalf of which the message will be sent
      chat_idInteger or StringYesUnique identifier for the target chat or username of the target bot, supergroup or channel in the format @username
      message_thread_idIntegerOptionalUnique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only
      direct_messages_topic_idIntegerOptionalIdentifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat
      voiceInputFile or StringYesAudio file to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files »
      captionStringOptionalVoice message caption, 0-1024 characters after entities parsing
      parse_modeStringOptionalMode for parsing entities in the voice message caption. See formatting options for more details.
      caption_entitiesArray of MessageEntityOptionalA JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode
      durationIntegerOptionalDuration of the voice message in seconds
      disable_notificationBooleanOptionalSends the message silently. Users will receive a notification with no sound.
      protect_contentBooleanOptionalProtects the contents of the sent message from forwarding and saving
      allow_paid_broadcastBooleanOptionalPass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance.
      message_effect_idStringOptionalUnique identifier of the message effect to be added to the message; for private chats only
      suggested_post_parametersSuggestedPostParametersOptionalA JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined.
      reply_parametersReplyParametersOptionalDescription of the message to reply to
      reply_markupInlineKeyboardMarkup or ReplyKeyboardMarkup or ReplyKeyboardRemove or ForceReplyOptionalAdditional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user
      +

      sendVideoNote

      +

      As of v.4.0, Telegram clients support rounded square MPEG4 videos of up to 1 minute long. Use this method to send video messages. On success, the sent Message is returned.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      business_connection_idStringOptionalUnique identifier of the business connection on behalf of which the message will be sent
      chat_idInteger or StringYesUnique identifier for the target chat or username of the target bot, supergroup or channel in the format @username
      message_thread_idIntegerOptionalUnique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only
      direct_messages_topic_idIntegerOptionalIdentifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat
      video_noteInputFile or StringYesVideo note to send. Pass a file_id as String to send a video note that exists on the Telegram servers (recommended) or upload a new video using multipart/form-data. More information on Sending Files ». Sending video notes by a URL is currently unsupported
      durationIntegerOptionalDuration of sent video in seconds
      lengthIntegerOptionalVideo width and height, i.e. diameter of the video message
      thumbnailInputFile or StringOptionalThumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://<file_attach_name>” if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files »
      disable_notificationBooleanOptionalSends the message silently. Users will receive a notification with no sound.
      protect_contentBooleanOptionalProtects the contents of the sent message from forwarding and saving
      allow_paid_broadcastBooleanOptionalPass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance.
      message_effect_idStringOptionalUnique identifier of the message effect to be added to the message; for private chats only
      suggested_post_parametersSuggestedPostParametersOptionalA JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined.
      reply_parametersReplyParametersOptionalDescription of the message to reply to
      reply_markupInlineKeyboardMarkup or ReplyKeyboardMarkup or ReplyKeyboardRemove or ForceReplyOptionalAdditional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user
      +

      sendPaidMedia

      +

      Use this method to send paid media. On success, the sent Message is returned.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      business_connection_idStringOptionalUnique identifier of the business connection on behalf of which the message will be sent
      chat_idInteger or StringYesUnique identifier for the target chat or username of the target bot, supergroup or channel in the format @username. If the chat is a channel, all Telegram Star proceeds from this media will be credited to the chat's balance. Otherwise, they will be credited to the bot's balance.
      message_thread_idIntegerOptionalUnique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only
      direct_messages_topic_idIntegerOptionalIdentifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat
      star_countIntegerYesThe number of Telegram Stars that must be paid to buy access to the media; 1-25000
      mediaArray of InputPaidMediaYesA JSON-serialized array describing the media to be sent; up to 10 items
      payloadStringOptionalBot-defined paid media payload, 0-128 bytes. This will not be displayed to the user, use it for your internal processes.
      captionStringOptionalMedia caption, 0-1024 characters after entities parsing
      parse_modeStringOptionalMode for parsing entities in the media caption. See formatting options for more details.
      caption_entitiesArray of MessageEntityOptionalA JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode
      show_caption_above_mediaBooleanOptionalPass True, if the caption must be shown above the message media
      disable_notificationBooleanOptionalSends the message silently. Users will receive a notification with no sound.
      protect_contentBooleanOptionalProtects the contents of the sent message from forwarding and saving
      allow_paid_broadcastBooleanOptionalPass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance.
      suggested_post_parametersSuggestedPostParametersOptionalA JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined.
      reply_parametersReplyParametersOptionalDescription of the message to reply to
      reply_markupInlineKeyboardMarkup or ReplyKeyboardMarkup or ReplyKeyboardRemove or ForceReplyOptionalAdditional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user
      +

      sendMediaGroup

      +

      Use this method to send a group of photos, live photos, videos, documents or audios as an album. Documents and audio files can be only grouped in an album with messages of the same type. On success, an array of Message objects that were sent is returned.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      business_connection_idStringOptionalUnique identifier of the business connection on behalf of which the message will be sent
      chat_idInteger or StringYesUnique identifier for the target chat or username of the target bot, supergroup or channel in the format @username
      message_thread_idIntegerOptionalUnique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only
      direct_messages_topic_idIntegerOptionalIdentifier of the direct messages topic to which the messages will be sent; required if the messages are sent to a direct messages chat
      mediaArray of InputMediaAudio, InputMediaDocument, InputMediaLivePhoto, InputMediaPhoto and InputMediaVideoYesA JSON-serialized array describing messages to be sent, must include 2-10 items
      disable_notificationBooleanOptionalSends messages silently. Users will receive a notification with no sound.
      protect_contentBooleanOptionalProtects the contents of the sent messages from forwarding and saving
      allow_paid_broadcastBooleanOptionalPass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance.
      message_effect_idStringOptionalUnique identifier of the message effect to be added to the message; for private chats only
      reply_parametersReplyParametersOptionalDescription of the message to reply to
      +

      sendLocation

      +

      Use this method to send point on the map. On success, the sent Message is returned.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      business_connection_idStringOptionalUnique identifier of the business connection on behalf of which the message will be sent
      chat_idInteger or StringYesUnique identifier for the target chat or username of the target bot, supergroup or channel in the format @username
      message_thread_idIntegerOptionalUnique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only
      direct_messages_topic_idIntegerOptionalIdentifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat
      latitudeFloatYesLatitude of the location
      longitudeFloatYesLongitude of the location
      horizontal_accuracyFloatOptionalThe radius of uncertainty for the location, measured in meters; 0-1500
      live_periodIntegerOptionalPeriod in seconds during which the location will be updated (see Live Locations, should be between 60 and 86400, or 0x7FFFFFFF for live locations that can be edited indefinitely.
      headingIntegerOptionalFor live locations, a direction in which the user is moving, in degrees. Must be between 1 and 360 if specified.
      proximity_alert_radiusIntegerOptionalFor live locations, a maximum distance for proximity alerts about approaching another chat member, in meters. Must be between 1 and 100000 if specified.
      disable_notificationBooleanOptionalSends the message silently. Users will receive a notification with no sound.
      protect_contentBooleanOptionalProtects the contents of the sent message from forwarding and saving
      allow_paid_broadcastBooleanOptionalPass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance.
      message_effect_idStringOptionalUnique identifier of the message effect to be added to the message; for private chats only
      suggested_post_parametersSuggestedPostParametersOptionalA JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined.
      reply_parametersReplyParametersOptionalDescription of the message to reply to
      reply_markupInlineKeyboardMarkup or ReplyKeyboardMarkup or ReplyKeyboardRemove or ForceReplyOptionalAdditional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user
      +

      sendVenue

      +

      Use this method to send information about a venue. On success, the sent Message is returned.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      business_connection_idStringOptionalUnique identifier of the business connection on behalf of which the message will be sent
      chat_idInteger or StringYesUnique identifier for the target chat or username of the target bot, supergroup or channel in the format @username
      message_thread_idIntegerOptionalUnique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only
      direct_messages_topic_idIntegerOptionalIdentifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat
      latitudeFloatYesLatitude of the venue
      longitudeFloatYesLongitude of the venue
      titleStringYesName of the venue
      addressStringYesAddress of the venue
      foursquare_idStringOptionalFoursquare identifier of the venue
      foursquare_typeStringOptionalFoursquare type of the venue, if known. (For example, “arts_entertainment/default”, “arts_entertainment/aquarium” or “food/icecream”.)
      google_place_idStringOptionalGoogle Places identifier of the venue
      google_place_typeStringOptionalGoogle Places type of the venue. (See supported types.)
      disable_notificationBooleanOptionalSends the message silently. Users will receive a notification with no sound.
      protect_contentBooleanOptionalProtects the contents of the sent message from forwarding and saving
      allow_paid_broadcastBooleanOptionalPass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance.
      message_effect_idStringOptionalUnique identifier of the message effect to be added to the message; for private chats only
      suggested_post_parametersSuggestedPostParametersOptionalA JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined.
      reply_parametersReplyParametersOptionalDescription of the message to reply to
      reply_markupInlineKeyboardMarkup or ReplyKeyboardMarkup or ReplyKeyboardRemove or ForceReplyOptionalAdditional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user
      +

      sendContact

      +

      Use this method to send phone contacts. On success, the sent Message is returned.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      business_connection_idStringOptionalUnique identifier of the business connection on behalf of which the message will be sent
      chat_idInteger or StringYesUnique identifier for the target chat or username of the target bot, supergroup or channel in the format @username
      message_thread_idIntegerOptionalUnique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only
      direct_messages_topic_idIntegerOptionalIdentifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat
      phone_numberStringYesContact's phone number
      first_nameStringYesContact's first name
      last_nameStringOptionalContact's last name
      vcardStringOptionalAdditional data about the contact in the form of a vCard, 0-2048 bytes
      disable_notificationBooleanOptionalSends the message silently. Users will receive a notification with no sound.
      protect_contentBooleanOptionalProtects the contents of the sent message from forwarding and saving
      allow_paid_broadcastBooleanOptionalPass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance.
      message_effect_idStringOptionalUnique identifier of the message effect to be added to the message; for private chats only
      suggested_post_parametersSuggestedPostParametersOptionalA JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined.
      reply_parametersReplyParametersOptionalDescription of the message to reply to
      reply_markupInlineKeyboardMarkup or ReplyKeyboardMarkup or ReplyKeyboardRemove or ForceReplyOptionalAdditional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user
      +

      sendPoll

      +

      Use this method to send a native poll. On success, the sent Message is returned.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      business_connection_idStringOptionalUnique identifier of the business connection on behalf of which the message will be sent
      chat_idInteger or StringYesUnique identifier for the target chat or username of the target bot, supergroup or channel in the format @username. Polls can't be sent to channel direct messages chats.
      message_thread_idIntegerOptionalUnique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only
      questionStringYesPoll question, 1-300 characters
      question_parse_modeStringOptionalMode for parsing entities in the question. See formatting options for more details. Currently, only custom emoji entities are allowed
      question_entitiesArray of MessageEntityOptionalA JSON-serialized list of special entities that appear in the poll question. It can be specified instead of question_parse_mode
      optionsArray of InputPollOptionYesA JSON-serialized list of 1-12 answer options
      is_anonymousBooleanOptionalTrue, if the poll needs to be anonymous, defaults to True
      typeStringOptionalPoll type, “quiz” or “regular”, defaults to “regular”
      allows_multiple_answersBooleanOptionalPass True, if the poll allows multiple answers, defaults to False
      allows_revotingBooleanOptionalPass True, if the poll allows to change chosen answer options, defaults to False for quizzes and to True for regular polls
      shuffle_optionsBooleanOptionalPass True, if the poll options must be shown in random order
      allow_adding_optionsBooleanOptionalPass True, if answer options can be added to the poll after creation; not supported for anonymous polls and quizzes
      hide_results_until_closesBooleanOptionalPass True, if poll results must be shown only after the poll closes
      members_onlyBooleanOptionalPass True, if voting is limited to users who have been members of the chat where the poll is being sent for more than 24 hours; for channel chats only
      country_codesArray of StringOptionalA JSON-serialized list of 0-12 two-letter ISO 3166-1 alpha-2 country codes indicating the countries from which users can vote in the poll; for channel chats only. If omitted or empty, then users from any country can participate in the poll.
      correct_option_idsArray of IntegerOptionalA JSON-serialized list of monotonically increasing 0-based identifiers of the correct answer options, required for polls in quiz mode
      explanationStringOptionalText that is shown when a user chooses an incorrect answer or taps on the lamp icon in a quiz-style poll, 0-200 characters with at most 2 line feeds after entities parsing
      explanation_parse_modeStringOptionalMode for parsing entities in the explanation. See formatting options for more details.
      explanation_entitiesArray of MessageEntityOptionalA JSON-serialized list of special entities that appear in the poll explanation. It can be specified instead of explanation_parse_mode
      explanation_mediaInputPollMediaOptionalMedia added to the quiz explanation
      open_periodIntegerOptionalAmount of time in seconds the poll will be active after creation, 5-2628000. Can't be used together with close_date.
      close_dateIntegerOptionalPoint in time (Unix timestamp) when the poll will be automatically closed. Must be at least 5 and no more than 2628000 seconds in the future. Can't be used together with open_period.
      is_closedBooleanOptionalPass True if the poll needs to be immediately closed. This can be useful for poll preview.
      descriptionStringOptionalDescription of the poll to be sent, 0-1024 characters after entities parsing
      description_parse_modeStringOptionalMode for parsing entities in the poll description. See formatting options for more details.
      description_entitiesArray of MessageEntityOptionalA JSON-serialized list of special entities that appear in the poll description, which can be specified instead of description_parse_mode
      mediaInputPollMediaOptionalMedia added to the poll description
      disable_notificationBooleanOptionalSends the message silently. Users will receive a notification with no sound.
      protect_contentBooleanOptionalProtects the contents of the sent message from forwarding and saving
      allow_paid_broadcastBooleanOptionalPass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance.
      message_effect_idStringOptionalUnique identifier of the message effect to be added to the message; for private chats only
      reply_parametersReplyParametersOptionalDescription of the message to reply to
      reply_markupInlineKeyboardMarkup or ReplyKeyboardMarkup or ReplyKeyboardRemove or ForceReplyOptionalAdditional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user
      +

      sendChecklist

      +

      Use this method to send a checklist on behalf of a connected business account. On success, the sent Message is returned.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      business_connection_idStringYesUnique identifier of the business connection on behalf of which the message will be sent
      chat_idInteger or StringYesUnique identifier for the target chat or username of the target bot in the format @username
      checklistInputChecklistYesA JSON-serialized object for the checklist to send
      disable_notificationBooleanOptionalSends the message silently. Users will receive a notification with no sound.
      protect_contentBooleanOptionalProtects the contents of the sent message from forwarding and saving
      message_effect_idStringOptionalUnique identifier of the message effect to be added to the message
      reply_parametersReplyParametersOptionalA JSON-serialized object for description of the message to reply to
      reply_markupInlineKeyboardMarkupOptionalA JSON-serialized object for an inline keyboard
      +

      sendDice

      +

      Use this method to send an animated emoji that will display a random value. On success, the sent Message is returned.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      business_connection_idStringOptionalUnique identifier of the business connection on behalf of which the message will be sent
      chat_idInteger or StringYesUnique identifier for the target chat or username of the target bot, supergroup or channel in the format @username
      message_thread_idIntegerOptionalUnique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only
      direct_messages_topic_idIntegerOptionalIdentifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat
      emojiStringOptionalEmoji on which the dice throw animation is based. Currently, must be one of “🎲”, “🎯”, “🏀”, “⚽”, “🎳”, or “🎰”. Dice can have values 1-6 for “🎲”, “🎯” and “🎳”, values 1-5 for “🏀” and “⚽”, and values 1-64 for “🎰”. Defaults to “🎲
      disable_notificationBooleanOptionalSends the message silently. Users will receive a notification with no sound.
      protect_contentBooleanOptionalProtects the contents of the sent message from forwarding
      allow_paid_broadcastBooleanOptionalPass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance.
      message_effect_idStringOptionalUnique identifier of the message effect to be added to the message; for private chats only
      suggested_post_parametersSuggestedPostParametersOptionalA JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined.
      reply_parametersReplyParametersOptionalDescription of the message to reply to
      reply_markupInlineKeyboardMarkup or ReplyKeyboardMarkup or ReplyKeyboardRemove or ForceReplyOptionalAdditional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user
      +

      sendMessageDraft

      +

      Use this method to stream a partial message to a user while the message is being generated. Note that the streamed draft is ephemeral and acts as a temporary 30-second preview - once the output is finalized, you must call sendMessage with the complete message to persist it in the user's chat. Returns True on success.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      chat_idIntegerYesUnique identifier for the target private chat
      message_thread_idIntegerOptionalUnique identifier for the target message thread
      draft_idIntegerYesUnique identifier of the message draft; must be non-zero. Changes of drafts with the same identifier are animated.
      textStringOptionalText of the message to be sent, 0-4096 characters after entities parsing. Pass an empty text to show a “Thinking…” placeholder.
      parse_modeStringOptionalMode for parsing entities in the message text. See formatting options for more details.
      entitiesArray of MessageEntityOptionalA JSON-serialized list of special entities that appear in message text, which can be specified instead of parse_mode
      +

      sendChatAction

      +

      Use this method when you need to tell the user that something is happening on the bot's side. The status is set for 5 seconds or less (when a message arrives from your bot, Telegram clients clear its typing status). Returns True on success.

      +
      +

      Example: The ImageBot needs some time to process a request and upload the image. Instead of sending a text message along the lines of “Retrieving image, please wait…”, the bot may use sendChatAction with action = upload_photo. The user will see a “sending photo” status for the bot.

      +
      +

      We only recommend using this method when a response from the bot will take a noticeable amount of time to arrive.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      business_connection_idStringOptionalUnique identifier of the business connection on behalf of which the action will be sent
      chat_idInteger or StringYesUnique identifier for the target chat or username of the target bot, supergroup or channel in the format @username. Channel chats and channel direct messages chats aren't supported.
      message_thread_idIntegerOptionalUnique identifier for the target message thread or topic of a forum; for supergroups and private chats of bots with forum topic mode enabled only
      actionStringYesType of action to broadcast. Choose one, depending on what the user is about to receive: typing for text messages, upload_photo for photos, record_video or upload_video for videos, record_voice or upload_voice for voice notes, upload_document for general files, choose_sticker for stickers, find_location for location data, record_video_note or upload_video_note for video notes.
      +

      setMessageReaction

      +

      Use this method to change the chosen reactions on a message. Service messages of some types can't be reacted to. Automatically forwarded messages from a channel to its discussion group have the same available reactions as messages in the channel. Bots can't use paid reactions. Returns True on success.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      chat_idInteger or StringYesUnique identifier for the target chat or username of the target bot, supergroup or channel in the format @username
      message_idIntegerYesIdentifier of the target message. If the message belongs to a media group, the reaction is set to the first non-deleted message in the group instead.
      reactionArray of ReactionTypeOptionalA JSON-serialized list of reaction types to set on the message. Currently, as non-premium users, bots can set up to one reaction per message. A custom emoji reaction can be used if it is either already present on the message or explicitly allowed by chat administrators. Paid reactions can't be used by bots.
      is_bigBooleanOptionalPass True to set the reaction with a big animation
      +

      getUserProfilePhotos

      +

      Use this method to get a list of profile pictures for a user. Returns a UserProfilePhotos object.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      user_idIntegerYesUnique identifier of the target user
      offsetIntegerOptionalSequential number of the first photo to be returned. By default, all photos are returned.
      limitIntegerOptionalLimits the number of photos to be retrieved. Values between 1-100 are accepted. Defaults to 100.
      +

      getUserProfileAudios

      +

      Use this method to get a list of profile audios for a user. Returns a UserProfileAudios object.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      user_idIntegerYesUnique identifier of the target user
      offsetIntegerOptionalSequential number of the first audio to be returned. By default, all audios are returned.
      limitIntegerOptionalLimits the number of audios to be retrieved. Values between 1-100 are accepted. Defaults to 100.
      +

      setUserEmojiStatus

      +

      Changes the emoji status for a given user that previously allowed the bot to manage their emoji status via the Mini App method requestEmojiStatusAccess. Returns True on success.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      user_idIntegerYesUnique identifier of the target user
      emoji_status_custom_emoji_idStringOptionalCustom emoji identifier of the emoji status to set. Pass an empty string to remove the status.
      emoji_status_expiration_dateIntegerOptionalExpiration date of the emoji status, if any
      +

      getFile

      +

      Use this method to get basic information about a file and prepare it for downloading. For the moment, bots can download files of up to 20MB in size. On success, a File object is returned. The file can then be downloaded via the link https://api.telegram.org/file/bot<token>/<file_path>, where <file_path> is taken from the response. It is guaranteed that the link will be valid for at least 1 hour. When the link expires, a new one can be requested by calling getFile again.

      + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      file_idStringYesFile identifier to get information about
      +

      Note: This function may not preserve the original file name and MIME type. You should save the file's MIME type and name (if available) when the File object is received.

      +

      banChatMember

      +

      Use this method to ban a user in a group, a supergroup or a channel. In the case of supergroups and channels, the user will not be able to return to the chat on their own using invite links, etc., unless unbanned first. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns True on success.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      chat_idInteger or StringYesUnique identifier for the target group or username of the target supergroup or channel in the format @username
      user_idIntegerYesUnique identifier of the target user
      until_dateIntegerOptionalDate when the user will be unbanned; Unix time. If user is banned for more than 366 days or less than 30 seconds from the current time they are considered to be banned forever. Applied for supergroups and channels only.
      revoke_messagesBooleanOptionalPass True to delete all messages from the chat for the user that is being removed. If False, the user will be able to see messages in the group that were sent before the user was removed. Always True for supergroups and channels.
      +

      unbanChatMember

      +

      Use this method to unban a previously banned user in a supergroup or channel. The user will not return to the group or channel automatically, but will be able to join via link, etc. The bot must be an administrator for this to work. By default, this method guarantees that after the call the user is not a member of the chat, but will be able to join it. So if the user is a member of the chat they will also be removed from the chat. If you don't want this, use the parameter only_if_banned. Returns True on success.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      chat_idInteger or StringYesUnique identifier for the target group or username of the target supergroup or channel in the format @username
      user_idIntegerYesUnique identifier of the target user
      only_if_bannedBooleanOptionalDo nothing if the user is not banned
      +

      restrictChatMember

      +

      Use this method to restrict a user in a supergroup. The bot must be an administrator in the supergroup for this to work and must have the appropriate administrator rights. Pass True for all permissions to lift restrictions from a user. Returns True on success.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      chat_idInteger or StringYesUnique identifier for the target chat or username of the target supergroup in the format @username
      user_idIntegerYesUnique identifier of the target user
      permissionsChatPermissionsYesA JSON-serialized object for new user permissions
      use_independent_chat_permissionsBooleanOptionalPass True if chat permissions are set independently. Otherwise, the can_send_other_messages and can_add_web_page_previews permissions will imply the can_send_messages, can_send_audios, can_send_documents, can_send_photos, can_send_videos, can_send_video_notes, and can_send_voice_notes permissions; the can_send_polls permission will imply the can_send_messages permission.
      until_dateIntegerOptionalDate when restrictions will be lifted for the user; Unix time. If user is restricted for more than 366 days or less than 30 seconds from the current time, they are considered to be restricted forever
      +

      promoteChatMember

      +

      Use this method to promote or demote a user in a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Pass False for all boolean parameters to demote a user. Returns True on success.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      chat_idInteger or StringYesUnique identifier for the target chat or username of the target channel in the format @username
      user_idIntegerYesUnique identifier of the target user
      is_anonymousBooleanOptionalPass True if the administrator's presence in the chat is hidden
      can_manage_chatBooleanOptionalPass True if the administrator can access the chat event log, get boost list, see hidden supergroup and channel members, report spam messages, ignore slow mode, and send messages to the chat without paying Telegram Stars. Implied by any other administrator privilege.
      can_delete_messagesBooleanOptionalPass True if the administrator can delete messages of other users
      can_manage_video_chatsBooleanOptionalPass True if the administrator can manage video chats
      can_restrict_membersBooleanOptionalPass True if the administrator can restrict, ban or unban chat members, or access supergroup statistics. For backward compatibility, defaults to True for promotions of channel administrators
      can_promote_membersBooleanOptionalPass True if the administrator can add new administrators with a subset of their own privileges or demote administrators that they have promoted, directly or indirectly (promoted by administrators that were appointed by him)
      can_change_infoBooleanOptionalPass True if the administrator can change chat title, photo and other settings
      can_invite_usersBooleanOptionalPass True if the administrator can invite new users to the chat
      can_post_storiesBooleanOptionalPass True if the administrator can post stories to the chat
      can_edit_storiesBooleanOptionalPass True if the administrator can edit stories posted by other users, post stories to the chat page, pin chat stories, and access the chat's story archive
      can_delete_storiesBooleanOptionalPass True if the administrator can delete stories posted by other users
      can_post_messagesBooleanOptionalPass True if the administrator can post messages in the channel, approve suggested posts, or access channel statistics; for channels only
      can_edit_messagesBooleanOptionalPass True if the administrator can edit messages of other users and can pin messages; for channels only
      can_pin_messagesBooleanOptionalPass True if the administrator can pin messages; for supergroups only
      can_manage_topicsBooleanOptionalPass True if the user is allowed to create, rename, close, and reopen forum topics; for supergroups only
      can_manage_direct_messagesBooleanOptionalPass True if the administrator can manage direct messages within the channel and decline suggested posts; for channels only
      can_manage_tagsBooleanOptionalPass True if the administrator can edit the tags of regular members; for groups and supergroups only
      +

      setChatAdministratorCustomTitle

      +

      Use this method to set a custom title for an administrator in a supergroup promoted by the bot. Returns True on success.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      chat_idInteger or StringYesUnique identifier for the target chat or username of the target supergroup in the format @username
      user_idIntegerYesUnique identifier of the target user
      custom_titleStringYesNew custom title for the administrator; 0-16 characters, emoji are not allowed
      +

      setChatMemberTag

      +

      Use this method to set a tag for a regular member in a group or a supergroup. The bot must be an administrator in the chat for this to work and must have the can_manage_tags administrator right. Returns True on success.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      chat_idInteger or StringYesUnique identifier for the target chat or username of the target supergroup in the format @username
      user_idIntegerYesUnique identifier of the target user
      tagStringOptionalNew tag for the member; 0-16 characters, emoji are not allowed
      +

      banChatSenderChat

      +

      Use this method to ban a channel chat in a supergroup or a channel. Until the chat is unbanned, the owner of the banned chat won't be able to send messages on behalf of any of their channels. The bot must be an administrator in the supergroup or channel for this to work and must have the appropriate administrator rights. Returns True on success.

      + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      chat_idInteger or StringYesUnique identifier for the target chat or username of the target channel in the format @username
      sender_chat_idIntegerYesUnique identifier of the target sender chat
      +

      unbanChatSenderChat

      +

      Use this method to unban a previously banned channel chat in a supergroup or channel. The bot must be an administrator for this to work and must have the appropriate administrator rights. Returns True on success.

      + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      chat_idInteger or StringYesUnique identifier for the target chat or username of the target channel in the format @username
      sender_chat_idIntegerYesUnique identifier of the target sender chat
      +

      setChatPermissions

      +

      Use this method to set default chat permissions for all members. The bot must be an administrator in the group or a supergroup for this to work and must have the can_restrict_members administrator rights. Returns True on success.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      chat_idInteger or StringYesUnique identifier for the target chat or username of the target supergroup in the format @username
      permissionsChatPermissionsYesA JSON-serialized object for new default chat permissions
      use_independent_chat_permissionsBooleanOptionalPass True if chat permissions are set independently. Otherwise, the can_send_other_messages and can_add_web_page_previews permissions will imply the can_send_messages, can_send_audios, can_send_documents, can_send_photos, can_send_videos, can_send_video_notes, and can_send_voice_notes permissions; the can_send_polls permission will imply the can_send_messages permission.
      +

      exportChatInviteLink

      +

      Use this method to generate a new primary invite link for a chat; any previously generated primary link is revoked. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns the new invite link as String on success.

      + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      chat_idInteger or StringYesUnique identifier for the target chat or username of the target channel in the format @username
      +
      +

      Note: Each administrator in a chat generates their own invite links. Bots can't use invite links generated by other administrators. If you want your bot to work with invite links, it will need to generate its own link using exportChatInviteLink or by calling the getChat method. If your bot needs to generate a new primary invite link replacing its previous one, use exportChatInviteLink again.

      +
      +

      createChatInviteLink

      +

      Use this method to create an additional invite link for a chat. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. The link can be revoked using the method revokeChatInviteLink. Returns the new invite link as ChatInviteLink object.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      chat_idInteger or StringYesUnique identifier for the target chat or username of the target channel in the format @username
      nameStringOptionalInvite link name; 0-32 characters
      expire_dateIntegerOptionalPoint in time (Unix timestamp) when the link will expire
      member_limitIntegerOptionalThe maximum number of users that can be members of the chat simultaneously after joining the chat via this invite link; 1-99999
      creates_join_requestBooleanOptionalTrue, if users joining the chat via the link need to be approved by chat administrators. If True, member_limit can't be specified
      +

      editChatInviteLink

      +

      Use this method to edit a non-primary invite link created by the bot. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns the edited invite link as a ChatInviteLink object.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      chat_idInteger or StringYesUnique identifier for the target chat or username of the target channel in the format @username
      invite_linkStringYesThe invite link to edit
      nameStringOptionalInvite link name; 0-32 characters
      expire_dateIntegerOptionalPoint in time (Unix timestamp) when the link will expire
      member_limitIntegerOptionalThe maximum number of users that can be members of the chat simultaneously after joining the chat via this invite link; 1-99999
      creates_join_requestBooleanOptionalTrue, if users joining the chat via the link need to be approved by chat administrators. If True, member_limit can't be specified
      +

      createChatSubscriptionInviteLink

      +

      Use this method to create a subscription invite link for a channel chat. The bot must have the can_invite_users administrator rights. The link can be edited using the method editChatSubscriptionInviteLink or revoked using the method revokeChatInviteLink. Returns the new invite link as a ChatInviteLink object.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      chat_idInteger or StringYesUnique identifier for the target channel chat or username of the target channel in the format @username
      nameStringOptionalInvite link name; 0-32 characters
      subscription_periodIntegerYesThe number of seconds the subscription will be active for before the next payment. Currently, it must always be 2592000 (30 days).
      subscription_priceIntegerYesThe amount of Telegram Stars a user must pay initially and after each subsequent subscription period to be a member of the chat; 1-10000
      +

      editChatSubscriptionInviteLink

      +

      Use this method to edit a subscription invite link created by the bot. The bot must have the can_invite_users administrator rights. Returns the edited invite link as a ChatInviteLink object.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      chat_idInteger or StringYesUnique identifier for the target chat or username of the target channel in the format @username
      invite_linkStringYesThe invite link to edit
      nameStringOptionalInvite link name; 0-32 characters
      +

      revokeChatInviteLink

      +

      Use this method to revoke an invite link created by the bot. If the primary link is revoked, a new link is automatically generated. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns the revoked invite link as ChatInviteLink object.

      + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      chat_idInteger or StringYesUnique identifier of the target chat or username of the target channel in the format @username
      invite_linkStringYesThe invite link to revoke
      +

      approveChatJoinRequest

      +

      Use this method to approve a chat join request. The bot must be an administrator in the chat for this to work and must have the can_invite_users administrator right. Returns True on success.

      + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      chat_idInteger or StringYesUnique identifier for the target chat or username of the target channel in the format @username
      user_idIntegerYesUnique identifier of the target user
      +

      declineChatJoinRequest

      +

      Use this method to decline a chat join request. The bot must be an administrator in the chat for this to work and must have the can_invite_users administrator right. Returns True on success.

      + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      chat_idInteger or StringYesUnique identifier for the target chat or username of the target channel in the format @username
      user_idIntegerYesUnique identifier of the target user
      +

      setChatPhoto

      +

      Use this method to set a new profile photo for the chat. Photos can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns True on success.

      + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      chat_idInteger or StringYesUnique identifier for the target chat or username of the target channel in the format @username
      photoInputFileYesNew chat photo, uploaded using multipart/form-data
      +

      deleteChatPhoto

      +

      Use this method to delete a chat photo. Photos can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns True on success.

      + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      chat_idInteger or StringYesUnique identifier for the target chat or username of the target channel in the format @username
      +

      setChatTitle

      +

      Use this method to change the title of a chat. Titles can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns True on success.

      + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      chat_idInteger or StringYesUnique identifier for the target chat or username of the target channel in the format @username
      titleStringYesNew chat title, 1-128 characters
      +

      setChatDescription

      +

      Use this method to change the description of a group, a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns True on success.

      + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      chat_idInteger or StringYesUnique identifier for the target chat or username of the target channel in the format @username
      descriptionStringOptionalNew chat description, 0-255 characters
      +

      pinChatMessage

      +

      Use this method to add a message to the list of pinned messages in a chat. In private chats and channel direct messages chats, all non-service messages can be pinned. Conversely, the bot must be an administrator with the 'can_pin_messages' right or the 'can_edit_messages' right to pin messages in groups and channels respectively. Returns True on success.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      business_connection_idStringOptionalUnique identifier of the business connection on behalf of which the message will be pinned
      chat_idInteger or StringYesUnique identifier for the target chat or username of the target channel in the format @username
      message_idIntegerYesIdentifier of a message to pin
      disable_notificationBooleanOptionalPass True if it is not necessary to send a notification to all chat members about the new pinned message. Notifications are always disabled in channels and private chats.
      +

      unpinChatMessage

      +

      Use this method to remove a message from the list of pinned messages in a chat. In private chats and channel direct messages chats, all messages can be unpinned. Conversely, the bot must be an administrator with the 'can_pin_messages' right or the 'can_edit_messages' right to unpin messages in groups and channels respectively. Returns True on success.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      business_connection_idStringOptionalUnique identifier of the business connection on behalf of which the message will be unpinned
      chat_idInteger or StringYesUnique identifier for the target chat or username of the target channel in the format @username
      message_idIntegerOptionalIdentifier of the message to unpin. Required if business_connection_id is specified. If not specified, the most recent pinned message (by sending date) will be unpinned.
      +

      unpinAllChatMessages

      +

      Use this method to clear the list of pinned messages in a chat. In private chats and channel direct messages chats, no additional rights are required to unpin all pinned messages. Conversely, the bot must be an administrator with the 'can_pin_messages' right or the 'can_edit_messages' right to unpin all pinned messages in groups and channels respectively. Returns True on success.

      + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      chat_idInteger or StringYesUnique identifier for the target chat or username of the target channel in the format @username
      +

      leaveChat

      +

      Use this method for your bot to leave a group, supergroup or channel. Returns True on success.

      + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      chat_idInteger or StringYesUnique identifier for the target chat or username of the target supergroup or channel in the format @username. Channel direct messages chats aren't supported; leave the corresponding channel instead.
      +

      getChat

      +

      Use this method to get up-to-date information about the chat. Returns a ChatFullInfo object on success.

      + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      chat_idInteger or StringYesUnique identifier for the target chat or username of the target supergroup or channel in the format @username
      +

      getChatAdministrators

      +

      Use this method to get a list of administrators in a chat. Returns an Array of ChatMember objects.

      + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      chat_idInteger or StringYesUnique identifier for the target chat or username of the target supergroup or channel in the format @username
      return_botsBooleanOptionalPass True to additionally receive all bots that are administrators of the chat. By default, bots other than the current bot are omitted.
      +

      getChatMemberCount

      +

      Use this method to get the number of members in a chat. Returns Int on success.

      + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      chat_idInteger or StringYesUnique identifier for the target chat or username of the target supergroup or channel in the format @username
      +

      getChatMember

      +

      Use this method to get information about a member of a chat. The method is only guaranteed to work for other users if the bot is an administrator in the chat. Returns a ChatMember object on success.

      + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      chat_idInteger or StringYesUnique identifier for the target chat or username of the target supergroup or channel in the format @username
      user_idIntegerYesUnique identifier of the target user
      +

      getUserPersonalChatMessages

      +

      Use this method to get the last messages from the personal chat (i.e., the chat currently added to their profile) of a given user. On success, an array of Message objects is returned.

      + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      user_idIntegerYesUnique identifier for the target user
      limitIntegerYesThe maximum number of messages to return; 1-20
      +

      setChatStickerSet

      +

      Use this method to set a new group sticker set for a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Use the field can_set_sticker_set optionally returned in getChat requests to check if the bot can use this method. Returns True on success.

      + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      chat_idInteger or StringYesUnique identifier for the target chat or username of the target supergroup in the format @username
      sticker_set_nameStringYesName of the sticker set to be set as the group sticker set
      +

      deleteChatStickerSet

      +

      Use this method to delete a group sticker set from a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Use the field can_set_sticker_set optionally returned in getChat requests to check if the bot can use this method. Returns True on success.

      + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      chat_idInteger or StringYesUnique identifier for the target chat or username of the target supergroup in the format @username
      +

      getForumTopicIconStickers

      +

      Use this method to get custom emoji stickers, which can be used as a forum topic icon by any user. Requires no parameters. Returns an Array of Sticker objects.

      +

      createForumTopic

      +

      Use this method to create a topic in a forum supergroup chat or a private chat with a user. In the case of a supergroup chat the bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator right. Returns information about the created topic as a ForumTopic object.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      chat_idInteger or StringYesUnique identifier for the target chat or username of the target supergroup in the format @username
      nameStringYesTopic name, 1-128 characters
      icon_colorIntegerOptionalColor of the topic icon in RGB format. Currently, must be one of 7322096 (0x6FB9F0), 16766590 (0xFFD67E), 13338331 (0xCB86DB), 9367192 (0x8EEE98), 16749490 (0xFF93B2), or 16478047 (0xFB6F5F)
      icon_custom_emoji_idStringOptionalUnique identifier of the custom emoji shown as the topic icon. Use getForumTopicIconStickers to get all allowed custom emoji identifiers.
      +

      editForumTopic

      +

      Use this method to edit name and icon of a topic in a forum supergroup chat or a private chat with a user. In the case of a supergroup chat the bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights, unless it is the creator of the topic. Returns True on success.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      chat_idInteger or StringYesUnique identifier for the target chat or username of the target supergroup in the format @username
      message_thread_idIntegerYesUnique identifier for the target message thread of the forum topic
      nameStringOptionalNew topic name, 0-128 characters. If not specified or empty, the current name of the topic will be kept
      icon_custom_emoji_idStringOptionalNew unique identifier of the custom emoji shown as the topic icon. Use getForumTopicIconStickers to get all allowed custom emoji identifiers. Pass an empty string to remove the icon. If not specified, the current icon will be kept
      +

      closeForumTopic

      +

      Use this method to close an open topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights, unless it is the creator of the topic. Returns True on success.

      + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      chat_idInteger or StringYesUnique identifier for the target chat or username of the target supergroup in the format @username
      message_thread_idIntegerYesUnique identifier for the target message thread of the forum topic
      +

      reopenForumTopic

      +

      Use this method to reopen a closed topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights, unless it is the creator of the topic. Returns True on success.

      + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      chat_idInteger or StringYesUnique identifier for the target chat or username of the target supergroup in the format @username
      message_thread_idIntegerYesUnique identifier for the target message thread of the forum topic
      +

      deleteForumTopic

      +

      Use this method to delete a forum topic along with all its messages in a forum supergroup chat or a private chat with a user. In the case of a supergroup chat the bot must be an administrator in the chat for this to work and must have the can_delete_messages administrator rights. Returns True on success.

      + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      chat_idInteger or StringYesUnique identifier for the target chat or username of the target supergroup in the format @username
      message_thread_idIntegerYesUnique identifier for the target message thread of the forum topic
      +

      unpinAllForumTopicMessages

      +

      Use this method to clear the list of pinned messages in a forum topic in a forum supergroup chat or a private chat with a user. In the case of a supergroup chat the bot must be an administrator in the chat for this to work and must have the can_pin_messages administrator right in the supergroup. Returns True on success.

      + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      chat_idInteger or StringYesUnique identifier for the target chat or username of the target supergroup in the format @username
      message_thread_idIntegerYesUnique identifier for the target message thread of the forum topic
      +

      editGeneralForumTopic

      +

      Use this method to edit the name of the 'General' topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights. Returns True on success.

      + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      chat_idInteger or StringYesUnique identifier for the target chat or username of the target supergroup in the format @username
      nameStringYesNew topic name, 1-128 characters
      +

      closeGeneralForumTopic

      +

      Use this method to close an open 'General' topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights. Returns True on success.

      + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      chat_idInteger or StringYesUnique identifier for the target chat or username of the target supergroup in the format @username
      +

      reopenGeneralForumTopic

      +

      Use this method to reopen a closed 'General' topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights. The topic will be automatically unhidden if it was hidden. Returns True on success.

      + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      chat_idInteger or StringYesUnique identifier for the target chat or username of the target supergroup in the format @username
      +

      hideGeneralForumTopic

      +

      Use this method to hide the 'General' topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights. The topic will be automatically closed if it was open. Returns True on success.

      + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      chat_idInteger or StringYesUnique identifier for the target chat or username of the target supergroup in the format @username
      +

      unhideGeneralForumTopic

      +

      Use this method to unhide the 'General' topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights. Returns True on success.

      + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      chat_idInteger or StringYesUnique identifier for the target chat or username of the target supergroup in the format @username
      +

      unpinAllGeneralForumTopicMessages

      +

      Use this method to clear the list of pinned messages in a General forum topic. The bot must be an administrator in the chat for this to work and must have the can_pin_messages administrator right in the supergroup. Returns True on success.

      + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      chat_idInteger or StringYesUnique identifier for the target chat or username of the target supergroup in the format @username
      +

      answerCallbackQuery

      +

      Use this method to send answers to callback queries sent from inline keyboards. The answer will be displayed to the user as a notification at the top of the chat screen or as an alert. On success, True is returned.

      +
      +

      Alternatively, the user can be redirected to the specified Game URL. For this option to work, you must first create a game for your bot via @BotFather and accept the terms. Otherwise, you may use links like t.me/your_bot?start=XXXX that open your bot with a parameter.

      +
      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      callback_query_idStringYesUnique identifier for the query to be answered
      textStringOptionalText of the notification. If not specified, nothing will be shown to the user, 0-200 characters
      show_alertBooleanOptionalIf True, an alert will be shown by the client instead of a notification at the top of the chat screen. Defaults to false.
      urlStringOptionalURL that will be opened by the user's client. If you have created a Game and accepted the conditions via @BotFather, specify the URL that opens your game - note that this will only work if the query comes from a callback_game button.

      Otherwise, you may use links like t.me/your_bot?start=XXXX that open your bot with a parameter.
      cache_timeIntegerOptionalThe maximum amount of time in seconds that the result of the callback query may be cached client-side. Telegram apps will support caching starting in version 3.14. Defaults to 0.
      +

      answerGuestQuery

      +

      Use this method to reply to a received guest message. On success, a SentGuestMessage object is returned.

      + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      guest_query_idStringYesUnique identifier for the query to be answered
      resultInlineQueryResultYesA JSON-serialized object describing the message to be sent
      +

      getUserChatBoosts

      +

      Use this method to get the list of boosts added to a chat by a user. Requires administrator rights in the chat. Returns a UserChatBoosts object.

      + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      chat_idInteger or StringYesUnique identifier for the chat or username of the channel in the format @username
      user_idIntegerYesUnique identifier of the target user
      +

      getBusinessConnection

      +

      Use this method to get information about the connection of the bot with a business account. Returns a BusinessConnection object on success.

      + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      business_connection_idStringYesUnique identifier of the business connection
      +

      getManagedBotToken

      +

      Use this method to get the token of a managed bot. Returns the token as String on success.

      + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      user_idIntegerYesUser identifier of the managed bot whose token will be returned
      +

      replaceManagedBotToken

      +

      Use this method to revoke the current token of a managed bot and generate a new one. Returns the new token as String on success.

      + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      user_idIntegerYesUser identifier of the managed bot whose token will be replaced
      +

      getManagedBotAccessSettings

      +

      Use this method to get the access settings of a managed bot. Returns a BotAccessSettings object on success.

      + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      user_idIntegerYesUser identifier of the managed bot whose access settings will be returned
      +

      setManagedBotAccessSettings

      +

      Use this method to change the access settings of a managed bot. Returns True on success.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      user_idIntegerYesUser identifier of the managed bot whose access settings will be changed
      is_access_restrictedBooleanYesPass True, if only selected users can access the bot. The bot's owner can always access it.
      added_user_idsArray of IntegerOptionalA JSON-serialized list of up to 10 identifiers of users who will have access to the bot in addition to its owner. Ignored if is_access_restricted is false.
      +

      setMyCommands

      +

      Use this method to change the list of the bot's commands. See this manual for more details about bot commands. Returns True on success.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      commandsArray of BotCommandYesA JSON-serialized list of bot commands to be set as the list of the bot's commands. At most 100 commands can be specified.
      scopeBotCommandScopeOptionalA JSON-serialized object, describing scope of users for which the commands are relevant. Defaults to BotCommandScopeDefault.
      language_codeStringOptionalA two-letter ISO 639-1 language code. If empty, commands will be applied to all users from the given scope, for whose language there are no dedicated commands
      +

      deleteMyCommands

      +

      Use this method to delete the list of the bot's commands for the given scope and user language. After deletion, higher level commands will be shown to affected users. Returns True on success.

      + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      scopeBotCommandScopeOptionalA JSON-serialized object, describing scope of users for which the commands are relevant. Defaults to BotCommandScopeDefault.
      language_codeStringOptionalA two-letter ISO 639-1 language code. If empty, commands will be applied to all users from the given scope, for whose language there are no dedicated commands
      +

      getMyCommands

      +

      Use this method to get the current list of the bot's commands for the given scope and user language. Returns an Array of BotCommand objects. If commands aren't set, an empty list is returned.

      + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      scopeBotCommandScopeOptionalA JSON-serialized object, describing scope of users. Defaults to BotCommandScopeDefault.
      language_codeStringOptionalA two-letter ISO 639-1 language code or an empty string
      +

      setMyName

      +

      Use this method to change the bot's name. Returns True on success.

      + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      nameStringOptionalNew bot name; 0-64 characters. Pass an empty string to remove the dedicated name for the given language.
      language_codeStringOptionalA two-letter ISO 639-1 language code. If empty, the name will be shown to all users for whose language there is no dedicated name.
      +

      getMyName

      +

      Use this method to get the current bot name for the given user language. Returns BotName on success.

      + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      language_codeStringOptionalA two-letter ISO 639-1 language code or an empty string
      +

      setMyDescription

      +

      Use this method to change the bot's description, which is shown in the chat with the bot if the chat is empty. Returns True on success.

      + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      descriptionStringOptionalNew bot description; 0-512 characters. Pass an empty string to remove the dedicated description for the given language.
      language_codeStringOptionalA two-letter ISO 639-1 language code. If empty, the description will be applied to all users for whose language there is no dedicated description.
      +

      getMyDescription

      +

      Use this method to get the current bot description for the given user language. Returns BotDescription on success.

      + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      language_codeStringOptionalA two-letter ISO 639-1 language code or an empty string
      +

      setMyShortDescription

      +

      Use this method to change the bot's short description, which is shown on the bot's profile page and is sent together with the link when users share the bot. Returns True on success.

      + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      short_descriptionStringOptionalNew short description for the bot; 0-120 characters. Pass an empty string to remove the dedicated short description for the given language.
      language_codeStringOptionalA two-letter ISO 639-1 language code. If empty, the short description will be applied to all users for whose language there is no dedicated short description.
      +

      getMyShortDescription

      +

      Use this method to get the current bot short description for the given user language. Returns BotShortDescription on success.

      + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      language_codeStringOptionalA two-letter ISO 639-1 language code or an empty string
      +

      setMyProfilePhoto

      +

      Changes the profile photo of the bot. Returns True on success.

      + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      photoInputProfilePhotoYesThe new profile photo to set
      +

      removeMyProfilePhoto

      +

      Removes the profile photo of the bot. Requires no parameters. Returns True on success.

      +

      setChatMenuButton

      +

      Use this method to change the bot's menu button in a private chat, or the default menu button. Returns True on success.

      + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      chat_idIntegerOptionalUnique identifier for the target private chat. If not specified, default bot's menu button will be changed
      menu_buttonMenuButtonOptionalA JSON-serialized object for the bot's new menu button. Defaults to MenuButtonDefault
      +

      getChatMenuButton

      +

      Use this method to get the current value of the bot's menu button in a private chat, or the default menu button. Returns MenuButton on success.

      + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      chat_idIntegerOptionalUnique identifier for the target private chat. If not specified, default bot's menu button will be returned
      +

      setMyDefaultAdministratorRights

      +

      Use this method to change the default administrator rights requested by the bot when it's added as an administrator to groups or channels. These rights will be suggested to users, but they are free to modify the list before adding the bot. Returns True on success.

      + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      rightsChatAdministratorRightsOptionalA JSON-serialized object describing new default administrator rights. If not specified, the default administrator rights will be cleared.
      for_channelsBooleanOptionalPass True to change the default administrator rights of the bot in channels. Otherwise, the default administrator rights of the bot for groups and supergroups will be changed.
      +

      getMyDefaultAdministratorRights

      +

      Use this method to get the current default administrator rights of the bot. Returns ChatAdministratorRights on success.

      + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      for_channelsBooleanOptionalPass True to get default administrator rights of the bot in channels. Otherwise, default administrator rights of the bot for groups and supergroups will be returned.
      +

      getAvailableGifts

      +

      Returns the list of gifts that can be sent by the bot to users and channel chats. Requires no parameters. Returns a Gifts object.

      +

      sendGift

      +

      Sends a gift to the given user or channel chat. The gift can't be converted to Telegram Stars by the receiver. Returns True on success.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      user_idIntegerOptionalRequired if chat_id is not specified. Unique identifier of the target user who will receive the gift.
      chat_idInteger or StringOptionalRequired if user_id is not specified. Unique identifier for the chat or username of the channel (in the format @username) that will receive the gift.
      gift_idStringYesIdentifier of the gift; limited gifts can't be sent to channel chats
      pay_for_upgradeBooleanOptionalPass True to pay for the gift upgrade from the bot's balance, thereby making the upgrade free for the receiver
      textStringOptionalText that will be shown along with the gift; 0-128 characters
      text_parse_modeStringOptionalMode for parsing entities in the text. See formatting options for more details. Entities other than “bold”, “italic”, “underline”, “strikethrough”, “spoiler”, “custom_emoji”, and “date_time” are ignored.
      text_entitiesArray of MessageEntityOptionalA JSON-serialized list of special entities that appear in the gift text. It can be specified instead of text_parse_mode. Entities other than “bold”, “italic”, “underline”, “strikethrough”, “spoiler”, “custom_emoji”, and “date_time” are ignored.
      +

      giftPremiumSubscription

      +

      Gifts a Telegram Premium subscription to the given user. Returns True on success.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      user_idIntegerYesUnique identifier of the target user who will receive a Telegram Premium subscription
      month_countIntegerYesNumber of months the Telegram Premium subscription will be active for the user; must be one of 3, 6, or 12
      star_countIntegerYesNumber of Telegram Stars to pay for the Telegram Premium subscription; must be 1000 for 3 months, 1500 for 6 months, and 2500 for 12 months
      textStringOptionalText that will be shown along with the service message about the subscription; 0-128 characters
      text_parse_modeStringOptionalMode for parsing entities in the text. See formatting options for more details. Entities other than “bold”, “italic”, “underline”, “strikethrough”, “spoiler”, “custom_emoji”, and “date_time” are ignored.
      text_entitiesArray of MessageEntityOptionalA JSON-serialized list of special entities that appear in the gift text. It can be specified instead of text_parse_mode. Entities other than “bold”, “italic”, “underline”, “strikethrough”, “spoiler”, “custom_emoji”, and “date_time” are ignored.
      +

      verifyUser

      +

      Verifies a user on behalf of the organization which is represented by the bot. Returns True on success.

      + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      user_idIntegerYesUnique identifier of the target user
      custom_descriptionStringOptionalCustom description for the verification; 0-70 characters. Must be empty if the organization isn't allowed to provide a custom verification description.
      +

      verifyChat

      +

      Verifies a chat on behalf of the organization which is represented by the bot. Returns True on success.

      + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      chat_idInteger or StringYesUnique identifier for the target chat or username of the target bot, supergroup or channel in the format @username. Channel direct messages chats can't be verified.
      custom_descriptionStringOptionalCustom description for the verification; 0-70 characters. Must be empty if the organization isn't allowed to provide a custom verification description.
      +

      removeUserVerification

      +

      Removes verification from a user who is currently verified on behalf of the organization represented by the bot. Returns True on success.

      + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      user_idIntegerYesUnique identifier of the target user
      +

      removeChatVerification

      +

      Removes verification from a chat that is currently verified on behalf of the organization represented by the bot. Returns True on success.

      + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      chat_idInteger or StringYesUnique identifier for the target chat or username of the target bot or channel in the format @username
      +

      readBusinessMessage

      +

      Marks incoming message as read on behalf of a business account. Requires the can_read_messages business bot right. Returns True on success.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      business_connection_idStringYesUnique identifier of the business connection on behalf of which to read the message
      chat_idIntegerYesUnique identifier of the chat in which the message was received. The chat must have been active in the last 24 hours.
      message_idIntegerYesUnique identifier of the message to mark as read
      +

      deleteBusinessMessages

      +

      Delete messages on behalf of a business account. Requires the can_delete_sent_messages business bot right to delete messages sent by the bot itself, or the can_delete_all_messages business bot right to delete any message. Returns True on success.

      + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      business_connection_idStringYesUnique identifier of the business connection on behalf of which to delete the messages
      message_idsArray of IntegerYesA JSON-serialized list of 1-100 identifiers of messages to delete. All messages must be from the same chat. See deleteMessage for limitations on which messages can be deleted
      +

      setBusinessAccountName

      +

      Changes the first and last name of a managed business account. Requires the can_change_name business bot right. Returns True on success.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      business_connection_idStringYesUnique identifier of the business connection
      first_nameStringYesThe new value of the first name for the business account; 1-64 characters
      last_nameStringOptionalThe new value of the last name for the business account; 0-64 characters
      +

      setBusinessAccountUsername

      +

      Changes the username of a managed business account. Requires the can_change_username business bot right. Returns True on success.

      + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      business_connection_idStringYesUnique identifier of the business connection
      usernameStringOptionalThe new value of the username for the business account; 0-32 characters
      +

      setBusinessAccountBio

      +

      Changes the bio of a managed business account. Requires the can_change_bio business bot right. Returns True on success.

      + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      business_connection_idStringYesUnique identifier of the business connection
      bioStringOptionalThe new value of the bio for the business account; 0-140 characters
      +

      setBusinessAccountProfilePhoto

      +

      Changes the profile photo of a managed business account. Requires the can_edit_profile_photo business bot right. Returns True on success.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      business_connection_idStringYesUnique identifier of the business connection
      photoInputProfilePhotoYesThe new profile photo to set
      is_publicBooleanOptionalPass True to set the public photo, which will be visible even if the main photo is hidden by the business account's privacy settings. An account can have only one public photo.
      +

      removeBusinessAccountProfilePhoto

      +

      Removes the current profile photo of a managed business account. Requires the can_edit_profile_photo business bot right. Returns True on success.

      + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      business_connection_idStringYesUnique identifier of the business connection
      is_publicBooleanOptionalPass True to remove the public photo, which is visible even if the main photo is hidden by the business account's privacy settings. After the main photo is removed, the previous profile photo (if present) becomes the main photo.
      +

      setBusinessAccountGiftSettings

      +

      Changes the privacy settings pertaining to incoming gifts in a managed business account. Requires the can_change_gift_settings business bot right. Returns True on success.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      business_connection_idStringYesUnique identifier of the business connection
      show_gift_buttonBooleanYesPass True, if a button for sending a gift to the user or by the business account must always be shown in the input field
      accepted_gift_typesAcceptedGiftTypesYesTypes of gifts accepted by the business account
      +

      getBusinessAccountStarBalance

      +

      Returns the amount of Telegram Stars owned by a managed business account. Requires the can_view_gifts_and_stars business bot right. Returns StarAmount on success.

      + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      business_connection_idStringYesUnique identifier of the business connection
      +

      transferBusinessAccountStars

      +

      Transfers Telegram Stars from the business account balance to the bot's balance. Requires the can_transfer_stars business bot right. Returns True on success.

      + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      business_connection_idStringYesUnique identifier of the business connection
      star_countIntegerYesNumber of Telegram Stars to transfer; 1-10000
      +

      getBusinessAccountGifts

      +

      Returns the gifts received and owned by a managed business account. Requires the can_view_gifts_and_stars business bot right. Returns OwnedGifts on success.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      business_connection_idStringYesUnique identifier of the business connection
      exclude_unsavedBooleanOptionalPass True to exclude gifts that aren't saved to the account's profile page
      exclude_savedBooleanOptionalPass True to exclude gifts that are saved to the account's profile page
      exclude_unlimitedBooleanOptionalPass True to exclude gifts that can be purchased an unlimited number of times
      exclude_limited_upgradableBooleanOptionalPass True to exclude gifts that can be purchased a limited number of times and can be upgraded to unique
      exclude_limited_non_upgradableBooleanOptionalPass True to exclude gifts that can be purchased a limited number of times and can't be upgraded to unique
      exclude_uniqueBooleanOptionalPass True to exclude unique gifts
      exclude_from_blockchainBooleanOptionalPass True to exclude gifts that were assigned from the TON blockchain and can't be resold or transferred in Telegram
      sort_by_priceBooleanOptionalPass True to sort results by gift price instead of send date. Sorting is applied before pagination.
      offsetStringOptionalOffset of the first entry to return as received from the previous request; use empty string to get the first chunk of results
      limitIntegerOptionalThe maximum number of gifts to be returned; 1-100. Defaults to 100
      +

      getUserGifts

      +

      Returns the gifts owned and hosted by a user. Returns OwnedGifts on success.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      user_idIntegerYesUnique identifier of the user
      exclude_unlimitedBooleanOptionalPass True to exclude gifts that can be purchased an unlimited number of times
      exclude_limited_upgradableBooleanOptionalPass True to exclude gifts that can be purchased a limited number of times and can be upgraded to unique
      exclude_limited_non_upgradableBooleanOptionalPass True to exclude gifts that can be purchased a limited number of times and can't be upgraded to unique
      exclude_from_blockchainBooleanOptionalPass True to exclude gifts that were assigned from the TON blockchain and can't be resold or transferred in Telegram
      exclude_uniqueBooleanOptionalPass True to exclude unique gifts
      sort_by_priceBooleanOptionalPass True to sort results by gift price instead of send date. Sorting is applied before pagination.
      offsetStringOptionalOffset of the first entry to return as received from the previous request; use an empty string to get the first chunk of results
      limitIntegerOptionalThe maximum number of gifts to be returned; 1-100. Defaults to 100
      +

      getChatGifts

      +

      Returns the gifts owned by a chat. Returns OwnedGifts on success.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      chat_idInteger or StringYesUnique identifier for the target chat or username of the target channel in the format @username
      exclude_unsavedBooleanOptionalPass True to exclude gifts that aren't saved to the chat's profile page. Always True, unless the bot has the can_post_messages administrator right in the channel.
      exclude_savedBooleanOptionalPass True to exclude gifts that are saved to the chat's profile page. Always False, unless the bot has the can_post_messages administrator right in the channel.
      exclude_unlimitedBooleanOptionalPass True to exclude gifts that can be purchased an unlimited number of times
      exclude_limited_upgradableBooleanOptionalPass True to exclude gifts that can be purchased a limited number of times and can be upgraded to unique
      exclude_limited_non_upgradableBooleanOptionalPass True to exclude gifts that can be purchased a limited number of times and can't be upgraded to unique
      exclude_from_blockchainBooleanOptionalPass True to exclude gifts that were assigned from the TON blockchain and can't be resold or transferred in Telegram
      exclude_uniqueBooleanOptionalPass True to exclude unique gifts
      sort_by_priceBooleanOptionalPass True to sort results by gift price instead of send date. Sorting is applied before pagination.
      offsetStringOptionalOffset of the first entry to return as received from the previous request; use an empty string to get the first chunk of results
      limitIntegerOptionalThe maximum number of gifts to be returned; 1-100. Defaults to 100
      +

      convertGiftToStars

      +

      Converts a given regular gift to Telegram Stars. Requires the can_convert_gifts_to_stars business bot right. Returns True on success.

      + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      business_connection_idStringYesUnique identifier of the business connection
      owned_gift_idStringYesUnique identifier of the regular gift that should be converted to Telegram Stars
      +

      upgradeGift

      +

      Upgrades a given regular gift to a unique gift. Requires the can_transfer_and_upgrade_gifts business bot right. Additionally requires the can_transfer_stars business bot right if the upgrade is paid. Returns True on success.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      business_connection_idStringYesUnique identifier of the business connection
      owned_gift_idStringYesUnique identifier of the regular gift that should be upgraded to a unique one
      keep_original_detailsBooleanOptionalPass True to keep the original gift text, sender and receiver in the upgraded gift
      star_countIntegerOptionalThe amount of Telegram Stars that will be paid for the upgrade from the business account balance. If gift.prepaid_upgrade_star_count > 0, then pass 0, otherwise, the can_transfer_stars business bot right is required and gift.upgrade_star_count must be passed.
      +

      transferGift

      +

      Transfers an owned unique gift to another user. Requires the can_transfer_and_upgrade_gifts business bot right. Requires can_transfer_stars business bot right if the transfer is paid. Returns True on success.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      business_connection_idStringYesUnique identifier of the business connection
      owned_gift_idStringYesUnique identifier of the regular gift that should be transferred
      new_owner_chat_idIntegerYesUnique identifier of the chat which will own the gift. The chat must be active in the last 24 hours.
      star_countIntegerOptionalThe amount of Telegram Stars that will be paid for the transfer from the business account balance. If positive, then the can_transfer_stars business bot right is required.
      +

      postStory

      +

      Posts a story on behalf of a managed business account. Requires the can_manage_stories business bot right. Returns Story on success.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      business_connection_idStringYesUnique identifier of the business connection
      contentInputStoryContentYesContent of the story
      active_periodIntegerYesPeriod after which the story is moved to the archive, in seconds; must be one of 6 * 3600, 12 * 3600, 86400, or 2 * 86400
      captionStringOptionalCaption of the story, 0-2048 characters after entities parsing
      parse_modeStringOptionalMode for parsing entities in the story caption. See formatting options for more details.
      caption_entitiesArray of MessageEntityOptionalA JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode
      areasArray of StoryAreaOptionalA JSON-serialized list of clickable areas to be shown on the story
      post_to_chat_pageBooleanOptionalPass True to keep the story accessible after it expires
      protect_contentBooleanOptionalPass True if the content of the story must be protected from forwarding and screenshotting
      +

      repostStory

      +

      Reposts a story on behalf of a business account from another business account. Both business accounts must be managed by the same bot, and the story on the source account must have been posted (or reposted) by the bot. Requires the can_manage_stories business bot right for both business accounts. Returns Story on success.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      business_connection_idStringYesUnique identifier of the business connection
      from_chat_idIntegerYesUnique identifier of the chat which posted the story that should be reposted
      from_story_idIntegerYesUnique identifier of the story that should be reposted
      active_periodIntegerYesPeriod after which the story is moved to the archive, in seconds; must be one of 6 * 3600, 12 * 3600, 86400, or 2 * 86400
      post_to_chat_pageBooleanOptionalPass True to keep the story accessible after it expires
      protect_contentBooleanOptionalPass True if the content of the story must be protected from forwarding and screenshotting
      +

      editStory

      +

      Edits a story previously posted by the bot on behalf of a managed business account. Requires the can_manage_stories business bot right. Returns Story on success.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      business_connection_idStringYesUnique identifier of the business connection
      story_idIntegerYesUnique identifier of the story to edit
      contentInputStoryContentYesContent of the story
      captionStringOptionalCaption of the story, 0-2048 characters after entities parsing
      parse_modeStringOptionalMode for parsing entities in the story caption. See formatting options for more details.
      caption_entitiesArray of MessageEntityOptionalA JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode
      areasArray of StoryAreaOptionalA JSON-serialized list of clickable areas to be shown on the story
      +

      deleteStory

      +

      Deletes a story previously posted by the bot on behalf of a managed business account. Requires the can_manage_stories business bot right. Returns True on success.

      + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      business_connection_idStringYesUnique identifier of the business connection
      story_idIntegerYesUnique identifier of the story to delete
      +

      answerWebAppQuery

      +

      Use this method to set the result of an interaction with a Web App and send a corresponding message on behalf of the user to the chat from which the query originated. On success, a SentWebAppMessage object is returned.

      + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      web_app_query_idStringYesUnique identifier for the query to be answered
      resultInlineQueryResultYesA JSON-serialized object describing the message to be sent
      +

      savePreparedInlineMessage

      +

      Stores a message that can be sent by a user of a Mini App. Returns a PreparedInlineMessage object.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      user_idIntegerYesUnique identifier of the target user that can use the prepared message
      resultInlineQueryResultYesA JSON-serialized object describing the message to be sent
      allow_user_chatsBooleanOptionalPass True if the message can be sent to private chats with users
      allow_bot_chatsBooleanOptionalPass True if the message can be sent to private chats with bots
      allow_group_chatsBooleanOptionalPass True if the message can be sent to group and supergroup chats
      allow_channel_chatsBooleanOptionalPass True if the message can be sent to channel chats
      +

      savePreparedKeyboardButton

      +

      Stores a keyboard button that can be used by a user within a Mini App. Returns a PreparedKeyboardButton object.

      + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      user_idIntegerYesUnique identifier of the target user that can use the button
      buttonKeyboardButtonYesA JSON-serialized object describing the button to be saved. The button must be of the type request_users, request_chat, or request_managed_bot
      +

      Inline mode methods

      +

      Methods and objects used in the inline mode are described in the Inline mode section.

      +

      Updating messages

      +

      The following methods allow you to change an existing message in the message history instead of sending a new one with a result of an action. This is most useful for messages with inline keyboards using callback queries, but can also help reduce clutter in conversations with regular chat bots.

      +

      Please note, that it is currently only possible to edit messages without reply_markup or with inline keyboards.

      +

      editMessageText

      +

      Use this method to edit text and game messages. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. Note that business messages that were not sent by the bot and do not contain an inline keyboard can only be edited within 48 hours from the time they were sent.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      business_connection_idStringOptionalUnique identifier of the business connection on behalf of which the message to be edited was sent
      chat_idInteger or StringOptionalRequired if inline_message_id is not specified. Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username.
      message_idIntegerOptionalRequired if inline_message_id is not specified. Identifier of the message to edit
      inline_message_idStringOptionalRequired if chat_id and message_id are not specified. Identifier of the inline message
      textStringYesNew text of the message, 1-4096 characters after entities parsing
      parse_modeStringOptionalMode for parsing entities in the message text. See formatting options for more details.
      entitiesArray of MessageEntityOptionalA JSON-serialized list of special entities that appear in message text, which can be specified instead of parse_mode
      link_preview_optionsLinkPreviewOptionsOptionalLink preview generation options for the message
      reply_markupInlineKeyboardMarkupOptionalA JSON-serialized object for an inline keyboard.
      +

      editMessageCaption

      +

      Use this method to edit captions of messages. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. Note that business messages that were not sent by the bot and do not contain an inline keyboard can only be edited within 48 hours from the time they were sent.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      business_connection_idStringOptionalUnique identifier of the business connection on behalf of which the message to be edited was sent
      chat_idInteger or StringOptionalRequired if inline_message_id is not specified. Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username.
      message_idIntegerOptionalRequired if inline_message_id is not specified. Identifier of the message to edit
      inline_message_idStringOptionalRequired if chat_id and message_id are not specified. Identifier of the inline message
      captionStringOptionalNew caption of the message, 0-1024 characters after entities parsing
      parse_modeStringOptionalMode for parsing entities in the message caption. See formatting options for more details.
      caption_entitiesArray of MessageEntityOptionalA JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode
      show_caption_above_mediaBooleanOptionalPass True, if the caption must be shown above the message media. Supported only for animation, photo and video messages.
      reply_markupInlineKeyboardMarkupOptionalA JSON-serialized object for an inline keyboard.
      +

      editMessageMedia

      +

      Use this method to edit animation, audio, document, live photo, photo, or video messages, or to add media to text messages. If a message is part of a message album, then it can be edited only to an audio for audio albums, only to a document for document albums and to a photo, a live photo, or a video otherwise. When an inline message is edited, a new file can't be uploaded; use a previously uploaded file via its file_id or specify a URL. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. Note that business messages that were not sent by the bot and do not contain an inline keyboard can only be edited within 48 hours from the time they were sent.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      business_connection_idStringOptionalUnique identifier of the business connection on behalf of which the message to be edited was sent
      chat_idInteger or StringOptionalRequired if inline_message_id is not specified. Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username.
      message_idIntegerOptionalRequired if inline_message_id is not specified. Identifier of the message to edit
      inline_message_idStringOptionalRequired if chat_id and message_id are not specified. Identifier of the inline message
      mediaInputMediaYesA JSON-serialized object for a new media content of the message
      reply_markupInlineKeyboardMarkupOptionalA JSON-serialized object for a new inline keyboard.
      +

      editMessageLiveLocation

      +

      Use this method to edit live location messages. A location can be edited until its live_period expires or editing is explicitly disabled by a call to stopMessageLiveLocation. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      business_connection_idStringOptionalUnique identifier of the business connection on behalf of which the message to be edited was sent
      chat_idInteger or StringOptionalRequired if inline_message_id is not specified. Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username.
      message_idIntegerOptionalRequired if inline_message_id is not specified. Identifier of the message to edit
      inline_message_idStringOptionalRequired if chat_id and message_id are not specified. Identifier of the inline message
      latitudeFloatYesLatitude of new location
      longitudeFloatYesLongitude of new location
      live_periodIntegerOptionalNew period in seconds during which the location can be updated, starting from the message send date. If 0x7FFFFFFF is specified, then the location can be updated forever. Otherwise, the new value must not exceed the current live_period by more than a day, and the live location expiration date must remain within the next 90 days. If not specified, then live_period remains unchanged
      horizontal_accuracyFloatOptionalThe radius of uncertainty for the location, measured in meters; 0-1500
      headingIntegerOptionalDirection in which the user is moving, in degrees. Must be between 1 and 360 if specified.
      proximity_alert_radiusIntegerOptionalThe maximum distance for proximity alerts about approaching another chat member, in meters. Must be between 1 and 100000 if specified.
      reply_markupInlineKeyboardMarkupOptionalA JSON-serialized object for a new inline keyboard.
      +

      stopMessageLiveLocation

      +

      Use this method to stop updating a live location message before live_period expires. On success, if the message is not an inline message, the edited Message is returned, otherwise True is returned.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      business_connection_idStringOptionalUnique identifier of the business connection on behalf of which the message to be edited was sent
      chat_idInteger or StringOptionalRequired if inline_message_id is not specified. Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username.
      message_idIntegerOptionalRequired if inline_message_id is not specified. Identifier of the message with live location to stop
      inline_message_idStringOptionalRequired if chat_id and message_id are not specified. Identifier of the inline message
      reply_markupInlineKeyboardMarkupOptionalA JSON-serialized object for a new inline keyboard.
      +

      editMessageChecklist

      +

      Use this method to edit a checklist on behalf of a connected business account. On success, the edited Message is returned.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      business_connection_idStringYesUnique identifier of the business connection on behalf of which the message will be sent
      chat_idInteger or StringYesUnique identifier for the target chat or username of the target bot in the format @username
      message_idIntegerYesUnique identifier for the target message
      checklistInputChecklistYesA JSON-serialized object for the new checklist
      reply_markupInlineKeyboardMarkupOptionalA JSON-serialized object for the new inline keyboard for the message
      +

      editMessageReplyMarkup

      +

      Use this method to edit only the reply markup of messages. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. Note that business messages that were not sent by the bot and do not contain an inline keyboard can only be edited within 48 hours from the time they were sent.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      business_connection_idStringOptionalUnique identifier of the business connection on behalf of which the message to be edited was sent
      chat_idInteger or StringOptionalRequired if inline_message_id is not specified. Unique identifier for the target chat or username of the target bot, supergroup or channel in the format @username.
      message_idIntegerOptionalRequired if inline_message_id is not specified. Identifier of the message to edit
      inline_message_idStringOptionalRequired if chat_id and message_id are not specified. Identifier of the inline message
      reply_markupInlineKeyboardMarkupOptionalA JSON-serialized object for an inline keyboard.
      +

      stopPoll

      +

      Use this method to stop a poll which was sent by the bot. On success, the stopped Poll is returned.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      business_connection_idStringOptionalUnique identifier of the business connection on behalf of which the message to be edited was sent
      chat_idInteger or StringYesUnique identifier for the target chat or username of the target bot, supergroup or channel in the format @username
      message_idIntegerYesIdentifier of the original message with the poll
      reply_markupInlineKeyboardMarkupOptionalA JSON-serialized object for a new message inline keyboard.
      +

      approveSuggestedPost

      +

      Use this method to approve a suggested post in a direct messages chat. The bot must have the 'can_post_messages' administrator right in the corresponding channel chat. Returns True on success.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      chat_idIntegerYesUnique identifier for the target direct messages chat
      message_idIntegerYesIdentifier of a suggested post message to approve
      send_dateIntegerOptionalPoint in time (Unix timestamp) when the post is expected to be published; omit if the date has already been specified when the suggested post was created. If specified, then the date must be not more than 2678400 seconds (30 days) in the future
      +

      declineSuggestedPost

      +

      Use this method to decline a suggested post in a direct messages chat. The bot must have the 'can_manage_direct_messages' administrator right in the corresponding channel chat. Returns True on success.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      chat_idIntegerYesUnique identifier for the target direct messages chat
      message_idIntegerYesIdentifier of a suggested post message to decline
      commentStringOptionalComment for the creator of the suggested post; 0-128 characters
      +

      deleteMessage

      +

      Use this method to delete a message, including service messages, with the following limitations:
      - A message can only be deleted if it was sent less than 48 hours ago.
      - Service messages about a supergroup, channel, or forum topic creation can't be deleted.
      - A dice message in a private chat can only be deleted if it was sent more than 24 hours ago.
      - Bots can delete outgoing messages in private chats, groups, and supergroups.
      - Bots can delete incoming messages in private chats.
      - Bots granted can_post_messages permissions can delete outgoing messages in channels.
      - If the bot is an administrator of a group, it can delete any message there.
      - If the bot has can_delete_messages administrator right in a supergroup or a channel, it can delete any message there.
      - If the bot has can_manage_direct_messages administrator right in a channel, it can delete any message in the corresponding direct messages chat.
      Returns True on success.

      + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      chat_idInteger or StringYesUnique identifier for the target chat or username of the target bot, supergroup or channel in the format @username
      message_idIntegerYesIdentifier of the message to delete
      +

      deleteMessages

      +

      Use this method to delete multiple messages simultaneously. If some of the specified messages can't be found, they are skipped. Returns True on success.

      + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      chat_idInteger or StringYesUnique identifier for the target chat or username of the target bot, supergroup or channel in the format @username
      message_idsArray of IntegerYesA JSON-serialized list of 1-100 identifiers of messages to delete. See deleteMessage for limitations on which messages can be deleted
      +

      deleteMessageReaction

      +

      Use this method to remove a reaction from a message in a group or a supergroup chat. The bot must have the 'can_delete_messages' administrator right in the chat. Returns True on success.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      chat_idInteger or StringYesUnique identifier for the target chat or username of the target supergroup (in the format @username)
      message_idIntegerYesIdentifier of the target message
      user_idIntegerOptionalIdentifier of the user whose reaction will be removed, if the reaction was added by a user
      actor_chat_idIntegerOptionalIdentifier of the chat whose reaction will be removed, if the reaction was added by a chat
      +

      deleteAllMessageReactions

      +

      Use this method to remove up to 10000 recent reactions in a group or a supergroup chat added by a given user or chat. The bot must have the 'can_delete_messages' administrator right in the chat. Returns True on success.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      chat_idInteger or StringYesUnique identifier for the target chat or username of the target supergroup (in the format @username)
      user_idIntegerOptionalIdentifier of the user whose reactions will be removed, if the reactions were added by a user
      actor_chat_idIntegerOptionalIdentifier of the chat whose reactions will be removed, if the reactions were added by a chat
      +

      Stickers

      +

      The following methods and objects allow your bot to handle stickers and sticker sets.

      +

      Sticker

      +

      This object represents a sticker.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      file_idStringIdentifier for this file, which can be used to download or reuse the file
      file_unique_idStringUnique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file.
      typeStringType of the sticker, currently one of “regular”, “mask”, “custom_emoji”. The type of the sticker is independent from its format, which is determined by the fields is_animated and is_video.
      widthIntegerSticker width
      heightIntegerSticker height
      is_animatedBooleanTrue, if the sticker is animated
      is_videoBooleanTrue, if the sticker is a video sticker
      thumbnailPhotoSizeOptional. Sticker thumbnail in the .WEBP or .JPG format
      emojiStringOptional. Emoji associated with the sticker
      set_nameStringOptional. Name of the sticker set to which the sticker belongs
      premium_animationFileOptional. For premium regular stickers, premium animation for the sticker
      mask_positionMaskPositionOptional. For mask stickers, the position where the mask should be placed
      custom_emoji_idStringOptional. For custom emoji stickers, unique identifier of the custom emoji
      needs_repaintingTrueOptional. True, if the sticker must be repainted to a text color in messages, the color of the Telegram Premium badge in emoji status, white color on chat photos, or another appropriate color in other places
      file_sizeIntegerOptional. File size in bytes
      +

      StickerSet

      +

      This object represents a sticker set.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      nameStringSticker set name
      titleStringSticker set title
      sticker_typeStringType of stickers in the set, currently one of “regular”, “mask”, “custom_emoji”
      stickersArray of StickerList of all set stickers
      thumbnailPhotoSizeOptional. Sticker set thumbnail in the .WEBP, .TGS, or .WEBM format
      +

      MaskPosition

      +

      This object describes the position on faces where a mask should be placed by default.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      pointStringThe part of the face relative to which the mask should be placed. One of “forehead”, “eyes”, “mouth”, or “chin”.
      x_shiftFloatShift by X-axis measured in widths of the mask scaled to the face size, from left to right. For example, choosing -1.0 will place mask just to the left of the default mask position.
      y_shiftFloatShift by Y-axis measured in heights of the mask scaled to the face size, from top to bottom. For example, 1.0 will place the mask just below the default mask position.
      scaleFloatMask scaling coefficient. For example, 2.0 means double size.
      +

      InputSticker

      +

      This object describes a sticker to be added to a sticker set.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      stickerStringThe added sticker. Pass a file_id as a String to send a file that already exists on the Telegram servers, pass an HTTP URL as a String for Telegram to get a file from the Internet, or pass “attach://<file_attach_name>” to upload a new file using multipart/form-data under <file_attach_name> name. Animated and video stickers can't be uploaded via HTTP URL. More information on Sending Files »
      formatStringFormat of the added sticker, must be one of “static” for a .WEBP or .PNG image, “animated” for a .TGS animation, “video” for a .WEBM video
      emoji_listArray of StringList of 1-20 emoji associated with the sticker
      mask_positionMaskPositionOptional. Position where the mask should be placed on faces. For “mask” stickers only.
      keywordsArray of StringOptional. List of 0-20 search keywords for the sticker with total length of up to 64 characters. For “regular” and “custom_emoji” stickers only.
      +

      sendSticker

      +

      Use this method to send static .WEBP, animated .TGS, or video .WEBM stickers. On success, the sent Message is returned.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      business_connection_idStringOptionalUnique identifier of the business connection on behalf of which the message will be sent
      chat_idInteger or StringYesUnique identifier for the target chat or username of the target bot, supergroup or channel in the format @username
      message_thread_idIntegerOptionalUnique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only
      direct_messages_topic_idIntegerOptionalIdentifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat
      stickerInputFile or StringYesSticker to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a .WEBP sticker from the Internet, or upload a new .WEBP, .TGS, or .WEBM sticker using multipart/form-data. More information on Sending Files ». Video and animated stickers can't be sent via an HTTP URL.
      emojiStringOptionalEmoji associated with the sticker; only for just uploaded stickers
      disable_notificationBooleanOptionalSends the message silently. Users will receive a notification with no sound.
      protect_contentBooleanOptionalProtects the contents of the sent message from forwarding and saving
      allow_paid_broadcastBooleanOptionalPass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance.
      message_effect_idStringOptionalUnique identifier of the message effect to be added to the message; for private chats only
      suggested_post_parametersSuggestedPostParametersOptionalA JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined.
      reply_parametersReplyParametersOptionalDescription of the message to reply to
      reply_markupInlineKeyboardMarkup or ReplyKeyboardMarkup or ReplyKeyboardRemove or ForceReplyOptionalAdditional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove a reply keyboard or to force a reply from the user
      +

      getStickerSet

      +

      Use this method to get a sticker set. On success, a StickerSet object is returned.

      + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      nameStringYesName of the sticker set
      +

      getCustomEmojiStickers

      +

      Use this method to get information about custom emoji stickers by their identifiers. Returns an Array of Sticker objects.

      + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      custom_emoji_idsArray of StringYesA JSON-serialized list of custom emoji identifiers. At most 200 custom emoji identifiers can be specified.
      +

      uploadStickerFile

      +

      Use this method to upload a file with a sticker for later use in the createNewStickerSet, addStickerToSet, or replaceStickerInSet methods (the file can be used multiple times). Returns the uploaded File on success.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      user_idIntegerYesUser identifier of sticker file owner
      stickerInputFileYesA file with the sticker in .WEBP, .PNG, .TGS, or .WEBM format. See https://core.telegram.org/stickers for technical requirements. More information on Sending Files »
      sticker_formatStringYesFormat of the sticker, must be one of “static”, “animated”, “video”
      +

      createNewStickerSet

      +

      Use this method to create a new sticker set owned by a user. The bot will be able to edit the sticker set thus created. Returns True on success.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      user_idIntegerYesUser identifier of created sticker set owner
      nameStringYesShort name of sticker set, to be used in t.me/addstickers/ URLs (e.g., animals). Can contain only English letters, digits and underscores. Must begin with a letter, can't contain consecutive underscores and must end in "_by_<bot_username>". <bot_username> is case insensitive. 1-64 characters.
      titleStringYesSticker set title, 1-64 characters
      stickersArray of InputStickerYesA JSON-serialized list of 1-50 initial stickers to be added to the sticker set
      sticker_typeStringOptionalType of stickers in the set, pass “regular”, “mask”, or “custom_emoji”. By default, a regular sticker set is created.
      needs_repaintingBooleanOptionalPass True if stickers in the sticker set must be repainted to the color of text when used in messages, the accent color if used as emoji status, white on chat photos, or another appropriate color based on context; for custom emoji sticker sets only
      +

      addStickerToSet

      +

      Use this method to add a new sticker to a set created by the bot. Emoji sticker sets can have up to 200 stickers. Other sticker sets can have up to 120 stickers. Returns True on success.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      user_idIntegerYesUser identifier of sticker set owner
      nameStringYesSticker set name
      stickerInputStickerYesA JSON-serialized object with information about the added sticker. If exactly the same sticker had already been added to the set, then the set isn't changed.
      +

      setStickerPositionInSet

      +

      Use this method to move a sticker in a set created by the bot to a specific position. Returns True on success.

      + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      stickerStringYesFile identifier of the sticker
      positionIntegerYesNew sticker position in the set, zero-based
      +

      deleteStickerFromSet

      +

      Use this method to delete a sticker from a set created by the bot. Returns True on success.

      + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      stickerStringYesFile identifier of the sticker
      +

      replaceStickerInSet

      +

      Use this method to replace an existing sticker in a sticker set with a new one. The method is equivalent to calling deleteStickerFromSet, then addStickerToSet, then setStickerPositionInSet. Returns True on success.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      user_idIntegerYesUser identifier of the sticker set owner
      nameStringYesSticker set name
      old_stickerStringYesFile identifier of the replaced sticker
      stickerInputStickerYesA JSON-serialized object with information about the added sticker. If exactly the same sticker had already been added to the set, then the set remains unchanged.
      +

      setStickerEmojiList

      +

      Use this method to change the list of emoji assigned to a regular or custom emoji sticker. The sticker must belong to a sticker set created by the bot. Returns True on success.

      + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      stickerStringYesFile identifier of the sticker
      emoji_listArray of StringYesA JSON-serialized list of 1-20 emoji associated with the sticker
      +

      setStickerKeywords

      +

      Use this method to change search keywords assigned to a regular or custom emoji sticker. The sticker must belong to a sticker set created by the bot. Returns True on success.

      + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      stickerStringYesFile identifier of the sticker
      keywordsArray of StringOptionalA JSON-serialized list of 0-20 search keywords for the sticker with total length of up to 64 characters
      +

      setStickerMaskPosition

      +

      Use this method to change the mask position of a mask sticker. The sticker must belong to a sticker set that was created by the bot. Returns True on success.

      + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      stickerStringYesFile identifier of the sticker
      mask_positionMaskPositionOptionalA JSON-serialized object with the position where the mask should be placed on faces. Omit the parameter to remove the mask position.
      +

      setStickerSetTitle

      +

      Use this method to set the title of a created sticker set. Returns True on success.

      + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      nameStringYesSticker set name
      titleStringYesSticker set title, 1-64 characters
      +

      setStickerSetThumbnail

      +

      Use this method to set the thumbnail of a regular or mask sticker set. The format of the thumbnail file must match the format of the stickers in the set. Returns True on success.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      nameStringYesSticker set name
      user_idIntegerYesUser identifier of the sticker set owner
      thumbnailInputFile or StringOptionalA .WEBP or .PNG image with the thumbnail, must be up to 128 kilobytes in size and have a width and height of exactly 100px, or a .TGS animation with a thumbnail up to 32 kilobytes in size (see https://core.telegram.org/stickers#animation-requirements for animated sticker technical requirements), or a .WEBM video with the thumbnail up to 32 kilobytes in size; see https://core.telegram.org/stickers#video-requirements for video sticker technical requirements. Pass a file_id as a String to send a file that already exists on the Telegram servers, pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files ». Animated and video sticker set thumbnails can't be uploaded via HTTP URL. If omitted, then the thumbnail is dropped and the first sticker is used as the thumbnail.
      formatStringYesFormat of the thumbnail, must be one of “static” for a .WEBP or .PNG image, “animated” for a .TGS animation, or “video” for a .WEBM video
      +

      setCustomEmojiStickerSetThumbnail

      +

      Use this method to set the thumbnail of a custom emoji sticker set. Returns True on success.

      + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      nameStringYesSticker set name
      custom_emoji_idStringOptionalCustom emoji identifier of a sticker from the sticker set; pass an empty string to drop the thumbnail and use the first sticker as the thumbnail.
      +

      deleteStickerSet

      +

      Use this method to delete a sticker set that was created by the bot. Returns True on success.

      + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      nameStringYesSticker set name
      +

      Inline mode

      +

      The following methods and objects allow your bot to work in inline mode.
      Please see our Introduction to Inline bots for more details.

      +

      To enable this option, send the /setinline command to @BotFather and provide the placeholder text that the user will see in the input field after typing your bot's name.

      +

      InlineQuery

      +

      This object represents an incoming inline query. When the user sends an empty query, your bot could return some default or trending results.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      idStringUnique identifier for this query
      fromUserSender
      queryStringText of the query (up to 256 characters)
      offsetStringOffset of the results to be returned, can be controlled by the bot
      chat_typeStringOptional. Type of the chat from which the inline query was sent. Can be either “sender” for a private chat with the inline query sender, “private”, “group”, “supergroup”, or “channel”. The chat type should be always known for requests sent from official clients and most third-party clients, unless the request was sent from a secret chat
      locationLocationOptional. Sender location, only for bots that request user location
      +

      answerInlineQuery

      +

      Use this method to send answers to an inline query. On success, True is returned.
      No more than 50 results per query are allowed.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      inline_query_idStringYesUnique identifier for the answered query
      resultsArray of InlineQueryResultYesA JSON-serialized array of results for the inline query
      cache_timeIntegerOptionalThe maximum amount of time in seconds that the result of the inline query may be cached on the server. Defaults to 300.
      is_personalBooleanOptionalPass True if results may be cached on the server side only for the user that sent the query. By default, results may be returned to any user who sends the same query.
      next_offsetStringOptionalPass the offset that a client should send in the next query with the same text to receive more results. Pass an empty string if there are no more results or if you don't support pagination. Offset length can't exceed 64 bytes.
      buttonInlineQueryResultsButtonOptionalA JSON-serialized object describing a button to be shown above inline query results
      +

      InlineQueryResultsButton

      +

      This object represents a button to be shown above inline query results. You must use exactly one of the optional fields.

      + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      textStringLabel text on the button
      web_appWebAppInfoOptional. Description of the Web App that will be launched when the user presses the button. The Web App will be able to switch back to the inline mode using the method switchInlineQuery inside the Web App.
      start_parameterStringOptional. Deep-linking parameter for the /start message sent to the bot when a user presses the button. 1-64 characters, only A-Z, a-z, 0-9, _ and - are allowed.

      Example: An inline bot that sends YouTube videos can ask the user to connect the bot to their YouTube account to adapt search results accordingly. To do this, it displays a 'Connect your YouTube account' button above the results, or even before showing any. The user presses the button, switches to a private chat with the bot and, in doing so, passes a start parameter that instructs the bot to return an OAuth link. Once done, the bot can offer a switch_inline button so that the user can easily return to the chat where they wanted to use the bot's inline capabilities.
      +

      InlineQueryResult

      +

      This object represents one result of an inline query. Telegram clients currently support results of the following 20 types:

      + +

      Note: All URLs passed in inline query results will be available to end users and therefore must be assumed to be public.

      +

      InlineQueryResultArticle

      +

      Represents a link to an article or web page.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringType of the result, must be article
      idStringUnique identifier for this result, 1-64 Bytes
      titleStringTitle of the result
      input_message_contentInputMessageContentContent of the message to be sent
      reply_markupInlineKeyboardMarkupOptional. Inline keyboard attached to the message
      urlStringOptional. URL of the result
      descriptionStringOptional. Short description of the result
      thumbnail_urlStringOptional. Url of the thumbnail for the result
      thumbnail_widthIntegerOptional. Thumbnail width
      thumbnail_heightIntegerOptional. Thumbnail height
      +

      InlineQueryResultPhoto

      +

      Represents a link to a photo. By default, this photo will be sent by the user with optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the photo.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringType of the result, must be photo
      idStringUnique identifier for this result, 1-64 bytes
      photo_urlStringA valid URL of the photo. Photo must be in JPEG format. Photo size must not exceed 5MB
      thumbnail_urlStringURL of the thumbnail for the photo
      photo_widthIntegerOptional. Width of the photo
      photo_heightIntegerOptional. Height of the photo
      titleStringOptional. Title for the result
      descriptionStringOptional. Short description of the result
      captionStringOptional. Caption of the photo to be sent, 0-1024 characters after entities parsing
      parse_modeStringOptional. Mode for parsing entities in the photo caption. See formatting options for more details.
      caption_entitiesArray of MessageEntityOptional. List of special entities that appear in the caption, which can be specified instead of parse_mode
      show_caption_above_mediaBooleanOptional. Pass True, if the caption must be shown above the message media
      reply_markupInlineKeyboardMarkupOptional. Inline keyboard attached to the message
      input_message_contentInputMessageContentOptional. Content of the message to be sent instead of the photo
      +

      InlineQueryResultGif

      +

      Represents a link to an animated GIF file. By default, this animated GIF file will be sent by the user with optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the animation.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringType of the result, must be gif
      idStringUnique identifier for this result, 1-64 bytes
      gif_urlStringA valid URL for the GIF file
      gif_widthIntegerOptional. Width of the GIF
      gif_heightIntegerOptional. Height of the GIF
      gif_durationIntegerOptional. Duration of the GIF in seconds
      thumbnail_urlStringURL of the static (JPEG or GIF) or animated (MPEG4) thumbnail for the result
      thumbnail_mime_typeStringOptional. MIME type of the thumbnail, must be one of “image/jpeg”, “image/gif”, or “video/mp4”. Defaults to “image/jpeg”
      titleStringOptional. Title for the result
      captionStringOptional. Caption of the GIF file to be sent, 0-1024 characters after entities parsing
      parse_modeStringOptional. Mode for parsing entities in the caption. See formatting options for more details.
      caption_entitiesArray of MessageEntityOptional. List of special entities that appear in the caption, which can be specified instead of parse_mode
      show_caption_above_mediaBooleanOptional. Pass True, if the caption must be shown above the message media
      reply_markupInlineKeyboardMarkupOptional. Inline keyboard attached to the message
      input_message_contentInputMessageContentOptional. Content of the message to be sent instead of the GIF animation
      +

      InlineQueryResultMpeg4Gif

      +

      Represents a link to a video animation (H.264/MPEG-4 AVC video without sound). By default, this animated MPEG-4 file will be sent by the user with optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the animation.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringType of the result, must be mpeg4_gif
      idStringUnique identifier for this result, 1-64 bytes
      mpeg4_urlStringA valid URL for the MPEG4 file
      mpeg4_widthIntegerOptional. Video width
      mpeg4_heightIntegerOptional. Video height
      mpeg4_durationIntegerOptional. Video duration in seconds
      thumbnail_urlStringURL of the static (JPEG or GIF) or animated (MPEG4) thumbnail for the result
      thumbnail_mime_typeStringOptional. MIME type of the thumbnail, must be one of “image/jpeg”, “image/gif”, or “video/mp4”. Defaults to “image/jpeg”
      titleStringOptional. Title for the result
      captionStringOptional. Caption of the MPEG-4 file to be sent, 0-1024 characters after entities parsing
      parse_modeStringOptional. Mode for parsing entities in the caption. See formatting options for more details.
      caption_entitiesArray of MessageEntityOptional. List of special entities that appear in the caption, which can be specified instead of parse_mode
      show_caption_above_mediaBooleanOptional. Pass True, if the caption must be shown above the message media
      reply_markupInlineKeyboardMarkupOptional. Inline keyboard attached to the message
      input_message_contentInputMessageContentOptional. Content of the message to be sent instead of the video animation
      +

      InlineQueryResultVideo

      +

      Represents a link to a page containing an embedded video player or a video file. By default, this video file will be sent by the user with an optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the video.

      +
      +

      If an InlineQueryResultVideo message contains an embedded video (e.g., YouTube), you must replace its content using input_message_content.

      +
      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringType of the result, must be video
      idStringUnique identifier for this result, 1-64 bytes
      video_urlStringA valid URL for the embedded video player or video file
      mime_typeStringMIME type of the content of the video URL, “text/html” or “video/mp4”
      thumbnail_urlStringURL of the thumbnail (JPEG only) for the video
      titleStringTitle for the result
      captionStringOptional. Caption of the video to be sent, 0-1024 characters after entities parsing
      parse_modeStringOptional. Mode for parsing entities in the video caption. See formatting options for more details.
      caption_entitiesArray of MessageEntityOptional. List of special entities that appear in the caption, which can be specified instead of parse_mode
      show_caption_above_mediaBooleanOptional. Pass True, if the caption must be shown above the message media
      video_widthIntegerOptional. Video width
      video_heightIntegerOptional. Video height
      video_durationIntegerOptional. Video duration in seconds
      descriptionStringOptional. Short description of the result
      reply_markupInlineKeyboardMarkupOptional. Inline keyboard attached to the message
      input_message_contentInputMessageContentOptional. Content of the message to be sent instead of the video. This field is required if InlineQueryResultVideo is used to send an HTML-page as a result (e.g., a YouTube video).
      +

      InlineQueryResultAudio

      +

      Represents a link to an MP3 audio file. By default, this audio file will be sent by the user. Alternatively, you can use input_message_content to send a message with the specified content instead of the audio.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringType of the result, must be audio
      idStringUnique identifier for this result, 1-64 bytes
      audio_urlStringA valid URL for the audio file
      titleStringTitle
      captionStringOptional. Caption, 0-1024 characters after entities parsing
      parse_modeStringOptional. Mode for parsing entities in the audio caption. See formatting options for more details.
      caption_entitiesArray of MessageEntityOptional. List of special entities that appear in the caption, which can be specified instead of parse_mode
      performerStringOptional. Performer
      audio_durationIntegerOptional. Audio duration in seconds
      reply_markupInlineKeyboardMarkupOptional. Inline keyboard attached to the message
      input_message_contentInputMessageContentOptional. Content of the message to be sent instead of the audio
      +

      InlineQueryResultVoice

      +

      Represents a link to a voice recording in an .OGG container encoded with OPUS. By default, this voice recording will be sent by the user. Alternatively, you can use input_message_content to send a message with the specified content instead of the the voice message.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringType of the result, must be voice
      idStringUnique identifier for this result, 1-64 bytes
      voice_urlStringA valid URL for the voice recording
      titleStringRecording title
      captionStringOptional. Caption, 0-1024 characters after entities parsing
      parse_modeStringOptional. Mode for parsing entities in the voice message caption. See formatting options for more details.
      caption_entitiesArray of MessageEntityOptional. List of special entities that appear in the caption, which can be specified instead of parse_mode
      voice_durationIntegerOptional. Recording duration in seconds
      reply_markupInlineKeyboardMarkupOptional. Inline keyboard attached to the message
      input_message_contentInputMessageContentOptional. Content of the message to be sent instead of the voice recording
      +

      InlineQueryResultDocument

      +

      Represents a link to a file. By default, this file will be sent by the user with an optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the file. Currently, only .PDF and .ZIP files can be sent using this method.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringType of the result, must be document
      idStringUnique identifier for this result, 1-64 bytes
      titleStringTitle for the result
      captionStringOptional. Caption of the document to be sent, 0-1024 characters after entities parsing
      parse_modeStringOptional. Mode for parsing entities in the document caption. See formatting options for more details.
      caption_entitiesArray of MessageEntityOptional. List of special entities that appear in the caption, which can be specified instead of parse_mode
      document_urlStringA valid URL for the file
      mime_typeStringMIME type of the content of the file, either “application/pdf” or “application/zip”
      descriptionStringOptional. Short description of the result
      reply_markupInlineKeyboardMarkupOptional. Inline keyboard attached to the message
      input_message_contentInputMessageContentOptional. Content of the message to be sent instead of the file
      thumbnail_urlStringOptional. URL of the thumbnail (JPEG only) for the file
      thumbnail_widthIntegerOptional. Thumbnail width
      thumbnail_heightIntegerOptional. Thumbnail height
      +

      InlineQueryResultLocation

      +

      Represents a location on a map. By default, the location will be sent by the user. Alternatively, you can use input_message_content to send a message with the specified content instead of the location.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringType of the result, must be location
      idStringUnique identifier for this result, 1-64 Bytes
      latitudeFloatLocation latitude in degrees
      longitudeFloatLocation longitude in degrees
      titleStringLocation title
      horizontal_accuracyFloatOptional. The radius of uncertainty for the location, measured in meters; 0-1500
      live_periodIntegerOptional. Period in seconds during which the location can be updated, should be between 60 and 86400, or 0x7FFFFFFF for live locations that can be edited indefinitely.
      headingIntegerOptional. For live locations, a direction in which the user is moving, in degrees. Must be between 1 and 360 if specified.
      proximity_alert_radiusIntegerOptional. For live locations, a maximum distance for proximity alerts about approaching another chat member, in meters. Must be between 1 and 100000 if specified.
      reply_markupInlineKeyboardMarkupOptional. Inline keyboard attached to the message
      input_message_contentInputMessageContentOptional. Content of the message to be sent instead of the location
      thumbnail_urlStringOptional. Url of the thumbnail for the result
      thumbnail_widthIntegerOptional. Thumbnail width
      thumbnail_heightIntegerOptional. Thumbnail height
      +

      InlineQueryResultVenue

      +

      Represents a venue. By default, the venue will be sent by the user. Alternatively, you can use input_message_content to send a message with the specified content instead of the venue.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringType of the result, must be venue
      idStringUnique identifier for this result, 1-64 Bytes
      latitudeFloatLatitude of the venue location in degrees
      longitudeFloatLongitude of the venue location in degrees
      titleStringTitle of the venue
      addressStringAddress of the venue
      foursquare_idStringOptional. Foursquare identifier of the venue if known
      foursquare_typeStringOptional. Foursquare type of the venue, if known. (For example, “arts_entertainment/default”, “arts_entertainment/aquarium” or “food/icecream”.)
      google_place_idStringOptional. Google Places identifier of the venue
      google_place_typeStringOptional. Google Places type of the venue. (See supported types.)
      reply_markupInlineKeyboardMarkupOptional. Inline keyboard attached to the message
      input_message_contentInputMessageContentOptional. Content of the message to be sent instead of the venue
      thumbnail_urlStringOptional. Url of the thumbnail for the result
      thumbnail_widthIntegerOptional. Thumbnail width
      thumbnail_heightIntegerOptional. Thumbnail height
      +

      InlineQueryResultContact

      +

      Represents a contact with a phone number. By default, this contact will be sent by the user. Alternatively, you can use input_message_content to send a message with the specified content instead of the contact.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringType of the result, must be contact
      idStringUnique identifier for this result, 1-64 Bytes
      phone_numberStringContact's phone number
      first_nameStringContact's first name
      last_nameStringOptional. Contact's last name
      vcardStringOptional. Additional data about the contact in the form of a vCard, 0-2048 bytes
      reply_markupInlineKeyboardMarkupOptional. Inline keyboard attached to the message
      input_message_contentInputMessageContentOptional. Content of the message to be sent instead of the contact
      thumbnail_urlStringOptional. Url of the thumbnail for the result
      thumbnail_widthIntegerOptional. Thumbnail width
      thumbnail_heightIntegerOptional. Thumbnail height
      +

      InlineQueryResultGame

      +

      Represents a Game.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringType of the result, must be game
      idStringUnique identifier for this result, 1-64 bytes
      game_short_nameStringShort name of the game
      reply_markupInlineKeyboardMarkupOptional. Inline keyboard attached to the message
      +

      InlineQueryResultCachedPhoto

      +

      Represents a link to a photo stored on the Telegram servers. By default, this photo will be sent by the user with an optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the photo.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringType of the result, must be photo
      idStringUnique identifier for this result, 1-64 bytes
      photo_file_idStringA valid file identifier of the photo
      titleStringOptional. Title for the result
      descriptionStringOptional. Short description of the result
      captionStringOptional. Caption of the photo to be sent, 0-1024 characters after entities parsing
      parse_modeStringOptional. Mode for parsing entities in the photo caption. See formatting options for more details.
      caption_entitiesArray of MessageEntityOptional. List of special entities that appear in the caption, which can be specified instead of parse_mode
      show_caption_above_mediaBooleanOptional. Pass True, if the caption must be shown above the message media
      reply_markupInlineKeyboardMarkupOptional. Inline keyboard attached to the message
      input_message_contentInputMessageContentOptional. Content of the message to be sent instead of the photo
      +

      InlineQueryResultCachedGif

      +

      Represents a link to an animated GIF file stored on the Telegram servers. By default, this animated GIF file will be sent by the user with an optional caption. Alternatively, you can use input_message_content to send a message with specified content instead of the animation.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringType of the result, must be gif
      idStringUnique identifier for this result, 1-64 bytes
      gif_file_idStringA valid file identifier for the GIF file
      titleStringOptional. Title for the result
      captionStringOptional. Caption of the GIF file to be sent, 0-1024 characters after entities parsing
      parse_modeStringOptional. Mode for parsing entities in the caption. See formatting options for more details.
      caption_entitiesArray of MessageEntityOptional. List of special entities that appear in the caption, which can be specified instead of parse_mode
      show_caption_above_mediaBooleanOptional. Pass True, if the caption must be shown above the message media
      reply_markupInlineKeyboardMarkupOptional. Inline keyboard attached to the message
      input_message_contentInputMessageContentOptional. Content of the message to be sent instead of the GIF animation
      +

      InlineQueryResultCachedMpeg4Gif

      +

      Represents a link to a video animation (H.264/MPEG-4 AVC video without sound) stored on the Telegram servers. By default, this animated MPEG-4 file will be sent by the user with an optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the animation.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringType of the result, must be mpeg4_gif
      idStringUnique identifier for this result, 1-64 bytes
      mpeg4_file_idStringA valid file identifier for the MPEG4 file
      titleStringOptional. Title for the result
      captionStringOptional. Caption of the MPEG-4 file to be sent, 0-1024 characters after entities parsing
      parse_modeStringOptional. Mode for parsing entities in the caption. See formatting options for more details.
      caption_entitiesArray of MessageEntityOptional. List of special entities that appear in the caption, which can be specified instead of parse_mode
      show_caption_above_mediaBooleanOptional. Pass True, if the caption must be shown above the message media
      reply_markupInlineKeyboardMarkupOptional. Inline keyboard attached to the message
      input_message_contentInputMessageContentOptional. Content of the message to be sent instead of the video animation
      +

      InlineQueryResultCachedSticker

      +

      Represents a link to a sticker stored on the Telegram servers. By default, this sticker will be sent by the user. Alternatively, you can use input_message_content to send a message with the specified content instead of the sticker.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringType of the result, must be sticker
      idStringUnique identifier for this result, 1-64 bytes
      sticker_file_idStringA valid file identifier of the sticker
      reply_markupInlineKeyboardMarkupOptional. Inline keyboard attached to the message
      input_message_contentInputMessageContentOptional. Content of the message to be sent instead of the sticker
      +

      InlineQueryResultCachedDocument

      +

      Represents a link to a file stored on the Telegram servers. By default, this file will be sent by the user with an optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the file.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringType of the result, must be document
      idStringUnique identifier for this result, 1-64 bytes
      titleStringTitle for the result
      document_file_idStringA valid file identifier for the file
      descriptionStringOptional. Short description of the result
      captionStringOptional. Caption of the document to be sent, 0-1024 characters after entities parsing
      parse_modeStringOptional. Mode for parsing entities in the document caption. See formatting options for more details.
      caption_entitiesArray of MessageEntityOptional. List of special entities that appear in the caption, which can be specified instead of parse_mode
      reply_markupInlineKeyboardMarkupOptional. Inline keyboard attached to the message
      input_message_contentInputMessageContentOptional. Content of the message to be sent instead of the file
      +

      InlineQueryResultCachedVideo

      +

      Represents a link to a video file stored on the Telegram servers. By default, this video file will be sent by the user with an optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the video.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringType of the result, must be video
      idStringUnique identifier for this result, 1-64 bytes
      video_file_idStringA valid file identifier for the video file
      titleStringTitle for the result
      descriptionStringOptional. Short description of the result
      captionStringOptional. Caption of the video to be sent, 0-1024 characters after entities parsing
      parse_modeStringOptional. Mode for parsing entities in the video caption. See formatting options for more details.
      caption_entitiesArray of MessageEntityOptional. List of special entities that appear in the caption, which can be specified instead of parse_mode
      show_caption_above_mediaBooleanOptional. Pass True, if the caption must be shown above the message media
      reply_markupInlineKeyboardMarkupOptional. Inline keyboard attached to the message
      input_message_contentInputMessageContentOptional. Content of the message to be sent instead of the video
      +

      InlineQueryResultCachedVoice

      +

      Represents a link to a voice message stored on the Telegram servers. By default, this voice message will be sent by the user. Alternatively, you can use input_message_content to send a message with the specified content instead of the voice message.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringType of the result, must be voice
      idStringUnique identifier for this result, 1-64 bytes
      voice_file_idStringA valid file identifier for the voice message
      titleStringVoice message title
      captionStringOptional. Caption, 0-1024 characters after entities parsing
      parse_modeStringOptional. Mode for parsing entities in the voice message caption. See formatting options for more details.
      caption_entitiesArray of MessageEntityOptional. List of special entities that appear in the caption, which can be specified instead of parse_mode
      reply_markupInlineKeyboardMarkupOptional. Inline keyboard attached to the message
      input_message_contentInputMessageContentOptional. Content of the message to be sent instead of the voice message
      +

      InlineQueryResultCachedAudio

      +

      Represents a link to an MP3 audio file stored on the Telegram servers. By default, this audio file will be sent by the user. Alternatively, you can use input_message_content to send a message with the specified content instead of the audio.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringType of the result, must be audio
      idStringUnique identifier for this result, 1-64 bytes
      audio_file_idStringA valid file identifier for the audio file
      captionStringOptional. Caption, 0-1024 characters after entities parsing
      parse_modeStringOptional. Mode for parsing entities in the audio caption. See formatting options for more details.
      caption_entitiesArray of MessageEntityOptional. List of special entities that appear in the caption, which can be specified instead of parse_mode
      reply_markupInlineKeyboardMarkupOptional. Inline keyboard attached to the message
      input_message_contentInputMessageContentOptional. Content of the message to be sent instead of the audio
      +

      InputMessageContent

      +

      This object represents the content of a message to be sent as a result of an inline query. Telegram clients currently support the following 5 types:

      + +

      InputTextMessageContent

      +

      Represents the content of a text message to be sent as the result of an inline query.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      message_textStringText of the message to be sent, 1-4096 characters
      parse_modeStringOptional. Mode for parsing entities in the message text. See formatting options for more details.
      entitiesArray of MessageEntityOptional. List of special entities that appear in message text, which can be specified instead of parse_mode
      link_preview_optionsLinkPreviewOptionsOptional. Link preview generation options for the message
      +

      InputLocationMessageContent

      +

      Represents the content of a location message to be sent as the result of an inline query.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      latitudeFloatLatitude of the location in degrees
      longitudeFloatLongitude of the location in degrees
      horizontal_accuracyFloatOptional. The radius of uncertainty for the location, measured in meters; 0-1500
      live_periodIntegerOptional. Period in seconds during which the location can be updated, should be between 60 and 86400, or 0x7FFFFFFF for live locations that can be edited indefinitely.
      headingIntegerOptional. For live locations, a direction in which the user is moving, in degrees. Must be between 1 and 360 if specified.
      proximity_alert_radiusIntegerOptional. For live locations, a maximum distance for proximity alerts about approaching another chat member, in meters. Must be between 1 and 100000 if specified.
      +

      InputVenueMessageContent

      +

      Represents the content of a venue message to be sent as the result of an inline query.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      latitudeFloatLatitude of the venue in degrees
      longitudeFloatLongitude of the venue in degrees
      titleStringName of the venue
      addressStringAddress of the venue
      foursquare_idStringOptional. Foursquare identifier of the venue, if known
      foursquare_typeStringOptional. Foursquare type of the venue, if known. (For example, “arts_entertainment/default”, “arts_entertainment/aquarium” or “food/icecream”.)
      google_place_idStringOptional. Google Places identifier of the venue
      google_place_typeStringOptional. Google Places type of the venue. (See supported types.)
      +

      InputContactMessageContent

      +

      Represents the content of a contact message to be sent as the result of an inline query.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      phone_numberStringContact's phone number
      first_nameStringContact's first name
      last_nameStringOptional. Contact's last name
      vcardStringOptional. Additional data about the contact in the form of a vCard, 0-2048 bytes
      +

      InputInvoiceMessageContent

      +

      Represents the content of an invoice message to be sent as the result of an inline query.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      titleStringProduct name, 1-32 characters
      descriptionStringProduct description, 1-255 characters
      payloadStringBot-defined invoice payload, 1-128 bytes. This will not be displayed to the user, use it for your internal processes.
      provider_tokenStringOptional. Payment provider token, obtained via @BotFather. Pass an empty string for payments in Telegram Stars.
      currencyStringThree-letter ISO 4217 currency code, see more on currencies. Pass “XTR” for payments in Telegram Stars.
      pricesArray of LabeledPricePrice breakdown, a JSON-serialized list of components (e.g. product price, tax, discount, delivery cost, delivery tax, bonus, etc.). Must contain exactly one item for payments in Telegram Stars.
      max_tip_amountIntegerOptional. The maximum accepted amount for tips in the smallest units of the currency (integer, not float/double). For example, for a maximum tip of US$ 1.45 pass max_tip_amount = 145. See the exp parameter in currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies). Defaults to 0. Not supported for payments in Telegram Stars.
      suggested_tip_amountsArray of IntegerOptional. A JSON-serialized array of suggested amounts of tip in the smallest units of the currency (integer, not float/double). At most 4 suggested tip amounts can be specified. The suggested tip amounts must be positive, passed in a strictly increased order and must not exceed max_tip_amount.
      provider_dataStringOptional. A JSON-serialized object for data about the invoice, which will be shared with the payment provider. A detailed description of the required fields should be provided by the payment provider.
      photo_urlStringOptional. URL of the product photo for the invoice. Can be a photo of the goods or a marketing image for a service.
      photo_sizeIntegerOptional. Photo size in bytes
      photo_widthIntegerOptional. Photo width
      photo_heightIntegerOptional. Photo height
      need_nameBooleanOptional. Pass True if you require the user's full name to complete the order. Ignored for payments in Telegram Stars.
      need_phone_numberBooleanOptional. Pass True if you require the user's phone number to complete the order. Ignored for payments in Telegram Stars.
      need_emailBooleanOptional. Pass True if you require the user's email address to complete the order. Ignored for payments in Telegram Stars.
      need_shipping_addressBooleanOptional. Pass True if you require the user's shipping address to complete the order. Ignored for payments in Telegram Stars.
      send_phone_number_to_providerBooleanOptional. Pass True if the user's phone number should be sent to the provider. Ignored for payments in Telegram Stars.
      send_email_to_providerBooleanOptional. Pass True if the user's email address should be sent to the provider. Ignored for payments in Telegram Stars.
      is_flexibleBooleanOptional. Pass True if the final price depends on the shipping method. Ignored for payments in Telegram Stars.
      +

      ChosenInlineResult

      +

      Represents a result of an inline query that was chosen by the user and sent to their chat partner.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      result_idStringThe unique identifier for the result that was chosen
      fromUserThe user that chose the result
      locationLocationOptional. Sender location, only for bots that require user location
      inline_message_idStringOptional. Identifier of the sent inline message. Available only if there is an inline keyboard attached to the message. Will be also received in callback queries and can be used to edit the message.
      queryStringThe query that was used to obtain the result
      +

      Note: It is necessary to enable inline feedback via @BotFather in order to receive these objects in updates.

      +

      Payments

      +

      Your bot can accept payments from Telegram users. Please see the introduction to payments for more details on the process and how to set up payments for your bot.

      +

      sendInvoice

      +

      Use this method to send invoices. On success, the sent Message is returned.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      chat_idInteger or StringYesUnique identifier for the target chat or username of the target bot, supergroup or channel in the format @username
      message_thread_idIntegerOptionalUnique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only
      direct_messages_topic_idIntegerOptionalIdentifier of the direct messages topic to which the message will be sent; required if the message is sent to a direct messages chat
      titleStringYesProduct name, 1-32 characters
      descriptionStringYesProduct description, 1-255 characters
      payloadStringYesBot-defined invoice payload, 1-128 bytes. This will not be displayed to the user, use it for your internal processes.
      provider_tokenStringOptionalPayment provider token, obtained via @BotFather. Pass an empty string for payments in Telegram Stars.
      currencyStringYesThree-letter ISO 4217 currency code, see more on currencies. Pass “XTR” for payments in Telegram Stars.
      pricesArray of LabeledPriceYesPrice breakdown, a JSON-serialized list of components (e.g. product price, tax, discount, delivery cost, delivery tax, bonus, etc.). Must contain exactly one item for payments in Telegram Stars.
      max_tip_amountIntegerOptionalThe maximum accepted amount for tips in the smallest units of the currency (integer, not float/double). For example, for a maximum tip of US$ 1.45 pass max_tip_amount = 145. See the exp parameter in currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies). Defaults to 0. Not supported for payments in Telegram Stars.
      suggested_tip_amountsArray of IntegerOptionalA JSON-serialized array of suggested amounts of tips in the smallest units of the currency (integer, not float/double). At most 4 suggested tip amounts can be specified. The suggested tip amounts must be positive, passed in a strictly increased order and must not exceed max_tip_amount.
      start_parameterStringOptionalUnique deep-linking parameter. If left empty, forwarded copies of the sent message will have a Pay button, allowing multiple users to pay directly from the forwarded message, using the same invoice. If non-empty, forwarded copies of the sent message will have a URL button with a deep link to the bot (instead of a Pay button), with the value used as the start parameter
      provider_dataStringOptionalJSON-serialized data about the invoice, which will be shared with the payment provider. A detailed description of required fields should be provided by the payment provider.
      photo_urlStringOptionalURL of the product photo for the invoice. Can be a photo of the goods or a marketing image for a service. People like it better when they see what they are paying for.
      photo_sizeIntegerOptionalPhoto size in bytes
      photo_widthIntegerOptionalPhoto width
      photo_heightIntegerOptionalPhoto height
      need_nameBooleanOptionalPass True if you require the user's full name to complete the order. Ignored for payments in Telegram Stars.
      need_phone_numberBooleanOptionalPass True if you require the user's phone number to complete the order. Ignored for payments in Telegram Stars.
      need_emailBooleanOptionalPass True if you require the user's email address to complete the order. Ignored for payments in Telegram Stars.
      need_shipping_addressBooleanOptionalPass True if you require the user's shipping address to complete the order. Ignored for payments in Telegram Stars.
      send_phone_number_to_providerBooleanOptionalPass True if the user's phone number should be sent to the provider. Ignored for payments in Telegram Stars.
      send_email_to_providerBooleanOptionalPass True if the user's email address should be sent to the provider. Ignored for payments in Telegram Stars.
      is_flexibleBooleanOptionalPass True if the final price depends on the shipping method. Ignored for payments in Telegram Stars.
      disable_notificationBooleanOptionalSends the message silently. Users will receive a notification with no sound.
      protect_contentBooleanOptionalProtects the contents of the sent message from forwarding and saving
      allow_paid_broadcastBooleanOptionalPass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance.
      message_effect_idStringOptionalUnique identifier of the message effect to be added to the message; for private chats only
      suggested_post_parametersSuggestedPostParametersOptionalA JSON-serialized object containing the parameters of the suggested post to send; for direct messages chats only. If the message is sent as a reply to another suggested post, then that suggested post is automatically declined.
      reply_parametersReplyParametersOptionalDescription of the message to reply to
      reply_markupInlineKeyboardMarkupOptionalA JSON-serialized object for an inline keyboard. If empty, one 'Pay total price' button will be shown. If not empty, the first button must be a Pay button.
      +

      createInvoiceLink

      +

      Use this method to create a link for an invoice. Returns the created invoice link as String on success.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      business_connection_idStringOptionalUnique identifier of the business connection on behalf of which the link will be created. For payments in Telegram Stars only.
      titleStringYesProduct name, 1-32 characters
      descriptionStringYesProduct description, 1-255 characters
      payloadStringYesBot-defined invoice payload, 1-128 bytes. This will not be displayed to the user, use it for your internal processes.
      provider_tokenStringOptionalPayment provider token, obtained via @BotFather. Pass an empty string for payments in Telegram Stars.
      currencyStringYesThree-letter ISO 4217 currency code, see more on currencies. Pass “XTR” for payments in Telegram Stars.
      pricesArray of LabeledPriceYesPrice breakdown, a JSON-serialized list of components (e.g. product price, tax, discount, delivery cost, delivery tax, bonus, etc.). Must contain exactly one item for payments in Telegram Stars.
      subscription_periodIntegerOptionalThe number of seconds the subscription will be active for before the next payment. The currency must be set to “XTR” (Telegram Stars) if the parameter is used. Currently, it must always be 2592000 (30 days) if specified. Any number of subscriptions can be active for a given bot at the same time, including multiple concurrent subscriptions from the same user. Subscription price must no exceed 10000 Telegram Stars.
      max_tip_amountIntegerOptionalThe maximum accepted amount for tips in the smallest units of the currency (integer, not float/double). For example, for a maximum tip of US$ 1.45 pass max_tip_amount = 145. See the exp parameter in currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies). Defaults to 0. Not supported for payments in Telegram Stars.
      suggested_tip_amountsArray of IntegerOptionalA JSON-serialized array of suggested amounts of tips in the smallest units of the currency (integer, not float/double). At most 4 suggested tip amounts can be specified. The suggested tip amounts must be positive, passed in a strictly increased order and must not exceed max_tip_amount.
      provider_dataStringOptionalJSON-serialized data about the invoice, which will be shared with the payment provider. A detailed description of required fields should be provided by the payment provider.
      photo_urlStringOptionalURL of the product photo for the invoice. Can be a photo of the goods or a marketing image for a service.
      photo_sizeIntegerOptionalPhoto size in bytes
      photo_widthIntegerOptionalPhoto width
      photo_heightIntegerOptionalPhoto height
      need_nameBooleanOptionalPass True if you require the user's full name to complete the order. Ignored for payments in Telegram Stars.
      need_phone_numberBooleanOptionalPass True if you require the user's phone number to complete the order. Ignored for payments in Telegram Stars.
      need_emailBooleanOptionalPass True if you require the user's email address to complete the order. Ignored for payments in Telegram Stars.
      need_shipping_addressBooleanOptionalPass True if you require the user's shipping address to complete the order. Ignored for payments in Telegram Stars.
      send_phone_number_to_providerBooleanOptionalPass True if the user's phone number should be sent to the provider. Ignored for payments in Telegram Stars.
      send_email_to_providerBooleanOptionalPass True if the user's email address should be sent to the provider. Ignored for payments in Telegram Stars.
      is_flexibleBooleanOptionalPass True if the final price depends on the shipping method. Ignored for payments in Telegram Stars.
      +

      answerShippingQuery

      +

      If you sent an invoice requesting a shipping address and the parameter is_flexible was specified, the Bot API will send an Update with a shipping_query field to the bot. Use this method to reply to shipping queries. On success, True is returned.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      shipping_query_idStringYesUnique identifier for the query to be answered
      okBooleanYesPass True if delivery to the specified address is possible and False if there are any problems (for example, if delivery to the specified address is not possible)
      shipping_optionsArray of ShippingOptionOptionalRequired if ok is True. A JSON-serialized array of available shipping options.
      error_messageStringOptionalRequired if ok is False. Error message in human readable form that explains why it is impossible to complete the order (e.g. “Sorry, delivery to your desired address is unavailable”). Telegram will display this message to the user.
      +

      answerPreCheckoutQuery

      +

      Once the user has confirmed their payment and shipping details, the Bot API sends the final confirmation in the form of an Update with the field pre_checkout_query. Use this method to respond to such pre-checkout queries. On success, True is returned. Note: The Bot API must receive an answer within 10 seconds after the pre-checkout query was sent.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      pre_checkout_query_idStringYesUnique identifier for the query to be answered
      okBooleanYesSpecify True if everything is alright (goods are available, etc.) and the bot is ready to proceed with the order. Use False if there are any problems.
      error_messageStringOptionalRequired if ok is False. Error message in human readable form that explains the reason for failure to proceed with the checkout (e.g. "Sorry, somebody just bought the last of our amazing black T-shirts while you were busy filling out your payment details. Please choose a different color or garment!"). Telegram will display this message to the user.
      +

      getMyStarBalance

      +

      A method to get the current Telegram Stars balance of the bot. Requires no parameters. On success, returns a StarAmount object.

      +

      getStarTransactions

      +

      Returns the bot's Telegram Star transactions in chronological order. On success, returns a StarTransactions object.

      + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      offsetIntegerOptionalNumber of transactions to skip in the response
      limitIntegerOptionalThe maximum number of transactions to be retrieved. Values between 1-100 are accepted. Defaults to 100.
      +

      refundStarPayment

      +

      Refunds a successful payment in Telegram Stars. Returns True on success.

      + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      user_idIntegerYesIdentifier of the user whose payment will be refunded
      telegram_payment_charge_idStringYesTelegram payment identifier
      +

      editUserStarSubscription

      +

      Allows the bot to cancel or re-enable extension of a subscription paid in Telegram Stars. Returns True on success.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      user_idIntegerYesIdentifier of the user whose subscription will be edited
      telegram_payment_charge_idStringYesTelegram payment identifier for the subscription
      is_canceledBooleanYesPass True to cancel extension of the user subscription; the subscription must be active up to the end of the current subscription period. Pass False to allow the user to re-enable a subscription that was previously canceled by the bot.
      +

      LabeledPrice

      +

      This object represents a portion of the price for goods or services.

      + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      labelStringPortion label
      amountIntegerPrice of the product in the smallest units of the currency (integer, not float/double). For example, for a price of US$ 1.45 pass amount = 145. See the exp parameter in currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies).
      +

      Invoice

      +

      This object contains basic information about an invoice.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      titleStringProduct name
      descriptionStringProduct description
      start_parameterStringUnique bot deep-linking parameter that can be used to generate this invoice
      currencyStringThree-letter ISO 4217 currency code, or “XTR” for payments in Telegram Stars
      total_amountIntegerTotal price in the smallest units of the currency (integer, not float/double). For example, for a price of US$ 1.45 pass amount = 145. See the exp parameter in currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies).
      +

      ShippingAddress

      +

      This object represents a shipping address.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      country_codeStringTwo-letter ISO 3166-1 alpha-2 country code
      stateStringState, if applicable
      cityStringCity
      street_line1StringFirst line for the address
      street_line2StringSecond line for the address
      post_codeStringAddress post code
      +

      OrderInfo

      +

      This object represents information about an order.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      nameStringOptional. User name
      phone_numberStringOptional. User's phone number
      emailStringOptional. User email
      shipping_addressShippingAddressOptional. User shipping address
      +

      ShippingOption

      +

      This object represents one shipping option.

      + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      idStringShipping option identifier
      titleStringOption title
      pricesArray of LabeledPriceList of price portions
      +

      SuccessfulPayment

      +

      This object contains basic information about a successful payment. Note that if the buyer initiates a chargeback with the relevant payment provider following this transaction, the funds may be debited from your balance. This is outside of Telegram's control.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      currencyStringThree-letter ISO 4217 currency code, or “XTR” for payments in Telegram Stars
      total_amountIntegerTotal price in the smallest units of the currency (integer, not float/double). For example, for a price of US$ 1.45 pass amount = 145. See the exp parameter in currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies).
      invoice_payloadStringBot-specified invoice payload
      subscription_expiration_dateIntegerOptional. Expiration date of the subscription, in Unix time; for recurring payments only
      is_recurringTrueOptional. True, if the payment is a recurring payment for a subscription
      is_first_recurringTrueOptional. True, if the payment is the first payment for a subscription
      shipping_option_idStringOptional. Identifier of the shipping option chosen by the user
      order_infoOrderInfoOptional. Order information provided by the user
      telegram_payment_charge_idStringTelegram payment identifier
      provider_payment_charge_idStringProvider payment identifier
      +

      RefundedPayment

      +

      This object contains basic information about a refunded payment.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      currencyStringThree-letter ISO 4217 currency code, or “XTR” for payments in Telegram Stars. Currently, always “XTR”
      total_amountIntegerTotal refunded price in the smallest units of the currency (integer, not float/double). For example, for a price of US$ 1.45, total_amount = 145. See the exp parameter in currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies).
      invoice_payloadStringBot-specified invoice payload
      telegram_payment_charge_idStringTelegram payment identifier
      provider_payment_charge_idStringOptional. Provider payment identifier
      +

      ShippingQuery

      +

      This object contains information about an incoming shipping query.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      idStringUnique query identifier
      fromUserUser who sent the query
      invoice_payloadStringBot-specified invoice payload
      shipping_addressShippingAddressUser specified shipping address
      +

      PreCheckoutQuery

      +

      This object contains information about an incoming pre-checkout query.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      idStringUnique query identifier
      fromUserUser who sent the query
      currencyStringThree-letter ISO 4217 currency code, or “XTR” for payments in Telegram Stars
      total_amountIntegerTotal price in the smallest units of the currency (integer, not float/double). For example, for a price of US$ 1.45 pass amount = 145. See the exp parameter in currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies).
      invoice_payloadStringBot-specified invoice payload
      shipping_option_idStringOptional. Identifier of the shipping option chosen by the user
      order_infoOrderInfoOptional. Order information provided by the user
      +

      PaidMediaPurchased

      +

      This object contains information about a paid media purchase.

      + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      fromUserUser who purchased the media
      paid_media_payloadStringBot-specified paid media payload
      +

      RevenueWithdrawalState

      +

      This object describes the state of a revenue withdrawal operation. Currently, it can be one of

      + +

      RevenueWithdrawalStatePending

      +

      The withdrawal is in progress.

      + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringType of the state, always “pending”
      +

      RevenueWithdrawalStateSucceeded

      +

      The withdrawal succeeded.

      + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringType of the state, always “succeeded”
      dateIntegerDate the withdrawal was completed in Unix time
      urlStringAn HTTPS URL that can be used to see transaction details
      +

      RevenueWithdrawalStateFailed

      +

      The withdrawal failed and the transaction was refunded.

      + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringType of the state, always “failed”
      +

      AffiliateInfo

      +

      Contains information about the affiliate that received a commission via this transaction.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      affiliate_userUserOptional. The bot or the user that received an affiliate commission if it was received by a bot or a user
      affiliate_chatChatOptional. The chat that received an affiliate commission if it was received by a chat
      commission_per_milleIntegerThe number of Telegram Stars received by the affiliate for each 1000 Telegram Stars received by the bot from referred users
      amountIntegerInteger amount of Telegram Stars received by the affiliate from the transaction, rounded to 0; can be negative for refunds
      nanostar_amountIntegerOptional. The number of 1/1000000000 shares of Telegram Stars received by the affiliate; from -999999999 to 999999999; can be negative for refunds
      +

      TransactionPartner

      +

      This object describes the source of a transaction, or its recipient for outgoing transactions. Currently, it can be one of

      + +

      TransactionPartnerUser

      +

      Describes a transaction with a user.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringType of the transaction partner, always “user”
      transaction_typeStringType of the transaction, currently one of “invoice_payment” for payments via invoices, “paid_media_payment” for payments for paid media, “gift_purchase” for gifts sent by the bot, “premium_purchase” for Telegram Premium subscriptions gifted by the bot, “business_account_transfer” for direct transfers from managed business accounts
      userUserInformation about the user
      affiliateAffiliateInfoOptional. Information about the affiliate that received a commission via this transaction. Can be available only for “invoice_payment” and “paid_media_payment” transactions.
      invoice_payloadStringOptional. Bot-specified invoice payload. Can be available only for “invoice_payment” transactions.
      subscription_periodIntegerOptional. The duration of the paid subscription. Can be available only for “invoice_payment” transactions.
      paid_mediaArray of PaidMediaOptional. Information about the paid media bought by the user; for “paid_media_payment” transactions only
      paid_media_payloadStringOptional. Bot-specified paid media payload. Can be available only for “paid_media_payment” transactions.
      giftGiftOptional. The gift sent to the user by the bot; for “gift_purchase” transactions only
      premium_subscription_durationIntegerOptional. Number of months the gifted Telegram Premium subscription will be active for; for “premium_purchase” transactions only
      +

      TransactionPartnerChat

      +

      Describes a transaction with a chat.

      + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringType of the transaction partner, always “chat”
      chatChatInformation about the chat
      giftGiftOptional. The gift sent to the chat by the bot
      +

      TransactionPartnerAffiliateProgram

      +

      Describes the affiliate program that issued the affiliate commission received via this transaction.

      + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringType of the transaction partner, always “affiliate_program”
      sponsor_userUserOptional. Information about the bot that sponsored the affiliate program
      commission_per_milleIntegerThe number of Telegram Stars received by the bot for each 1000 Telegram Stars received by the affiliate program sponsor from referred users
      +

      TransactionPartnerFragment

      +

      Describes a withdrawal transaction with Fragment.

      + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringType of the transaction partner, always “fragment”
      withdrawal_stateRevenueWithdrawalStateOptional. State of the transaction if the transaction is outgoing
      +

      TransactionPartnerTelegramAds

      +

      Describes a withdrawal transaction to the Telegram Ads platform.

      + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringType of the transaction partner, always “telegram_ads”
      +

      TransactionPartnerTelegramApi

      +

      Describes a transaction with payment for paid broadcasting.

      + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringType of the transaction partner, always “telegram_api”
      request_countIntegerThe number of successful requests that exceeded regular limits and were therefore billed
      +

      TransactionPartnerOther

      +

      Describes a transaction with an unknown source or recipient.

      + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringType of the transaction partner, always “other”
      +

      StarTransaction

      +

      Describes a Telegram Star transaction. Note that if the buyer initiates a chargeback with the payment provider from whom they acquired Stars (e.g., Apple, Google) following this transaction, the refunded Stars will be deducted from the bot's balance. This is outside of Telegram's control.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      idStringUnique identifier of the transaction. Coincides with the identifier of the original transaction for refund transactions. Coincides with SuccessfulPayment.telegram_payment_charge_id for successful incoming payments from users.
      amountIntegerInteger amount of Telegram Stars transferred by the transaction
      nanostar_amountIntegerOptional. The number of 1/1000000000 shares of Telegram Stars transferred by the transaction; from 0 to 999999999
      dateIntegerDate the transaction was created in Unix time
      sourceTransactionPartnerOptional. Source of an incoming transaction (e.g., a user purchasing goods or services, Fragment refunding a failed withdrawal). Only for incoming transactions
      receiverTransactionPartnerOptional. Receiver of an outgoing transaction (e.g., a user for a purchase refund, Fragment for a withdrawal). Only for outgoing transactions
      +

      StarTransactions

      +

      Contains a list of Telegram Star transactions.

      + + + + + + + + + + + + + + + +
      FieldTypeDescription
      transactionsArray of StarTransactionThe list of transactions
      +

      Telegram Passport

      +

      Telegram Passport is a unified authorization method for services that require personal identification. Users can upload their documents once, then instantly share their data with services that require real-world ID (finance, ICOs, etc.). Please see the manual for details.

      +

      PassportData

      +

      Describes Telegram Passport data shared with the bot by the user.

      + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      dataArray of EncryptedPassportElementArray with information about documents and other Telegram Passport elements that was shared with the bot
      credentialsEncryptedCredentialsEncrypted credentials required to decrypt the data
      +

      PassportFile

      +

      This object represents a file uploaded to Telegram Passport. Currently all Telegram Passport files are in JPEG format when decrypted and don't exceed 10MB.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      file_idStringIdentifier for this file, which can be used to download or reuse the file
      file_unique_idStringUnique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file.
      file_sizeIntegerFile size in bytes
      file_dateIntegerUnix time when the file was uploaded
      +

      EncryptedPassportElement

      +

      Describes documents or other Telegram Passport elements shared with the bot by the user.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      typeStringElement type. One of “personal_details”, “passport”, “driver_license”, “identity_card”, “internal_passport”, “address”, “utility_bill”, “bank_statement”, “rental_agreement”, “passport_registration”, “temporary_registration”, “phone_number”, “email”.
      dataStringOptional. Base64-encoded encrypted Telegram Passport element data provided by the user; available only for “personal_details”, “passport”, “driver_license”, “identity_card”, “internal_passport” and “address” types. Can be decrypted and verified using the accompanying EncryptedCredentials.
      phone_numberStringOptional. User's verified phone number; available only for “phone_number” type
      emailStringOptional. User's verified email address; available only for “email” type
      filesArray of PassportFileOptional. Array of encrypted files with documents provided by the user; available only for “utility_bill”, “bank_statement”, “rental_agreement”, “passport_registration” and “temporary_registration” types. Files can be decrypted and verified using the accompanying EncryptedCredentials.
      front_sidePassportFileOptional. Encrypted file with the front side of the document, provided by the user; available only for “passport”, “driver_license”, “identity_card” and “internal_passport”. The file can be decrypted and verified using the accompanying EncryptedCredentials.
      reverse_sidePassportFileOptional. Encrypted file with the reverse side of the document, provided by the user; available only for “driver_license” and “identity_card”. The file can be decrypted and verified using the accompanying EncryptedCredentials.
      selfiePassportFileOptional. Encrypted file with the selfie of the user holding a document, provided by the user; available if requested for “passport”, “driver_license”, “identity_card” and “internal_passport”. The file can be decrypted and verified using the accompanying EncryptedCredentials.
      translationArray of PassportFileOptional. Array of encrypted files with translated versions of documents provided by the user; available if requested for “passport”, “driver_license”, “identity_card”, “internal_passport”, “utility_bill”, “bank_statement”, “rental_agreement”, “passport_registration” and “temporary_registration” types. Files can be decrypted and verified using the accompanying EncryptedCredentials.
      hashStringBase64-encoded element hash for using in PassportElementErrorUnspecified
      +

      EncryptedCredentials

      +

      Describes data required for decrypting and authenticating EncryptedPassportElement. See the Telegram Passport Documentation for a complete description of the data decryption and authentication processes.

      + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      dataStringBase64-encoded encrypted JSON-serialized data with unique user's payload, data hashes and secrets required for EncryptedPassportElement decryption and authentication
      hashStringBase64-encoded data hash for data authentication
      secretStringBase64-encoded secret, encrypted with the bot's public RSA key, required for data decryption
      +

      setPassportDataErrors

      +

      Informs a user that some of the Telegram Passport elements they provided contains errors. The user will not be able to re-submit their Passport to you until the errors are fixed (the contents of the field for which you returned the error must change). Returns True on success.

      +

      Use this if the data submitted by the user doesn't satisfy the standards your service requires for any reason. For example, if a birthday date seems invalid, a submitted document is blurry, a scan shows evidence of tampering, etc. Supply some details in the error message to make sure the user knows how to correct the issues.

      + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      user_idIntegerYesUser identifier
      errorsArray of PassportElementErrorYesA JSON-serialized array describing the errors
      +

      PassportElementError

      +

      This object represents an error in the Telegram Passport element which was submitted that should be resolved by the user. It should be one of:

      + +

      PassportElementErrorDataField

      +

      Represents an issue in one of the data fields that was provided by the user. The error is considered resolved when the field's value changes.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      sourceStringError source, must be data
      typeStringThe section of the user's Telegram Passport which has the error, one of “personal_details”, “passport”, “driver_license”, “identity_card”, “internal_passport”, “address”
      field_nameStringName of the data field which has the error
      data_hashStringBase64-encoded data hash
      messageStringError message
      +

      PassportElementErrorFrontSide

      +

      Represents an issue with the front side of a document. The error is considered resolved when the file with the front side of the document changes.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      sourceStringError source, must be front_side
      typeStringThe section of the user's Telegram Passport which has the issue, one of “passport”, “driver_license”, “identity_card”, “internal_passport”
      file_hashStringBase64-encoded hash of the file with the front side of the document
      messageStringError message
      +

      PassportElementErrorReverseSide

      +

      Represents an issue with the reverse side of a document. The error is considered resolved when the file with reverse side of the document changes.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      sourceStringError source, must be reverse_side
      typeStringThe section of the user's Telegram Passport which has the issue, one of “driver_license”, “identity_card”
      file_hashStringBase64-encoded hash of the file with the reverse side of the document
      messageStringError message
      +

      PassportElementErrorSelfie

      +

      Represents an issue with the selfie with a document. The error is considered resolved when the file with the selfie changes.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      sourceStringError source, must be selfie
      typeStringThe section of the user's Telegram Passport which has the issue, one of “passport”, “driver_license”, “identity_card”, “internal_passport”
      file_hashStringBase64-encoded hash of the file with the selfie
      messageStringError message
      +

      PassportElementErrorFile

      +

      Represents an issue with a document scan. The error is considered resolved when the file with the document scan changes.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      sourceStringError source, must be file
      typeStringThe section of the user's Telegram Passport which has the issue, one of “utility_bill”, “bank_statement”, “rental_agreement”, “passport_registration”, “temporary_registration”
      file_hashStringBase64-encoded file hash
      messageStringError message
      +

      PassportElementErrorFiles

      +

      Represents an issue with a list of scans. The error is considered resolved when the list of files containing the scans changes.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      sourceStringError source, must be files
      typeStringThe section of the user's Telegram Passport which has the issue, one of “utility_bill”, “bank_statement”, “rental_agreement”, “passport_registration”, “temporary_registration”
      file_hashesArray of StringList of base64-encoded file hashes
      messageStringError message
      +

      PassportElementErrorTranslationFile

      +

      Represents an issue with one of the files that constitute the translation of a document. The error is considered resolved when the file changes.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      sourceStringError source, must be translation_file
      typeStringType of element of the user's Telegram Passport which has the issue, one of “passport”, “driver_license”, “identity_card”, “internal_passport”, “utility_bill”, “bank_statement”, “rental_agreement”, “passport_registration”, “temporary_registration”
      file_hashStringBase64-encoded file hash
      messageStringError message
      +

      PassportElementErrorTranslationFiles

      +

      Represents an issue with the translated version of a document. The error is considered resolved when a file with the document translation change.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      sourceStringError source, must be translation_files
      typeStringType of element of the user's Telegram Passport which has the issue, one of “passport”, “driver_license”, “identity_card”, “internal_passport”, “utility_bill”, “bank_statement”, “rental_agreement”, “passport_registration”, “temporary_registration”
      file_hashesArray of StringList of base64-encoded file hashes
      messageStringError message
      +

      PassportElementErrorUnspecified

      +

      Represents an issue in an unspecified place. The error is considered resolved when new data is added.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      sourceStringError source, must be unspecified
      typeStringType of element of the user's Telegram Passport which has the issue
      element_hashStringBase64-encoded element hash
      messageStringError message
      +

      Games

      +

      Your bot can offer users HTML5 games to play solo or to compete against each other in groups and one-on-one chats. Create games via @BotFather using the /newgame command. Please note that this kind of power requires responsibility: you will need to accept the terms for each game that your bots will be offering.

      +
        +
      • Games are a new type of content on Telegram, represented by the Game and InlineQueryResultGame objects.
      • +
      • Once you've created a game via BotFather, you can send games to chats as regular messages using the sendGame method, or use inline mode with InlineQueryResultGame.
      • +
      • If you send the game message without any buttons, it will automatically have a 'Play GameName' button. When this button is pressed, your bot gets a CallbackQuery with the game_short_name of the requested game. You provide the correct URL for this particular user and the app opens the game in the in-app browser.
      • +
      • You can manually add multiple buttons to your game message. Please note that the first button in the first row must always launch the game, using the field callback_game in InlineKeyboardButton. You can add extra buttons according to taste: e.g., for a description of the rules, or to open the game's official community.
      • +
      • To make your game more attractive, you can upload a GIF animation that demonstrates the game to the users via BotFather (see Lumberjack for example).
      • +
      • A game message will also display high scores for the current chat. Use setGameScore to post high scores to the chat with the game, add the disable_edit_message parameter to disable automatic update of the message with the current scoreboard.
      • +
      • Use getGameHighScores to get data for in-game high score tables.
      • +
      • You can also add an extra sharing button for users to share their best score to different chats.
      • +
      • For examples of what can be done using this new stuff, check the @gamebot and @gamee bots.
      • +
      +

      sendGame

      +

      Use this method to send a game. On success, the sent Message is returned.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      business_connection_idStringOptionalUnique identifier of the business connection on behalf of which the message will be sent
      chat_idInteger or StringYesUnique identifier for the target chat or username of the target bot in the format @username. Games can't be sent to channel direct messages chats and channel chats.
      message_thread_idIntegerOptionalUnique identifier for the target message thread (topic) of a forum; for forum supergroups and private chats of bots with forum topic mode enabled only
      game_short_nameStringYesShort name of the game, serves as the unique identifier for the game. Set up your games via @BotFather.
      disable_notificationBooleanOptionalSends the message silently. Users will receive a notification with no sound.
      protect_contentBooleanOptionalProtects the contents of the sent message from forwarding and saving
      allow_paid_broadcastBooleanOptionalPass True to allow up to 1000 messages per second, ignoring broadcasting limits for a fee of 0.1 Telegram Stars per message. The relevant Stars will be withdrawn from the bot's balance.
      message_effect_idStringOptionalUnique identifier of the message effect to be added to the message; for private chats only
      reply_parametersReplyParametersOptionalDescription of the message to reply to
      reply_markupInlineKeyboardMarkupOptionalA JSON-serialized object for an inline keyboard. If empty, one 'Play game_title' button will be shown. If not empty, the first button must launch the game.
      +

      Game

      +

      This object represents a game. Use BotFather to create and edit games, their short names will act as unique identifiers.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      titleStringTitle of the game
      descriptionStringDescription of the game
      photoArray of PhotoSizePhoto that will be displayed in the game message in chats.
      textStringOptional. Brief description of the game or high scores included in the game message. Can be automatically edited to include current high scores for the game when the bot calls setGameScore, or manually edited using editMessageText. 0-4096 characters.
      text_entitiesArray of MessageEntityOptional. Special entities that appear in text, such as usernames, URLs, bot commands, etc.
      animationAnimationOptional. Animation that will be displayed in the game message in chats. Upload via BotFather
      +

      CallbackGame

      +

      A placeholder, currently holds no information. Use BotFather to set up your game.

      +

      setGameScore

      +

      Use this method to set the score of the specified user in a game message. On success, if the message is not an inline message, the Message is returned, otherwise True is returned. Returns an error, if the new score is not greater than the user's current score in the chat and force is False.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      user_idIntegerYesUser identifier
      scoreIntegerYesNew score, must be non-negative
      forceBooleanOptionalPass True if the high score is allowed to decrease. This can be useful when fixing mistakes or banning cheaters
      disable_edit_messageBooleanOptionalPass True if the game message should not be automatically edited to include the current scoreboard
      chat_idIntegerOptionalRequired if inline_message_id is not specified. Unique identifier for the target chat
      message_idIntegerOptionalRequired if inline_message_id is not specified. Identifier of the sent message
      inline_message_idStringOptionalRequired if chat_id and message_id are not specified. Identifier of the inline message
      +

      getGameHighScores

      +

      Use this method to get data for high score tables. Will return the score of the specified user and several of their neighbors in a game. Returns an Array of GameHighScore objects.

      +
      +

      This method will currently return scores for the target user, plus two of their closest neighbors on each side. Will also return the top three users if the user and their neighbors are not among them. Please note that this behavior is subject to change.

      +
      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ParameterTypeRequiredDescription
      user_idIntegerYesTarget user id
      chat_idIntegerOptionalRequired if inline_message_id is not specified. Unique identifier for the target chat
      message_idIntegerOptionalRequired if inline_message_id is not specified. Identifier of the sent message
      inline_message_idStringOptionalRequired if chat_id and message_id are not specified. Identifier of the inline message
      +

      GameHighScore

      +

      This object represents one row of the high scores table for a game.

      + + + + + + + + + + + + + + + + + + + + + + + + + +
      FieldTypeDescription
      positionIntegerPosition in high score table for the game
      userUserUser
      scoreIntegerScore
      +
      +

      And that's about all we've got for now.
      If you've got any questions, please check out our Bot FAQ »

      +
      + +
      + +
      +
      + +
      + + + + + + + + diff --git a/transport/backoff.go b/transport/backoff.go new file mode 100644 index 0000000..fe8853c --- /dev/null +++ b/transport/backoff.go @@ -0,0 +1,51 @@ +package transport + +import ( + "math" + "math/rand/v2" + "time" +) + +// BackoffStrategy returns the duration to wait before the next attempt +// after `attempt` consecutive failures (1-based). Implementations must +// be safe to call from a single goroutine. +type BackoffStrategy interface { + NextDelay(attempt int) time.Duration +} + +// ExponentialBackoff implements capped exponential back-off with jitter. +// Defaults: Base=500ms, Max=30s, Factor=2.0, Jitter=0.2. +type ExponentialBackoff struct { + Base time.Duration + Max time.Duration + Factor float64 + Jitter float64 // 0..1; fraction of computed delay added/subtracted at random +} + +// DefaultBackoff returns an ExponentialBackoff with library defaults. +func DefaultBackoff() *ExponentialBackoff { + return &ExponentialBackoff{ + Base: 500 * time.Millisecond, + Max: 30 * time.Second, + Factor: 2.0, + Jitter: 0.2, + } +} + +// NextDelay implements BackoffStrategy. +func (b *ExponentialBackoff) NextDelay(attempt int) time.Duration { + if attempt < 1 { + attempt = 1 + } + d := float64(b.Base) * math.Pow(b.Factor, float64(attempt-1)) + if b.Jitter > 0 { + d *= 1 + (rand.Float64()*2-1)*b.Jitter + } + if d > float64(b.Max) { + d = float64(b.Max) + } + if d < 0 { + d = 0 + } + return time.Duration(d) +} diff --git a/transport/backoff_test.go b/transport/backoff_test.go new file mode 100644 index 0000000..a27938c --- /dev/null +++ b/transport/backoff_test.go @@ -0,0 +1,40 @@ +package transport + +import ( + "testing" + "time" +) + +// TestExponentialBackoff_MaxCapAfterJitter verifies that the Max cap is applied +// after jitter so no delay can exceed Max regardless of jitter magnitude. +func TestExponentialBackoff_MaxCapAfterJitter(t *testing.T) { + b := &ExponentialBackoff{ + Base: 10 * time.Second, + Max: 20 * time.Second, + Factor: 2.0, + Jitter: 0.5, + } + + // Run many times to account for randomness. + for i := 0; i < 10_000; i++ { + d := b.NextDelay(10) + if d > b.Max { + t.Fatalf("attempt 10: got %v, want ≤ %v (jitter exceeded Max cap)", d, b.Max) + } + if d < 0 { + t.Fatalf("attempt 10: got negative delay %v", d) + } + } +} + +// TestExponentialBackoff_ZeroAttemptClamped ensures attempt < 1 is treated as 1. +func TestExponentialBackoff_ZeroAttemptClamped(t *testing.T) { + b := DefaultBackoff() + d0 := b.NextDelay(0) + d1 := b.NextDelay(1) + // Both should be in the same ballpark (Base ± Jitter*Base). + maxBase := float64(b.Base) * (1 + b.Jitter) + if float64(d0) > maxBase || float64(d1) > maxBase { + t.Fatalf("unexpected delay: d0=%v d1=%v maxBase=%v", d0, d1, time.Duration(maxBase)) + } +} diff --git a/transport/extra_test.go b/transport/extra_test.go new file mode 100644 index 0000000..a3e657e --- /dev/null +++ b/transport/extra_test.go @@ -0,0 +1,188 @@ +package transport + +import ( + "bytes" + "context" + "errors" + "io" + "net" + "net/http" + "strings" + "testing" + "time" + + "github.com/lukaszraczylo/go-telegram/api" + "github.com/lukaszraczylo/go-telegram/client" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" +) + +// --------------------------------------------------------------------------- +// LongPoller — unauthorized error causes immediate return +// --------------------------------------------------------------------------- + +func TestLongPoller_UnauthorizedExits(t *testing.T) { + m := &mockDoer{} + m.On("Do", mock.Anything).Return( + resp(`{"ok":false,"error_code":401,"description":"Unauthorized"}`), nil, + ).Once() + + b := client.New("bad-token", client.WithHTTPClient(m)) + p := NewLongPoller(b) + p.Timeout = 0 + + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + + err := p.Run(ctx) + require.Error(t, err) + require.True(t, errors.Is(err, client.ErrUnauthorized), "expected unauthorized: %v", err) +} + +// --------------------------------------------------------------------------- +// LongPoller — ctx cancelled while waiting for retry backoff +// --------------------------------------------------------------------------- + +func TestLongPoller_CtxCancelledDuringBackoff(t *testing.T) { + m := &mockDoer{} + var callCount int + m.On("Do", mock.Anything).Run(func(args mock.Arguments) { + callCount++ + }).Return(nil, errors.New("network error")).Maybe() + + b := client.New("t", client.WithHTTPClient(m)) + p := NewLongPoller(b) + p.Timeout = 0 + // Long backoff ensures ctx cancels before retry fires. + p.Backoff = &ExponentialBackoff{Base: 5 * time.Second, Max: 5 * time.Second, Factor: 1} + + ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) + defer cancel() + + err := p.Run(ctx) + require.Error(t, err) + // Should fail fast, not wait the full 5s backoff. + require.LessOrEqual(t, callCount, 3) +} + +// --------------------------------------------------------------------------- +// LongPoller — AllowedTypes field +// --------------------------------------------------------------------------- + +func TestLongPoller_AllowedTypes(t *testing.T) { + m := &mockDoer{} + var seenBody string + m.On("Do", mock.MatchedBy(func(r *http.Request) bool { + b, _ := io.ReadAll(r.Body) + seenBody = string(b) + return true + })).Return(resp(`{"ok":true,"result":[]}`), nil).Once() + m.On("Do", mock.Anything).Return(resp(`{"ok":true,"result":[]}`), nil).Maybe() + + b := client.New("t", client.WithHTTPClient(m)) + p := NewLongPoller(b) + p.Timeout = 0 + p.AllowedTypes = []api.UpdateType{"message", "callback_query"} + + ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) + defer cancel() + _ = p.Run(ctx) + + require.Contains(t, seenBody, "allowed_updates") +} + +// --------------------------------------------------------------------------- +// WebhookServer — ListenAndServe error (bind on in-use port) +// --------------------------------------------------------------------------- + +func TestWebhookServer_ListenAndServeError(t *testing.T) { + // Bind a port to block the webhook server. + l, err := net.Listen("tcp", "127.0.0.1:0") + require.NoError(t, err) + t.Cleanup(func() { _ = l.Close() }) + addr := l.Addr().String() + + b := client.New("t") + w := NewWebhookServer(b) + + ctx := context.Background() + err = w.ListenAndServe(ctx, addr) + require.Error(t, err, "should error when port is in use") + require.False(t, errors.Is(err, http.ErrServerClosed)) +} + +// --------------------------------------------------------------------------- +// WebhookServer — body too large (> 1 MiB) +// --------------------------------------------------------------------------- + +func TestWebhookServer_BodyTooLarge(t *testing.T) { + b := client.New("t") + w := NewWebhookServer(b) + + // Construct a body slightly over 1 MiB. + bigBody := bytes.Repeat([]byte("x"), 1<<20+1) + req, _ := http.NewRequest(http.MethodPost, "/", bytes.NewReader(bigBody)) + rw := newTestResponseWriter() + w.ServeHTTP(rw, req) + require.Equal(t, http.StatusRequestEntityTooLarge, rw.code) +} + +// --------------------------------------------------------------------------- +// WebhookServer — Stop when srv is nil (no ListenAndServe called) +// --------------------------------------------------------------------------- + +func TestWebhookServer_StopNoServer(t *testing.T) { + b := client.New("t") + w := NewWebhookServer(b) + require.NoError(t, w.Stop(context.Background())) +} + +// --------------------------------------------------------------------------- +// WebhookServer — no secret token, any POST accepted +// --------------------------------------------------------------------------- + +func TestWebhookServer_NoSecretAllowsAnyPost(t *testing.T) { + b := client.New("t") + w := NewWebhookServer(b) + + body := `{"update_id":99}` + req, _ := http.NewRequest(http.MethodPost, "/", strings.NewReader(body)) + // No secret header set. + rw := newTestResponseWriter() + // ServeHTTP would block on w.out <- u unless we drain it. + go func() { + for range w.Updates() { + } + }() + w.ServeHTTP(rw, req) + // Bad JSON would return 400; update_id-only body is valid enough for Update. + require.NotEqual(t, http.StatusUnauthorized, rw.code) +} + +// --------------------------------------------------------------------------- +// ExponentialBackoff — negative attempt clamped to 1 +// --------------------------------------------------------------------------- + +func TestExponentialBackoff_NegativeAttempt(t *testing.T) { + b := DefaultBackoff() + d := b.NextDelay(-5) + require.GreaterOrEqual(t, d, time.Duration(0)) + require.LessOrEqual(t, d, b.Max) +} + +// --------------------------------------------------------------------------- +// helpers +// --------------------------------------------------------------------------- + +type testResponseWriter struct { + code int + header http.Header +} + +func newTestResponseWriter() *testResponseWriter { + return &testResponseWriter{code: http.StatusOK, header: http.Header{}} +} + +func (r *testResponseWriter) Header() http.Header { return r.header } +func (r *testResponseWriter) Write(b []byte) (int, error) { return len(b), nil } +func (r *testResponseWriter) WriteHeader(statusCode int) { r.code = statusCode } diff --git a/transport/longpoll.go b/transport/longpoll.go new file mode 100644 index 0000000..8ee3d17 --- /dev/null +++ b/transport/longpoll.go @@ -0,0 +1,129 @@ +package transport + +import ( + "context" + "errors" + "sync" + "time" + + "github.com/lukaszraczylo/go-telegram/api" + "github.com/lukaszraczylo/go-telegram/client" +) + +// LongPoller pulls updates via Bot.GetUpdates in a loop, advancing the +// offset cursor after each batch. It applies BackoffStrategy on transient +// errors (network failures, 5xx, 429). +// +// At-least-once semantics on shutdown: when ctx is cancelled or Stop is +// called mid-batch, any updates already fetched but not yet dispatched are +// dropped without advancing the offset. On the next restart those updates +// will be re-delivered by Telegram. +type LongPoller struct { + Bot *client.Bot + Timeout int // seconds, default 30 + Limit int // 1..100, default 100 + AllowedTypes []api.UpdateType + Backoff BackoffStrategy + + out chan api.Update + once sync.Once + stop chan struct{} +} + +// NewLongPoller constructs a LongPoller with sensible defaults. +func NewLongPoller(b *client.Bot) *LongPoller { + return &LongPoller{ + Bot: b, + Timeout: 30, + Limit: 100, + Backoff: DefaultBackoff(), + out: make(chan api.Update, 64), + stop: make(chan struct{}), + } +} + +// Updates implements Updater. +func (p *LongPoller) Updates() <-chan api.Update { return p.out } + +// Run implements Updater. It blocks until ctx is cancelled, Stop is +// called, or a fatal error occurs (e.g. unauthorized). See LongPoller +// for at-least-once delivery semantics on shutdown. +func (p *LongPoller) Run(ctx context.Context) error { + defer close(p.out) + + var offset int64 + failures := 0 + for { + select { + case <-ctx.Done(): + return ctx.Err() + case <-p.stop: + return nil + default: + } + + params := &api.GetUpdatesParams{Offset: &offset} + if p.Limit > 0 { + lim := int64(p.Limit) + params.Limit = &lim + } + if p.Timeout > 0 { + to := int64(p.Timeout) + params.Timeout = &to + } + if len(p.AllowedTypes) > 0 { + allowed := make([]string, len(p.AllowedTypes)) + for i, t := range p.AllowedTypes { + allowed[i] = string(t) + } + params.AllowedUpdates = allowed + } + ups, err := api.GetUpdates(ctx, p.Bot, params) + if err != nil { + if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { + return err + } + // Fatal: unauthorized -> bail. + if errors.Is(err, client.ErrUnauthorized) { + return err + } + var ae *client.APIError + var delay time.Duration + if errors.As(err, &ae) && ae.RetryAfter() > 0 { + delay = ae.RetryAfter() + // Don't escalate failures count — Telegram is dictating the wait. + } else { + failures++ + delay = p.Backoff.NextDelay(failures) + } + select { + case <-time.After(delay): + continue + case <-ctx.Done(): + return ctx.Err() + case <-p.stop: + return nil + } + } + failures = 0 + + for _, u := range ups { + select { + case p.out <- u: + if u.UpdateID >= offset { + offset = u.UpdateID + 1 + } + case <-ctx.Done(): + return ctx.Err() + case <-p.stop: + return nil + } + } + } +} + +// Stop implements Updater. +func (p *LongPoller) Stop(ctx context.Context) error { + p.once.Do(func() { close(p.stop) }) + return nil +} diff --git a/transport/longpoll_test.go b/transport/longpoll_test.go new file mode 100644 index 0000000..29e33b1 --- /dev/null +++ b/transport/longpoll_test.go @@ -0,0 +1,146 @@ +package transport + +import ( + "bytes" + "context" + "io" + "net/http" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/lukaszraczylo/go-telegram/client" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" +) + +type mockDoer struct{ mock.Mock } + +func (m *mockDoer) Do(r *http.Request) (*http.Response, error) { + args := m.Called(r) + if v := args.Get(0); v != nil { + return v.(*http.Response), args.Error(1) + } + return nil, args.Error(1) +} + +func resp(body string) *http.Response { + return &http.Response{ + StatusCode: 200, + Body: io.NopCloser(bytes.NewBufferString(body)), + Header: http.Header{"Content-Type": []string{"application/json"}}, + } +} + +func TestLongPoller_DeliversUpdatesAndAdvancesOffset(t *testing.T) { + m := &mockDoer{} + m.On("Do", mock.Anything).Return( + resp(`{"ok":true,"result":[{"update_id":10,"message":{"message_id":1,"date":0,"chat":{"id":1,"type":"private"},"text":"hi"}}]}`), + nil, + ).Once() + m.On("Do", mock.Anything).Return( + resp(`{"ok":true,"result":[{"update_id":11,"message":{"message_id":2,"date":0,"chat":{"id":1,"type":"private"},"text":"there"}}]}`), + nil, + ).Once() + m.On("Do", mock.Anything).Return( + resp(`{"ok":true,"result":[]}`), + nil, + ).Maybe() + + b := client.New("t", client.WithHTTPClient(m)) + p := NewLongPoller(b) + p.Timeout = 0 + + ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond) + defer cancel() + + go func() { _ = p.Run(ctx) }() + + u1 := <-p.Updates() + require.Equal(t, int64(10), u1.UpdateID) + u2 := <-p.Updates() + require.Equal(t, int64(11), u2.UpdateID) +} + +func TestLongPoller_BackoffOnNetworkError(t *testing.T) { + m := &mockDoer{} + var attempts atomic.Int32 + m.On("Do", mock.Anything).Run(func(args mock.Arguments) { + attempts.Add(1) + }).Return(nil, io.ErrUnexpectedEOF).Maybe() + + b := client.New("t", client.WithHTTPClient(m)) + p := NewLongPoller(b) + p.Timeout = 0 + p.Backoff = &ExponentialBackoff{Base: 5 * time.Millisecond, Max: 5 * time.Millisecond} + + ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) + defer cancel() + + _ = p.Run(ctx) + require.GreaterOrEqual(t, attempts.Load(), int32(2), "should retry at least once") +} + +func TestLongPoller_StopCloses(t *testing.T) { + m := &mockDoer{} + m.On("Do", mock.Anything).Return(resp(`{"ok":true,"result":[]}`), nil).Maybe() + + b := client.New("t", client.WithHTTPClient(m)) + p := NewLongPoller(b) + p.Timeout = 0 + + ctx := context.Background() + done := make(chan struct{}) + go func() { _ = p.Run(ctx); close(done) }() + + require.NoError(t, p.Stop(ctx)) + select { + case <-done: + case <-time.After(time.Second): + t.Fatal("Run did not exit after Stop") + } + + // Channel must be closed. + _, ok := <-p.Updates() + require.False(t, ok, "expected closed channel after Stop") +} +func TestLongPoller_HonoursRetryAfterOn429(t *testing.T) { + m := &mockDoer{} + var requestTimes []time.Time + var mu sync.Mutex + + record := func(args mock.Arguments) { + mu.Lock() + requestTimes = append(requestTimes, time.Now()) + mu.Unlock() + } + + // First call: 429 with retry_after=1. + m.On("Do", mock.Anything). + Run(record). + Return(resp(`{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}`), nil). + Once() + // Subsequent calls: empty success. + m.On("Do", mock.Anything). + Run(record). + Return(resp(`{"ok":true,"result":[]}`), nil). + Maybe() + + b := client.New("t", client.WithHTTPClient(m)) + p := NewLongPoller(b) + p.Timeout = 0 + // Backoff base is huge so if it were used we'd see >>1s delay. + p.Backoff = &ExponentialBackoff{Base: 10 * time.Second, Max: 30 * time.Second} + + ctx, cancel := context.WithTimeout(context.Background(), 2500*time.Millisecond) + defer cancel() + _ = p.Run(ctx) + + mu.Lock() + defer mu.Unlock() + require.GreaterOrEqual(t, len(requestTimes), 2, "expected at least 2 requests") + gap := requestTimes[1].Sub(requestTimes[0]) + require.GreaterOrEqual(t, gap, 900*time.Millisecond, "should have waited ~1s per retry_after, got %v", gap) + require.Less(t, gap, 3*time.Second, "should not have waited backoff base (10s), got %v", gap) +} diff --git a/transport/updater.go b/transport/updater.go new file mode 100644 index 0000000..d5b76d0 --- /dev/null +++ b/transport/updater.go @@ -0,0 +1,23 @@ +package transport + +import ( + "context" + + "github.com/lukaszraczylo/go-telegram/api" +) + +// Updater is the abstraction over update sources. Implementations must: +// - return a channel from Updates() that receives every Update they read. +// - close the channel after Run returns. +// - honour ctx cancellation in Run. +type Updater interface { + // Updates returns the channel updates flow into. Multiple readers + // is implementation-defined; users should treat it as single-reader. + Updates() <-chan api.Update + // Run blocks until ctx is cancelled or a fatal error occurs. It is + // the user's responsibility to call Run in a goroutine if needed. + Run(ctx context.Context) error + // Stop signals Run to exit and waits for the channel to drain. + // Implementations must be idempotent. + Stop(ctx context.Context) error +} diff --git a/transport/webhook.go b/transport/webhook.go new file mode 100644 index 0000000..20f519d --- /dev/null +++ b/transport/webhook.go @@ -0,0 +1,167 @@ +// Package transport provides update delivery mechanisms (long-poll and +// webhook) that feed updates into the dispatch package's Router. +// +// All implementations satisfy the Updater interface so user code can +// swap one for the other without touching handler logic. +package transport + +import ( + "context" + "crypto/subtle" + "errors" + "net" + "net/http" + "sync" + "time" + + "github.com/lukaszraczylo/go-telegram/api" + "github.com/lukaszraczylo/go-telegram/client" +) + +// WebhookServer implements Updater by exposing an http.Handler that +// receives updates from Telegram. It can be mounted on the user's own +// HTTP server (via ServeHTTP) or run standalone (via ListenAndServe). +type WebhookServer struct { + Bot *client.Bot + SecretToken string // verify X-Telegram-Bot-Api-Secret-Token; empty disables + + out chan api.Update + once sync.Once + stop chan struct{} + mu sync.Mutex + handlers sync.WaitGroup + + srv *http.Server +} + +// WebhookOption configures a WebhookServer at construction time. +type WebhookOption func(*webhookOptions) + +type webhookOptions struct { + bufferSize int +} + +// WithBufferSize sets the size of the updates channel buffer. +// Default is 64. +func WithBufferSize(n int) WebhookOption { + return func(o *webhookOptions) { o.bufferSize = n } +} + +// NewWebhookServer constructs a WebhookServer with default buffer size (64). +// Use WithBufferSize to override. +func NewWebhookServer(b *client.Bot, opts ...WebhookOption) *WebhookServer { + cfg := webhookOptions{bufferSize: 64} + for _, o := range opts { + o(&cfg) + } + return &WebhookServer{ + Bot: b, + out: make(chan api.Update, cfg.bufferSize), + stop: make(chan struct{}), + } +} + +// Updates implements Updater. +func (w *WebhookServer) Updates() <-chan api.Update { return w.out } + +// Run implements Updater. It blocks until Stop is called or ctx is +// cancelled. If the server has not been started via ListenAndServe, Run +// only watches for shutdown — the user is expected to mount ServeHTTP +// on their own router. +func (w *WebhookServer) Run(ctx context.Context) error { + defer close(w.out) + defer w.handlers.Wait() // drain in-flight ServeHTTP calls before closing out (LIFO: runs first) + select { + case <-ctx.Done(): + return ctx.Err() + case <-w.stop: + return nil + } +} + +// Stop implements Updater. +func (w *WebhookServer) Stop(ctx context.Context) error { + w.once.Do(func() { close(w.stop) }) + w.mu.Lock() + srv := w.srv + w.mu.Unlock() + if srv != nil { + return srv.Shutdown(ctx) + } + return nil +} + +// ServeHTTP implements http.Handler. Telegram POSTs each update as JSON +// to this endpoint. Non-POST requests get 405; bad bodies get 400; secret +// token mismatches get 401. +func (w *WebhookServer) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + rw.WriteHeader(http.StatusMethodNotAllowed) + return + } + if w.SecretToken != "" { + got := r.Header.Get("X-Telegram-Bot-Api-Secret-Token") + if subtle.ConstantTimeCompare([]byte(got), []byte(w.SecretToken)) != 1 { + rw.WriteHeader(http.StatusUnauthorized) + return + } + } + w.handlers.Add(1) + defer w.handlers.Done() + defer func() { _ = r.Body.Close() }() + + const max = 1 << 20 // 1 MiB cap on body + buf := make([]byte, 0, 1024) + tmp := make([]byte, 4096) + for { + n, err := r.Body.Read(tmp) + if n > 0 { + buf = append(buf, tmp[:n]...) + if len(buf) > max { + rw.WriteHeader(http.StatusRequestEntityTooLarge) + return + } + } + if errors.Is(err, http.ErrBodyReadAfterClose) || err != nil { + break + } + } + + var u api.Update + codec := w.Bot.Codec() + if err := codec.Unmarshal(buf, &u); err != nil { + rw.WriteHeader(http.StatusBadRequest) + return + } + + select { + case w.out <- u: + case <-w.stop: + } + + rw.WriteHeader(http.StatusOK) +} + +// ListenAndServe starts an HTTP server on addr and blocks until Stop is +// called (which triggers Shutdown with the caller's context) or the server +// returns an error other than http.ErrServerClosed. Callers must invoke +// Stop(ctx) to cleanly shut down the server; the ctx passed here is only +// used as the server's base context for incoming requests. +func (w *WebhookServer) ListenAndServe(ctx context.Context, addr string) error { + mux := http.NewServeMux() + mux.Handle("/", w) + srv := &http.Server{ + Addr: addr, + Handler: mux, + BaseContext: func(net.Listener) context.Context { return ctx }, + ReadHeaderTimeout: 10 * time.Second, + } + w.mu.Lock() + w.srv = srv + w.mu.Unlock() + err := srv.ListenAndServe() + if errors.Is(err, http.ErrServerClosed) { + return nil + } + return err +} diff --git a/transport/webhook_test.go b/transport/webhook_test.go new file mode 100644 index 0000000..9fa01f1 --- /dev/null +++ b/transport/webhook_test.go @@ -0,0 +1,137 @@ +package transport + +import ( + "bytes" + "context" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" + + "github.com/lukaszraczylo/go-telegram/client" + "github.com/stretchr/testify/require" +) + +func TestWebhook_DeliversUpdate(t *testing.T) { + b := client.New("t") + w := NewWebhookServer(b) + w.SecretToken = "secret" + + srv := httptest.NewServer(w) + t.Cleanup(srv.Close) + + body := `{"update_id":1,"message":{"message_id":1,"date":0,"chat":{"id":1,"type":"private"},"text":"hi"}}` + req, _ := http.NewRequest(http.MethodPost, srv.URL, strings.NewReader(body)) + req.Header.Set("X-Telegram-Bot-Api-Secret-Token", "secret") + resp, err := http.DefaultClient.Do(req) + require.NoError(t, err) + _ = resp.Body.Close() + require.Equal(t, http.StatusOK, resp.StatusCode) + + select { + case u := <-w.Updates(): + require.Equal(t, int64(1), u.UpdateID) + case <-time.After(time.Second): + t.Fatal("update not delivered") + } +} + +func TestWebhook_RejectsBadSecret(t *testing.T) { + b := client.New("t") + w := NewWebhookServer(b) + w.SecretToken = "secret" + + srv := httptest.NewServer(w) + t.Cleanup(srv.Close) + + req, _ := http.NewRequest(http.MethodPost, srv.URL, strings.NewReader(`{}`)) + req.Header.Set("X-Telegram-Bot-Api-Secret-Token", "wrong") + resp, err := http.DefaultClient.Do(req) + require.NoError(t, err) + _ = resp.Body.Close() + require.Equal(t, http.StatusUnauthorized, resp.StatusCode) +} + +func TestWebhook_RejectsNonPOST(t *testing.T) { + w := NewWebhookServer(client.New("t")) + srv := httptest.NewServer(w) + t.Cleanup(srv.Close) + + resp, err := http.Get(srv.URL) + require.NoError(t, err) + _ = resp.Body.Close() + require.Equal(t, http.StatusMethodNotAllowed, resp.StatusCode) +} + +func TestWebhook_RejectsBadJSON(t *testing.T) { + w := NewWebhookServer(client.New("t")) + srv := httptest.NewServer(w) + t.Cleanup(srv.Close) + + resp, err := http.Post(srv.URL, "application/json", bytes.NewBufferString("not json")) + require.NoError(t, err) + _ = resp.Body.Close() + require.Equal(t, http.StatusBadRequest, resp.StatusCode) +} + +func TestWebhook_StopExitsRun(t *testing.T) { + w := NewWebhookServer(client.New("t")) + + done := make(chan struct{}) + go func() { _ = w.Run(context.Background()); close(done) }() + + require.NoError(t, w.Stop(context.Background())) + select { + case <-done: + case <-time.After(time.Second): + t.Fatal("Run did not exit after Stop") + } +} + +// TestWebhook_ConcurrentStopNoPanic fires many concurrent requests while +// simultaneously calling Stop, and asserts no panic (send on closed channel). +// Run under -race to verify mutex and WaitGroup correctness. +func TestWebhook_ConcurrentStopNoPanic(t *testing.T) { + body := `{"update_id":1,"message":{"message_id":1,"date":0,"chat":{"id":1,"type":"private"},"text":"hi"}}` + + for range 20 { + w := NewWebhookServer(client.New("t"), WithBufferSize(256)) + srv := httptest.NewServer(w) + + // Drain updates so ServeHTTP doesn't block on a full channel. + go func() { + for range w.Updates() { + } + }() + + // Run in background. + go func() { _ = w.Run(context.Background()) }() + + // Fire concurrent requests. + const goroutines = 20 + ready := make(chan struct{}) + var wg sync.WaitGroup + for i := 0; i < goroutines; i++ { + wg.Add(1) + go func() { + defer wg.Done() + <-ready + for j := 0; j < 5; j++ { + req, _ := http.NewRequest(http.MethodPost, srv.URL, strings.NewReader(body)) + resp, err := http.DefaultClient.Do(req) + if err == nil { + _ = resp.Body.Close() + } + } + }() + } + + close(ready) + time.Sleep(5 * time.Millisecond) // let some requests land before Stop + srv.Close() + _ = w.Stop(context.Background()) + wg.Wait() + } +}