cmdlib

package
v7.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 17, 2026 License: MIT Imports: 23 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 cmdlib contains utlities mostly for bot

Index

Constants

View Source
const (
	SilentVerbosity = 0
	ErrVerbosity    = 1
	InfVerbosity    = 2
	DbgVerbosity    = 3
	TraceVerbosity  = 4
)

Verbosity constants

View Source
const IdleConnTimeout = 90 * time.Second

IdleConnTimeout is how long a client keeps an idle connection.

Variables

View Source
var CommonNicknameRegexp = regexp.MustCompile(`^[a-z0-9\-_@]+$`)

CommonNicknameRegexp is a regular expression to check nicknames

View Source
var Version = "(devel)"

Version is the version of the current code state

Functions

func BindEnvForConfig

func BindEnvForConfig(v *viper.Viper, cfg any)

BindEnvForConfig walks cfg's mapstructure tags and binds each resulting dotted key to v so AutomaticEnv picks up env overrides without an explicit list. cfg must be a pointer to a struct.

func CanonicalNicknamePreprocessing

func CanonicalNicknamePreprocessing(name string) string

CanonicalNicknamePreprocessing preprocesses nickname to canonical form

func CheckErr

func CheckErr(err error)

CheckErr panics on an error

func CloseBody

func CloseBody(body io.Closer)

CloseBody closes request body

func CommandFuncs

func CommandFuncs(mention string) template.FuncMap

CommandFuncs rebinds the command writers for one chat. mention is empty where a bare command reaches the bot, or where no chat is in play.

func ConfigDirs

func ConfigDirs() []string

ConfigDirs lists where FindConfig looks, in order, so a usage message can name the directories this machine actually searches rather than describe them. The working directory is not among them: these files carry production credentials, and a repo checkout is a working directory.

func FindConfig

func FindConfig(name string) (string, error)

FindConfig returns the path to name in the first config directory holding it. Callers take an explicit path for anywhere else.

func HTTPClientWithProxy

func HTTPClientWithProxy(timeout time.Duration, proxyURL *url.URL) *http.Client

HTTPClientWithProxy returns an HTTP client routing all requests through the given proxy URL (supports http, https, socks5 schemes).

func HTTPClientWithTimeout

func HTTPClientWithTimeout(timeout time.Duration) *http.Client

HTTPClientWithTimeout returns an HTTP client with the given timeout. A zero timeout disables the timeout (the same convention http.Client itself uses) and is intended for tests.

func IntegerHookFunc

func IntegerHookFunc() mapstructure.DecodeHookFunc

IntegerHookFunc decodes into an integer type only a base 10 string or a whole number that fits, where mapstructure reads "010" as octal, "0x10" as hex, "" as 0, true as 1 and 1.5 as 1

func Ldbg

func Ldbg(format string, v ...interface{})

Ldbg logs a debug message

func Lerr

func Lerr(format string, v ...interface{})

Lerr logs an error

func Lfatalf

func Lfatalf(format string, v ...interface{})

Lfatalf logs a fatal error and terminates the process. It prints regardless of verbosity, then exits with a non-zero status.

func Linf

func Linf(format string, v ...interface{})

Linf logs an info message

func LoadAllAds

func LoadAllAds(
	files map[string][]string,
) (trMap map[string]map[string]*Translation, tpl map[string]*template.Template)

LoadAllAds loads all ads

func LoadAllTranslations

func LoadAllTranslations(
	files map[string][]string,
) (trMap map[string]*Translations, tpl map[string]*template.Template)

LoadAllTranslations loads all translations

func LoadEndpointTranslations

func LoadEndpointTranslations(files []string) (*Translations, AllTranslations)

LoadEndpointTranslations loads translations for a specific endpoint

func Ltrace

func Ltrace(format string, v ...interface{})

Ltrace logs a trace message — finest-grained level, intended for raw protocol payloads and similar high-volume diagnostic data.

func NoRedirect

func NoRedirect(_ *http.Request, _ []*http.Request) error

NoRedirect tells HTTP client not to redirect

func OnlineListLine

func OnlineListLine(nickname string, info StreamerInfo) string

OnlineListLine is a streamer's line in the online lists the CLI tools print: "<nickname>, pic: <image_url>, prof: <profile_image_url>", leaving out an empty URL.

func OnlineQuery

func OnlineQuery(
	usersOnlineEndpoint string,
	client *http.Client,
	headers [][2]string,
) (
	*http.Response,
	*bytes.Buffer,
	error,
)

OnlineQuery creates and performs online request

func OnlineRequest

func OnlineRequest(
	req *http.Request,
	client *http.Client,
) (
	*http.Response,
	*bytes.Buffer,
	error,
)

OnlineRequest performs online request

func SetVerbosity

func SetVerbosity(debug bool)

SetVerbosity sets the global verbosity from a boolean debug switch: debug level when true, info level otherwise.

func StrictConfigDecoder

func StrictConfigDecoder(dc *mapstructure.DecoderConfig)

StrictConfigDecoder configures a viper Unmarshal to reject unknown keys and apply the standard config decode-hook chain: comma-split strings into slices, duration strings, RFC3339 strings into time.Time, encoding.TextUnmarshaler types, JSON strings into maps (the last few let XRN_ env vars carry slice/map/duration/time values), and integers from base 10 strings and whole numbers only.

func StringToMapHookFunc

func StringToMapHookFunc() mapstructure.DecodeHookFunc

StringToMapHookFunc decodes a JSON string into a map field. Lets env vars supply structured map values.

func StringToSliceHookFunc

func StringToSliceHookFunc(sep string) mapstructure.DecodeHookFunc

StringToSliceHookFunc decodes a sep-split string into a slice field. Lets env vars supply list values.

func TemplateFuncs

func TemplateFuncs() template.FuncMap

TemplateFuncs are the functions every translation template is parsed with. command writes a command mention: {{ command "add" }}, naming it as the bot registers it. short_command writes the shortest form that still reaches the bot. Both refuse here: the names must resolve at parse time, but only the send path knows the chat, so executing this set without CommandFuncs fails instead of writing a command bare. feature_enabled reports whether the bot has a feature on, and refuses until the bot binds it.

Types

type AllTranslations

type AllTranslations map[string]*Translation

AllTranslations represents a collection of translated texts in all supported languages

func LoadAds

func LoadAds(files []string) AllTranslations

LoadAds loads ads for a specific endpoint

type CheckMode

type CheckMode int

CheckMode represents check mode

const (
	CheckOnline CheckMode = iota
	CheckStatuses
)

Streamer statuses check mode

type CheckerResults

type CheckerResults interface {
	Duration() time.Duration
	Failed() bool
	Count() int
	ExtraLogFields() map[string]any
	// contains filtered or unexported methods
}

CheckerResults is the interface for status results

type ExistenceListResults

type ExistenceListResults struct {
	Streamers map[string]StreamerInfoWithStatus
	// contains filtered or unexported fields
}

ExistenceListResults contains results for ExistenceListRequest

func NewExistenceListResults

func NewExistenceListResults(
	streamers map[string]StreamerInfoWithStatus,
	duration time.Duration,
) *ExistenceListResults

NewExistenceListResults creates a successful ExistenceListResults.

func NewExistenceListResultsFailed

func NewExistenceListResultsFailed() *ExistenceListResults

NewExistenceListResultsFailed creates a failed ExistenceListResults.

func (*ExistenceListResults) Count

func (r *ExistenceListResults) Count() int

Count returns the number of streamers in the result.

func (*ExistenceListResults) Duration

func (r *ExistenceListResults) Duration() time.Duration

Duration returns the elapsed time for the request.

func (*ExistenceListResults) ExtraLogFields

func (r *ExistenceListResults) ExtraLogFields() map[string]any

ExtraLogFields returns extra fields for performance logging.

func (*ExistenceListResults) Failed

func (r *ExistenceListResults) Failed() bool

Failed returns whether the request failed.

type FixedListOnlineRequest

type FixedListOnlineRequest struct {
	Streamers map[string]bool
	ResultsCh chan<- CheckerResults
}

FixedListOnlineRequest requests statuses for specific streamers

type FixedListOnlineResults

type FixedListOnlineResults struct {
	RequestedStreamers map[string]bool
	Streamers          map[string]StreamerInfo
	// contains filtered or unexported fields
}

FixedListOnlineResults contains results for FixedListOnlineRequest

func NewFixedListOnlineResults

func NewFixedListOnlineResults(
	requestedStreamers map[string]bool,
	streamers map[string]StreamerInfo,
	duration time.Duration,
) *FixedListOnlineResults

NewFixedListOnlineResults creates a successful FixedListOnlineResults.

func NewFixedListOnlineResultsFailed

func NewFixedListOnlineResultsFailed() *FixedListOnlineResults

NewFixedListOnlineResultsFailed creates a failed FixedListOnlineResults.

func (*FixedListOnlineResults) Count

func (r *FixedListOnlineResults) Count() int

Count returns the number of streamers in the result.

func (*FixedListOnlineResults) Duration

func (r *FixedListOnlineResults) Duration() time.Duration

Duration returns the elapsed time for the request.

func (*FixedListOnlineResults) ExtraLogFields

func (r *FixedListOnlineResults) ExtraLogFields() map[string]any

ExtraLogFields returns extra fields for performance logging.

func (*FixedListOnlineResults) Failed

func (r *FixedListOnlineResults) Failed() bool

Failed returns whether the request failed.

type FixedListStatusRequest

type FixedListStatusRequest struct {
	Streamers map[string]bool
	ResultsCh chan<- *ExistenceListResults
}

FixedListStatusRequest checks if specific streamers exist

type OnlineListRequest

type OnlineListRequest struct {
	Poll      []string
	ResultsCh chan<- CheckerResults
}

OnlineListRequest requests statuses for all online streamers. Names in Poll fall back to QueryStreamer when not in the bulk result.

type OnlineListResults

type OnlineListResults struct {
	Streamers  map[string]StreamerInfo
	PollCount  int
	PollErrors []string
	// contains filtered or unexported fields
}

OnlineListResults contains results for OnlineListRequest

func NewOnlineListResults

func NewOnlineListResults(streamers map[string]StreamerInfo, duration time.Duration) *OnlineListResults

NewOnlineListResults creates a successful OnlineListResults.

func NewOnlineListResultsFailed

func NewOnlineListResultsFailed() *OnlineListResults

NewOnlineListResultsFailed creates a failed OnlineListResults.

func (*OnlineListResults) Count

func (r *OnlineListResults) Count() int

Count returns the number of streamers in the result.

func (*OnlineListResults) Duration

func (r *OnlineListResults) Duration() time.Duration

Duration returns the elapsed time for the request.

func (*OnlineListResults) ExtraLogFields

func (r *OnlineListResults) ExtraLogFields() map[string]any

ExtraLogFields returns extra fields for performance logging.

func (*OnlineListResults) Failed

func (r *OnlineListResults) Failed() bool

Failed returns whether the request failed.

func (*OnlineListResults) MarshalJSON

func (r *OnlineListResults) MarshalJSON() ([]byte, error)

MarshalJSON serialises the result so consumers (e.g. adapter-mfc) can return it over HTTP without exposing the unexported fields.

type ParseKind

type ParseKind int

ParseKind specifies Telegram message parsing method

const (
	// ParseRaw parses Telegram message as a raw text
	ParseRaw ParseKind = iota
	// ParseHTML parses Telegram message as HTML
	ParseHTML
	// ParseMarkdown parses Telegram message as Markdown
	ParseMarkdown
)

func (ParseKind) MarshalYAML

func (r ParseKind) MarshalYAML() ([]byte, error)

MarshalYAML is generated so ParseKind satisfies yaml.Marshaler.

func (ParseKind) String

func (r ParseKind) String() string

func (*ParseKind) UnmarshalYAML

func (r *ParseKind) UnmarshalYAML(unmarshal func(v interface{}) error) error

UnmarshalYAML is generated so ParseKind satisfies yaml.Unmarshaler.

type Secret

type Secret string

Secret is a string type that redacts its value in JSON and logs.

func (Secret) MarshalJSON

func (s Secret) MarshalJSON() ([]byte, error)

MarshalJSON redacts the secret value.

func (Secret) String

func (s Secret) String() string

String redacts the secret value.

type ShowKind

type ShowKind int

ShowKind represents the kind of show

const (
	// ShowUnknown means the show kind is unknown
	ShowUnknown ShowKind = 0
	// ShowPublic means the show is public
	ShowPublic ShowKind = 1
	// ShowGroup means the show is a group show
	ShowGroup ShowKind = 2
	// ShowTicket means the show is a ticket show
	ShowTicket ShowKind = 3
	// ShowHidden means the show is hidden
	ShowHidden ShowKind = 4
	// ShowPrivate means the show is private
	ShowPrivate ShowKind = 5
	// ShowAway means the model is away
	ShowAway ShowKind = 6
)

func (ShowKind) String

func (s ShowKind) String() string

String returns the symbolic name of the show kind.

type SingleStatusRequest

type SingleStatusRequest struct {
	Streamer  string
	ResultsCh chan<- *ExistenceListResults
}

SingleStatusRequest is FixedListStatusRequest dispatched via QueryStreamer for one streamer; used when the checker has no batched surface.

type StatusKind

type StatusKind int

StatusKind represents a status of a streamer

const (
	StatusUnknown  StatusKind = 0
	StatusOffline  StatusKind = 1
	StatusOnline   StatusKind = 2
	StatusNotFound StatusKind = 4
	StatusDenied   StatusKind = 8
)

Streamer statuses

func (StatusKind) String

func (s StatusKind) String() string

type StatusRequest

type StatusRequest interface {
	// contains filtered or unexported methods
}

StatusRequest is the interface for status requests

type StatusUpdate

type StatusUpdate struct {
	Nickname string
	Status   StatusKind
}

StatusUpdate represents an update of streamer status

type StreamerInfo

type StreamerInfo struct {
	ImageURL string `json:"image_url,omitempty"`
	// ProfileImageURL is the streamer's profile image, a fallback for ImageURL.
	ProfileImageURL string   `json:"profile_image_url,omitempty"`
	Viewers         *int     `json:"viewers,omitempty"`
	ShowKind        ShowKind `json:"show_kind,omitempty"`
	Subject         string   `json:"subject,omitempty"`
}

StreamerInfo carries presentation data for a streamer: cover image, profile image, viewer count, current show kind, and the room subject when supported.

type StreamerInfoWithStatus

type StreamerInfoWithStatus struct {
	StreamerInfo
	Status StatusKind `json:"status"`
	// ShowKindSince is when the current show kind, such as private, began.
	WentOnlineAt  *time.Time `json:"went_online_at,omitempty"`
	WentOfflineAt *time.Time `json:"went_offline_at,omitempty"`
	ShowKindSince *time.Time `json:"show_kind_since,omitempty"`
}

StreamerInfoWithStatus is StreamerInfo plus a StatusKind verdict and the times that only QueryStreamer with ExtraTimes fills.

type StringSetFlag

type StringSetFlag map[string]bool

StringSetFlag is a flag representing a set of strings

func (*StringSetFlag) Set

func (s *StringSetFlag) Set(value string) error

Set implements flag.Value interface

func (*StringSetFlag) String

func (s *StringSetFlag) String() string

String implements flag.Value interface

type Translation

type Translation struct {
	Key            string    `yaml:"-"`
	Str            string    `yaml:"str"`
	Parse          ParseKind `yaml:"parse"`
	DisablePreview bool      `yaml:"disable_preview"`
	Image          string    `yaml:"image"`
	ImageBytes     []byte    `yaml:"-"`
	Weight         int       `yaml:"weight"`
	// NeedsFeature drops an ad that pitches a feature the bot has off.
	NeedsFeature string `yaml:"needs_feature"`
}

Translation represents a translated text for a Telegram message

type Translations

type Translations struct {
	Start                       *Translation `yaml:"start"`
	Help                        *Translation `yaml:"help"`
	Online                      *Translation `yaml:"online"`
	List                        *Translation `yaml:"list"`
	Offline                     *Translation `yaml:"offline"`
	Denied                      *Translation `yaml:"denied"`
	SyntaxAdd                   *Translation `yaml:"syntax_add"`
	SyntaxRemove                *Translation `yaml:"syntax_remove"`
	SyntaxFeedback              *Translation `yaml:"syntax_feedback"`
	InvalidSymbols              *Translation `yaml:"invalid_symbols"`
	AlreadyAdded                *Translation `yaml:"already_added"`
	AddError                    *Translation `yaml:"add_error"`
	StreamerAdded               *Translation `yaml:"streamer_added"`
	StreamerNotInList           *Translation `yaml:"streamer_not_in_list"`
	StreamerRemoved             *Translation `yaml:"streamer_removed"`
	CheckingStreamer            *Translation `yaml:"checking_streamer"`
	Feedback                    *Translation `yaml:"feedback"`
	Social                      *Translation `yaml:"social"`
	UnknownCommand              *Translation `yaml:"unknown_command"`
	InvalidCommand              *Translation `yaml:"invalid_command"`
	Languages                   *Translation `yaml:"languages"`
	Version                     *Translation `yaml:"version"`
	ProfileRemoved              *Translation `yaml:"profile_removed"`
	NoOnlineStreamers           *Translation `yaml:"no_online_streamers"`
	RemoveAll                   *Translation `yaml:"remove_all"`
	AllStreamersRemoved         *Translation `yaml:"all_streamers_removed"`
	MoreSubs                    *Translation `yaml:"more_subs"`
	InvalidReferralLink         *Translation `yaml:"invalid_referral_link"`
	RefereeExists               *Translation `yaml:"referee_exists"`
	ReferralApplied             *Translation `yaml:"referral_applied"`
	OwnReferralLinkHit          *Translation `yaml:"own_referral_link_hit"`
	SubscriptionUsage           *Translation `yaml:"subscription_usage"`
	SubscriptionUsageAd         *Translation `yaml:"subscription_usage_ad"`
	NotEnoughSubscriptions      *Translation `yaml:"not_enough_subscriptions"`
	Week                        *Translation `yaml:"week"`
	WeekChunk                   *Translation `yaml:"week_chunk"`
	WeekNeverOnline             *Translation `yaml:"week_never_online"`
	Month                       *Translation `yaml:"month"`
	MonthChunk                  *Translation `yaml:"month_chunk"`
	MonthNeverOnline            *Translation `yaml:"month_never_online"`
	ZeroSubscriptions           *Translation `yaml:"zero_subscriptions"`
	FAQ                         *Translation `yaml:"faq"`
	RawCommands                 *Translation `yaml:"raw_commands"`
	Settings                    *Translation `yaml:"settings"`
	OK                          *Translation `yaml:"ok"`
	TooManySubscriptionsForPics *Translation `yaml:"too_many_subscriptions_for_pics"`
	WeAreUp                     *Translation `yaml:"we_are_up"`
	FieldsCustomizationHint     *Translation `yaml:"fields_customization_hint"`
	BotLinkHint                 *Translation `yaml:"bot_link_hint"`
	ImageUnavailable            *Translation `yaml:"image_unavailable"`
	SearchButton                *Translation `yaml:"search_button"`
	SearchHeader                *Translation `yaml:"search_header"`
	SearchPlaceholder           *Translation `yaml:"search_placeholder"`
	SearchNoResults             *Translation `yaml:"search_no_results"`
	SearchFailed                *Translation `yaml:"search_failed"`
	SearchFailedToAdd           *Translation `yaml:"search_failed_to_add"`
	BuySubsPackageButton        *Translation `yaml:"buy_subs_package_button"`
	BuySubsInvoiceTitle         *Translation `yaml:"buy_subs_invoice_title"`
	BuySubsInvoiceDescription   *Translation `yaml:"buy_subs_invoice_description"`
	BuySubsInvoiceLabel         *Translation `yaml:"buy_subs_invoice_label"`
	BuyInvoiceFailed            *Translation `yaml:"buy_invoice_failed"`
	BuyInvoiceExpired           *Translation `yaml:"buy_invoice_expired"`
	BuyAlreadyCredited          *Translation `yaml:"buy_already_credited"`
	BuyAdminsOnly               *Translation `yaml:"buy_admins_only"`
	SubsPurchased               *Translation `yaml:"subs_purchased"`
	AffiliateStatus             *Translation `yaml:"affiliate_status"`
	AffiliateInvalid            *Translation `yaml:"affiliate_invalid"`
	AdminsOnly                  *Translation `yaml:"admins_only"`
	AffiliateNothingToReset     *Translation `yaml:"affiliate_nothing_to_reset"`
	AffiliateInstructions       *Translation `yaml:"affiliate_instructions"`
	AffiliateCommand            *Translation `yaml:"affiliate_command"`
	AffiliateGroupsOnly         *Translation `yaml:"affiliate_groups_only"`
	GroupsOnly                  *Translation `yaml:"groups_only"`
	Timezone                    *Translation `yaml:"timezone"`
	TimezoneInvalid             *Translation `yaml:"timezone_invalid"`
	TimezoneButton              *Translation `yaml:"timezone_button"`
	TimezoneAppHeader           *Translation `yaml:"timezone_app_header"`
	TimezoneAppCurrent          *Translation `yaml:"timezone_app_current"`
	TimezoneAppDetected         *Translation `yaml:"timezone_app_detected"`
	TimezoneAppPlaceholder      *Translation `yaml:"timezone_app_placeholder"`
	TimezoneAppNoResults        *Translation `yaml:"timezone_app_no_results"`
	TimezoneAppFailed           *Translation `yaml:"timezone_app_failed"`
	RemoveButton                *Translation `yaml:"remove_button"`
	RemovalAppHeader            *Translation `yaml:"removal_app_header"`
	RemovalAppPlaceholder       *Translation `yaml:"removal_app_placeholder"`
	RemovalAppNoSubscriptions   *Translation `yaml:"removal_app_no_subscriptions"`
	RemovalAppNoResults         *Translation `yaml:"removal_app_no_results"`
	RemovalAppFailed            *Translation `yaml:"removal_app_failed"`
	RemovalAppFailedToRemove    *Translation `yaml:"removal_app_failed_to_remove"`
}

Translations represents a collection of translated texts for Telegram messages

func (*Translations) ToMap

func (x *Translations) ToMap() map[string]*Translation

ToMap returns translations as a map

type VerbosityKind

type VerbosityKind int

VerbosityKind represents logging verbosity

var Verbosity VerbosityKind = DbgVerbosity

Verbosity is the current logging verbosity

Jump to

Keyboard shortcuts

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