telegram

package
v0.0.0-...-ffd5c47 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 15, 2026 License: MIT Imports: 20 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package telegram is the Telegram transport adapter for the core/chat conversation layer. It wraps a *bot.Bot, implements core/chat.Transport (converting Telegram's native int64 chat id / int message id to and from the string ChatID/MessageID the neutral layer uses), renders the Stop and star inline markup, classifies Telegram's 429 rate-limit error, downloads inbound files (with token redaction), and converts the assistant's Markdown to Telegram HTML. The transport-neutral run loop lives in core/chat.

Index

Constants

View Source
const HelpText = "Flock Telegram assistant — available commands:\n\n" +
	"/help — show this message\n" +
	"/new — start a fresh session (forget the current conversation)\n" +
	"/stop — stop the run currently in progress\n" +
	"/schedule — manage scheduled jobs (when enabled)\n" +
	"/goal <criterion> — arm a goal an independent evaluator re-checks after every run " +
	"(/goal off to disarm)\n\n" +
	"Send any other message to run it through the assistant."

HelpText is the static usage message replied to an allowed user who sends /help. It lists the slash commands the adapter understands. It is an engineering artifact (professional English, no duck flavor) and never reaches the Claude Runner.

View Source
const WelcomeText = "Hi! I'm the Flock assistant.\n\n" + HelpText

WelcomeText is the static usage message replied to an allowed user who sends /start. It is a short greeting prepended to the command help so a brand-new user immediately sees what the bot does and how to use it. Like HelpText it is an engineering artifact (plain English, no duck flavor) and never reaches the Claude Runner — the duck greeting comes from the model on a real message.

Variables

View Source
var ErrUploadTooLarge = fsutil.ErrUploadTooLarge

ErrUploadTooLarge is returned when the source reports (or the stream exceeds) the configured size cap, so the caller can turn it into one friendly notice.

Functions

func CallbackMatch

func CallbackMatch() string

CallbackMatch reports whether callback data is a Stop callback this Service should handle. Used as the prefix for the bot's callback handler.

func CommandName

func CommandName(msg *models.Message) string

CommandName returns the slash command addressed at the start of msg, lowercased and without any @botname suffix, or "" when msg is not a bot command. Telegram inserts an @botname suffix when a command is tapped in a group (e.g. /new@duck_bot), and go-telegram/bot's MatchTypeCommand compares the FULL "new@duck_bot" token, so it would miss the command in groups; stripping the suffix here makes /new and /new@duck_bot equivalent. The token is lowercased because Telegram preserves the case the user typed for the command word (only the @botname suffix is lowercased by clients), so /Stop arrives as "Stop"; lowercasing keeps reserved-command routing case-insensitive (matching VK and chat.IsReservedCommand) instead of leaking /Stop, /New, … to the model as free text. Only a bot_command entity at offset 0 counts, so a "/new" appearing mid-message is not treated as a command.

func MarkdownToHTML

func MarkdownToHTML(md string) string

MarkdownToHTML renders assistant Markdown using the shared bot HTML formatter. Callers retain their platform-specific plain-text fallback on parse rejection.

func NewBotChat

func NewBotChat(b *bot.Bot, enableRich bool) chat.Transport

NewBotChat adapts a *bot.Bot to the core/chat.Transport interface used by the Service. enableRich sets Capabilities().CanSendRich (from ENABLE_RICH_MESSAGES) and, when set, wires the rich HTTP transport over the bot's token; pass false to keep the legacy MarkdownToHTML/plain rendering.

func NewBotFileSource

func NewBotFileSource(b *bot.Bot) fileSource

NewBotFileSource adapts a *bot.Bot to the fileSource used by VoiceTranscriber.

func RetryAfter

func RetryAfter(err error) (time.Duration, bool)

RetryAfter reports the server-requested back-off when err is a Telegram 429 (rate limit), flooring a missing/zero value to 1s so callers still wait. It is wired into core/chat.Config.RetryAfter so the neutral run loop can throttle its edit fallback and back off terminal delivery without knowing about Telegram's error types.

func StarCallbackPrefix

func StarCallbackPrefix() string

StarCallbackPrefix is the callback_data prefix the cmd registers the star handler against (bot.MatchTypePrefix), mirroring CallbackMatch for Stop.

func StopRunID

func StopRunID(data string) string

StopRunID extracts the run id from a Stop callback's data, or "" if the data is not a Stop callback.

func StripCommandMention

func StripCommandMention(text, botUsername string) string

StripCommandMention normalizes the group form of a forwarded slash command so Claude receives it as a bare command. In a group, Telegram appends "@botname" to a tapped command (e.g. "/loop@duck_bot 5m"); this strips ONLY that "@botUsername" suffix from the leading "/command" token, yielding "/loop 5m".

It is intentionally conservative — a pure string transform with no entity awareness — and a no-op unless ALL of these hold:

  • botUsername is non-empty,
  • text begins with "/",
  • the leading whitespace-delimited token contains "@<botUsername>" as its suffix (case-insensitive: Telegram may lowercase the username, so we match either casing).

It never touches a non-leading token, so a mid-message "@botname" is left intact, and it returns text unchanged when there is no leading command, no "@" in the leading token, or the "@" addresses a DIFFERENT bot. Reserved commands never reach this path (they are routed to their own handlers), so it only ever normalizes Claude pass-through commands.

Types

type Uploader

type Uploader struct {
	// contains filtered or unexported fields
}

Uploader downloads a Telegram document/photo by file_id and saves it under a per-chat uploads directory that lives OUTSIDE every repo working tree (a sibling of the cloned repos), so user files can never enter a git commit. It reuses the voice download seam (fileSource / redactURLError / io.LimitReader) so the token-bearing download URL is never logged or surfaced.

func NewUploader

func NewUploader(
	source fileSource, client *http.Client, uploads uploadsDirResolver, maxBytes int64, logger *slog.Logger,
) *Uploader

NewUploader builds an Uploader. A nil client defaults to http.DefaultClient, a non-positive maxBytes to defaultMaxUploadBytes, and a nil logger to slog.Default().

func (*Uploader) MaxBytes

func (u *Uploader) MaxBytes() int64

MaxBytes is the configured download cap. Callers may pre-check a known file size against it to reject an oversize upload before any download.

func (*Uploader) Save

func (u *Uploader) Save(ctx context.Context, chatID int64, fileID, fileName string) (string, error)

Save downloads fileID's bytes (capped at maxBytes) and writes them to a sanitized, collision-safe path under chatID's uploads directory, returning the saved ABSOLUTE path. fileName is the client-supplied name and is treated as hostile: only its base is used and path separators / leading dots are stripped, so the saved file can never escape the uploads dir. An oversize or undownloadable file returns an error (ErrUploadTooLarge for the size case) the caller turns into one friendly notice; the error never carries the bot token.

type VoiceTranscriber

type VoiceTranscriber struct {
	// contains filtered or unexported fields
}

VoiceTranscriber downloads a Telegram voice file and transcribes it. The download is capped at maxBytes (via io.LimitReader) to guard against oversized files. The token-bearing download URL is never logged.

func NewVoiceTranscriber

func NewVoiceTranscriber(
	source fileSource, client *http.Client, transcriber voice.Transcriber, maxBytes int64, logger *slog.Logger,
) *VoiceTranscriber

NewVoiceTranscriber builds a VoiceTranscriber. A nil client defaults to http.DefaultClient, a non-positive maxBytes to defaultMaxVoiceBytes, and a nil logger to slog.Default().

func (*VoiceTranscriber) Transcribe

func (vt *VoiceTranscriber) Transcribe(ctx context.Context, fileID string) (string, error)

Transcribe fetches fileID's bytes (capped at maxBytes) and returns the transcript, or an error. The token-bearing download URL is never logged.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL