Documentation
¶
Overview ¶
Package telegram provides SDK-agnostic Telegram formatting utilities. Stdlib-only, zero external dependencies.
Package telegram provides SDK-agnostic Telegram formatting utilities. Stdlib-only, zero external dependencies.
Package telegram provides SDK-agnostic Telegram formatting utilities.
Index ¶
- Constants
- func CloseUnclosedMarkdown(text string) string
- func CompactForTelegram(text string, maxChars int) string
- func EscapeHTML(text string) string
- func IsTransientError(err error) bool
- func MarkdownToHTML(text string) string
- func ParseChatID(s string) (int64, error)
- func PrepareForTelegram(text string) (out string, parseMode string)
- func RepairHTMLNesting(html string) string
- func SanitizeHTML(input string) string
- func SanitizeUTF8(text string) string
- func SplitMessage(text string, maxLen int) []string
- func StripHTMLTags(s string) string
- func StripMarkdown(text string) string
- func Truncate(s string, maxLen int) string
- type Command
- type Format
- type Glossary
- type Locale
- type Term
Constants ¶
const MaxMessageLen = 4096
MaxMessageLen is the Telegram Bot API limit for a single message.
Variables ¶
This section is empty.
Functions ¶
func CloseUnclosedMarkdown ¶
CloseUnclosedMarkdown closes any unclosed markdown constructs at the end of partial streaming text, so it can be safely converted to HTML mid-stream.
func CompactForTelegram ¶
CompactForTelegram truncates verbose LLM responses for Telegram delivery. Runs on raw markdown BEFORE HTML conversion. Pass-through if text <= maxChars. maxChars is measured in runes (Unicode code points), not bytes.
func EscapeHTML ¶
EscapeHTML escapes &, <, > for Telegram HTML mode.
func IsTransientError ¶
IsTransientError returns true if the error looks like a transient Telegram API error that should be retried (429, 502, timeout, etc.).
func MarkdownToHTML ¶
MarkdownToHTML converts markdown to Telegram-compatible HTML.
Handles: headings (bold), bold, italic, bold-italic, strikethrough, links, code blocks with language, inline code, blockquotes, horizontal rules, and lists. Code blocks and inline codes are extracted first via placeholders to protect from transformation. Calls RepairHTMLNesting at the end.
func ParseChatID ¶
ParseChatID parses a string chat ID to int64.
func PrepareForTelegram ¶
PrepareForTelegram detects the markup format of text and returns a Telegram-ready (out, parseMode) pair. parseMode is always "HTML" — Telegram accepts HTML mode for plain-escaped text just as well.
Routing:
- HTML input: SanitizeHTML → RepairHTMLNesting → ("HTML")
- Markdown input: MarkdownToHTML (converts + escapes + repairs) → SanitizeHTML (defensive) → ("HTML")
- Plain input: EscapeHTML → ("HTML")
- Empty input: ("", "HTML")
func RepairHTMLNesting ¶
RepairHTMLNesting fixes malformed HTML tag nesting from regex-based conversion. Tracks Telegram-supported tags (b, i, s, u, a, code, pre, blockquote). Closes unclosed tags, discards unmatched closers, reorders interleaved tags.
func SanitizeHTML ¶
SanitizeHTML converts arbitrary HTML into Telegram-safe HTML using the golang.org/x/net/html parser (not regex). Synonyms are renamed (strong→b, em→i, etc.), block elements are converted to newlines, lists produce bullets/numbers, unknown tags are stripped keeping their text content, and dangerous tags (script, style, iframe) are dropped entirely.
func SanitizeUTF8 ¶
SanitizeUTF8 removes null bytes and invalid UTF-8 sequences.
func SplitMessage ¶
SplitMessage splits text into chunks respecting maxLen (in UTF-16 code units, the unit Telegram measures message length in — not runes, not bytes), preferring newline boundaries. A non-BMP rune (2 UTF-16 units, e.g. an emoji) is never halved across a boundary. Second pass fixes HTML tags across chunk boundaries by closing open tags at end of each chunk and reopening them at start of next chunk, and trims any chunk that exceeds maxLen after tag repair.
For pure-BMP text (ASCII, Cyrillic, etc.) UTF-16 units == runes, so behaviour is identical to the previous rune-based implementation.
Unsatisfiable budget: if maxLen is smaller than the UTF-16 unit width of the leading rune (e.g. maxLen==1 with a leading non-BMP emoji, which is 2 units), that rune cannot fit in any legal chunk. Rather than hang or drop it, the rune is emitted as its own chunk, exceeding maxLen by its unit width. The caller's real budgets (Telegram 4096) never hit this; it only matters for adversarially small maxLen values where no correct chunk exists for that rune.
func StripHTMLTags ¶
StripHTMLTags removes all HTML tags, returning plain text.
func StripMarkdown ¶
StripMarkdown removes all markdown syntax for plain-text fallback. Produces clean readable text without formatting markers.
Types ¶
type Command ¶ added in v0.56.0
Command represents a single Telegram bot command used in setMyCommands.
type Format ¶
type Format int
Format represents the detected markup format of a text string.
type Glossary ¶ added in v0.97.5
type Glossary struct {
// contains filtered or unexported fields
}
Glossary normalizes STT-garbled brand/service/person names to their canonical spelling and optionally bolds them. Compile once with NewGlossary; the result is immutable and safe for concurrent use by any number of Apply calls.
func NewGlossary ¶ added in v0.97.5
NewGlossary compiles a set of terms into a matcher. The Canonical spelling of each term is also registered as an alias of itself, so an already-correct but wrong-case occurrence (e.g. "headhunter") is normalized to the canonical spelling (e.g. "HeadHunter"). nil/empty terms yield a no-op Glossary.
func (*Glossary) Apply ¶ added in v0.97.5
Apply normalizes every glossary term occurrence in text to its canonical spelling, optionally bolding it. Matching is case-insensitive with case-correct output, Unicode/Cyrillic word-boundary aware (whole words only, never a substring inside a longer word), and tolerant of run-of-whitespace between the words of a multi-word alias. Existing HTML tags are passed through untouched, and a bold term is not double-wrapped if it is already inside a <b>…</b> span. A nil Glossary is a no-op.
type Locale ¶ added in v0.56.0
type Locale struct {
// contains filtered or unexported fields
}
Locale loads YAML-defined per-lang string maps, button labels, and command menus.
Each locale file maps keys → strings; missing keys fall back to the default lang. Locale is immutable after construction; all methods are safe for concurrent use.
func NewLocale ¶ added in v0.56.0
NewLocale loads locale YAML files from fsys (caller picks: embed.FS, os.DirFS, testing/fstest.MapFS, …). Files are expected at the root of fsys with names matching "<lang>.yaml" (e.g. "ru.yaml", "en.yaml").
defaultLang must be present in fsys; it is used as the fallback for missing keys. Returns an error if defaultLang file is absent or any loaded file has invalid YAML.
NewLocale eagerly pre-compiles all template strings and merges button maps so that Get, Button, and Buttons incur zero allocations on the read hot path.
func (*Locale) Available ¶ added in v0.56.0
Available returns the list of locale codes that loaded successfully. The order is not guaranteed.
func (*Locale) Button ¶ added in v0.57.0
Button returns the label for a single button key in lang, without allocating a full map. Falls back to the default lang if the key is absent in lang. Returns key itself if absent everywhere (same sentinel behaviour as Get).
func (*Locale) Buttons ¶ added in v0.56.0
Buttons returns the merged button map for lang (default-lang base overlaid by lang-specific values). The returned map is pre-built at construction and shared across callers — treat it as read-only.
Falls back to the default lang map if lang was not loaded.
func (*Locale) Commands ¶ added in v0.56.0
Commands returns the bot command menu for lang (used by setMyCommands). Falls back to default lang if lang is not loaded.
func (*Locale) Get ¶ added in v0.56.0
Get returns the string for key in lang. If the key is missing in lang, it falls back to the default lang. If still missing, it returns key as-is (debug-friendly).
When vars is non-empty, the string is interpreted as a text/template with the first element of vars as the dot value ({{.}}). The template is pre-compiled at construction time — no parse overhead on the hot path.
type Term ¶ added in v0.97.5
type Term struct {
Canonical string // canonical spelling, e.g. "HeadHunter"
Aliases []string // STT-garbled spoken forms to normalize, e.g. {"хэт хантер","хед хантер"}
Bold bool // when true, wrap each normalized occurrence of Canonical in <b>…</b>
}
Term is one glossary entry.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package botusers tracks Telegram users that interact with a bot.
|
Package botusers tracks Telegram users that interact with a bot. |
|
botuserstest
Package botuserstest provides a reusable contract test suite for botusers.Store implementations.
|
Package botuserstest provides a reusable contract test suite for botusers.Store implementations. |
|
pg
Package pg provides a PostgreSQL-backed implementation of botusers.Store using pgxpool.
|
Package pg provides a PostgreSQL-backed implementation of botusers.Store using pgxpool. |
|
Package broadcast provides a rate-limited broadcaster for Telegram messages.
|
Package broadcast provides a rate-limited broadcaster for Telegram messages. |
|
Package callback provides HMAC-SHA256 signed Telegram CallbackData encoding.
|
Package callback provides HMAC-SHA256 signed Telegram CallbackData encoding. |
|
Package cmd provides a fluent text-command router for Telegram bots.
|
Package cmd provides a fluent text-command router for Telegram bots. |
|
Package forum provides a Manager for supergroup forum-topic operations.
|
Package forum provides a Manager for supergroup forum-topic operations. |
|
Package fsm provides a conversation state machine for Telegram bots.
|
Package fsm provides a conversation state machine for Telegram bots. |
|
Package kb provides a fluent inline keyboard builder for Telegram bots, with co-located callback handler registration.
|
Package kb provides a fluent inline keyboard builder for Telegram bots, with co-located callback handler registration. |
|
Package middleware provides composable handler middleware for Telegram bots.
|
Package middleware provides composable handler middleware for Telegram bots. |
|
Package miniapp provides Telegram Mini App initData signature validation.
|
Package miniapp provides Telegram Mini App initData signature validation. |
|
Package notify provides two opinionated, non-conflatable notification sinks for Go services.
|
Package notify provides two opinionated, non-conflatable notification sinks for Go services. |
|
Package ops provides operator notification utilities for Telegram bots.
|
Package ops provides operator notification utilities for Telegram bots. |
|
Package tgapi5 provides default implementations of the Telegram adapter interfaces defined in the go-kit/telegram/middleware and related packages, backed by github.com/OvyFlash/telegram-bot-api.
|
Package tgapi5 provides default implementations of the Telegram adapter interfaces defined in the go-kit/telegram/middleware and related packages, backed by github.com/OvyFlash/telegram-bot-api. |