Documentation
¶
Overview ¶
Package cmdlib contains utlities mostly for bot
Index ¶
- Constants
- Variables
- func BindEnvForConfig(v *viper.Viper, cfg any)
- func CanonicalNicknamePreprocessing(name string) string
- func CheckErr(err error)
- func CloseBody(body io.Closer)
- func CommandFuncs(mention string) template.FuncMap
- func ConfigDirs() []string
- func FindConfig(name string) (string, error)
- func HTTPClientWithProxy(timeout time.Duration, proxyURL *url.URL) *http.Client
- func HTTPClientWithTimeout(timeout time.Duration) *http.Client
- func IntegerHookFunc() mapstructure.DecodeHookFunc
- func Ldbg(format string, v ...interface{})
- func Lerr(format string, v ...interface{})
- func Lfatalf(format string, v ...interface{})
- func Linf(format string, v ...interface{})
- func LoadAllAds(files map[string][]string) (trMap map[string]map[string]*Translation, tpl map[string]*template.Template)
- func LoadAllTranslations(files map[string][]string) (trMap map[string]*Translations, tpl map[string]*template.Template)
- func LoadEndpointTranslations(files []string) (*Translations, AllTranslations)
- func Ltrace(format string, v ...interface{})
- func NoRedirect(_ *http.Request, _ []*http.Request) error
- func OnlineListLine(nickname string, info StreamerInfo) string
- func OnlineQuery(usersOnlineEndpoint string, client *http.Client, headers [][2]string) (*http.Response, *bytes.Buffer, error)
- func OnlineRequest(req *http.Request, client *http.Client) (*http.Response, *bytes.Buffer, error)
- func SetVerbosity(debug bool)
- func StrictConfigDecoder(dc *mapstructure.DecoderConfig)
- func StringToMapHookFunc() mapstructure.DecodeHookFunc
- func StringToSliceHookFunc(sep string) mapstructure.DecodeHookFunc
- func TemplateFuncs() template.FuncMap
- type AllTranslations
- type CheckMode
- type CheckerResults
- type ExistenceListResults
- type FixedListOnlineRequest
- type FixedListOnlineResults
- type FixedListStatusRequest
- type OnlineListRequest
- type OnlineListResults
- type ParseKind
- type Secret
- type ShowKind
- type SingleStatusRequest
- type StatusKind
- type StatusRequest
- type StatusUpdate
- type StreamerInfo
- type StreamerInfoWithStatus
- type StringSetFlag
- type Translation
- type Translations
- type VerbosityKind
Constants ¶
const ( SilentVerbosity = 0 ErrVerbosity = 1 InfVerbosity = 2 DbgVerbosity = 3 TraceVerbosity = 4 )
Verbosity constants
const IdleConnTimeout = 90 * time.Second
IdleConnTimeout is how long a client keeps an idle connection.
Variables ¶
var CommonNicknameRegexp = regexp.MustCompile(`^[a-z0-9\-_@]+$`)
CommonNicknameRegexp is a regular expression to check nicknames
var Version = "(devel)"
Version is the version of the current code state
Functions ¶
func BindEnvForConfig ¶
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 ¶
CanonicalNicknamePreprocessing preprocesses nickname to canonical form
func CommandFuncs ¶
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 ¶
FindConfig returns the path to name in the first config directory holding it. Callers take an explicit path for anywhere else.
func HTTPClientWithProxy ¶
HTTPClientWithProxy returns an HTTP client routing all requests through the given proxy URL (supports http, https, socks5 schemes).
func HTTPClientWithTimeout ¶
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 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 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 ¶
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 ¶
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 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
func (ParseKind) MarshalYAML ¶
MarshalYAML is generated so ParseKind satisfies yaml.Marshaler.
func (*ParseKind) UnmarshalYAML ¶
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 ¶
MarshalJSON 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 )
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 ¶
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"`
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