Documentation ¶
Overview ¶
Package bot provides the internal machinery for most of Gopherbot.
Index ¶
- func GetEvents() *[]Event
- func Initialize(handler robot.Handler, l *log.Logger) robot.Connector
- func Log(l robot.LogLevel, m string, v ...interface{}) bool
- func ReadBinary(in io.Reader) (*[]byte, error)
- func ReadBinaryFile(filename string) (*[]byte, error)
- func RegisterConnector(name string, connstarter func(robot.Handler, *log.Logger) robot.Connector)
- func RegisterHistoryProvider(name string, provider func(robot.Handler) robot.HistoryProvider)
- func RegisterJob(name string, gojob robot.JobHandler)
- func RegisterPlugin(name string, plug robot.PluginHandler)
- func RegisterPreload(s string)
- func RegisterSimpleBrain(name string, provider func(robot.Handler) robot.SimpleBrain)
- func RegisterTask(name string, privRequired bool, gotask robot.TaskHandler)
- func Start(v VersionInfo)
- func StartTest(v VersionInfo, cfgdir, logfile string, t *testing.T) (chan bool, robot.Connector)
- func Wrap(s string, limit int) string
- func WriteBase64(out io.Writer, b *[]byte) error
- func WriteBase64File(filename string, b *[]byte) error
- type ChannelInfo
- type ConfigLoader
- type Event
- type InputMatcher
- type Job
- type JobTrigger
- type LoadableModule
- type NameSpace
- type Plugin
- type PluginHelp
- type Robot
- func (r Robot) AddCommand(plugname, command string) robot.RetVal
- func (r Robot) AddJob(name string, args ...string) robot.RetVal
- func (r Robot) AddTask(name string, args ...string) robot.RetVal
- func (r Robot) CheckAdmin() bool
- func (r Robot) CheckinDatum(key, locktoken string)
- func (r Robot) CheckoutDatum(key string, datum interface{}, rw bool) (locktoken string, exists bool, ret robot.RetVal)
- func (r Robot) Direct() robot.Robot
- func (r Robot) Elevate(immediate bool) bool
- func (r Robot) Email(subject string, messageBody *bytes.Buffer, html ...bool) (ret robot.RetVal)
- func (r Robot) EmailAddress(address, subject string, messageBody *bytes.Buffer, html ...bool) (ret robot.RetVal)
- func (r Robot) EmailUser(user, subject string, messageBody *bytes.Buffer, html ...bool) (ret robot.RetVal)
- func (r Robot) Exclusive(tag string, queueTask bool) (success bool)
- func (r Robot) ExtendNamespace(ext string, histories int) bool
- func (r Robot) FailCommand(plugname, command string) robot.RetVal
- func (r Robot) FailTask(name string, args ...string) robot.RetVal
- func (r Robot) FinalCommand(plugname, command string) robot.RetVal
- func (r Robot) FinalTask(name string, args ...string) robot.RetVal
- func (r Robot) Fixed() robot.Robot
- func (r Robot) GetBotAttribute(a string) *robot.AttrRet
- func (r Robot) GetMessage() *robot.Message
- func (r Robot) GetParameter(key string) string
- func (r Robot) GetRepoData() map[string]robot.Repository
- func (r Robot) GetSenderAttribute(a string) *robot.AttrRet
- func (r Robot) GetTaskConfig(dptr interface{}) robot.RetVal
- func (r Robot) GetUserAttribute(u, a string) *robot.AttrRet
- func (r Robot) Log(l robot.LogLevel, msg string, v ...interface{}) (logged bool)
- func (r Robot) MessageFormat(f robot.MessageFormat) robot.Robot
- func (r Robot) Pause(s float64)
- func (r Robot) PromptForReply(regexID string, prompt string, v ...interface{}) (string, robot.RetVal)
- func (r Robot) PromptUserChannelForReply(regexID string, user string, channel string, prompt string, v ...interface{}) (string, robot.RetVal)
- func (r Robot) PromptUserForReply(regexID string, user string, prompt string, v ...interface{}) (string, robot.RetVal)
- func (r Robot) RaisePriv(reason string)
- func (r Robot) RandomInt(n int) int
- func (r Robot) RandomString(s []string) string
- func (r Robot) Recall(key string) string
- func (r Robot) Remember(key, value string)
- func (r Robot) RememberContext(context, value string)
- func (r Robot) Reply(msg string, v ...interface{}) robot.RetVal
- func (r Robot) Say(msg string, v ...interface{}) robot.RetVal
- func (r Robot) SendChannelMessage(ch, msg string, v ...interface{}) robot.RetVal
- func (r Robot) SendUserChannelMessage(u, ch, msg string, v ...interface{}) robot.RetVal
- func (r Robot) SendUserMessage(u, msg string, v ...interface{}) robot.RetVal
- func (r Robot) SetParameter(name, value string) bool
- func (r Robot) SetWorkingDirectory(path string) bool
- func (r Robot) SpawnJob(name string, args ...string) robot.RetVal
- func (r Robot) UpdateDatum(key, locktoken string, datum interface{}) (ret robot.RetVal)
- type ScheduledTask
- type Task
- type TaskSettings
- type TaskSpec
- type UserInfo
- type VersionInfo
- type Wrapper
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Initialize ¶
Initialize sets up the connector and returns a connector object
func ReadBinary ¶
ReadBinary reads a binary reader, detecting and decoding base64
func ReadBinaryFile ¶
ReadBinaryFile reads a binary file, detecting and decoding base64
func RegisterConnector ¶
RegisterConnector should be called in an init function to register a type of connector. Currently only Slack is implemented.
func RegisterHistoryProvider ¶
func RegisterHistoryProvider(name string, provider func(robot.Handler) robot.HistoryProvider)
RegisterHistoryProvider allows history implementations to register a function with a named provider type that returns a HistoryProvider interface.
func RegisterJob ¶
func RegisterJob(name string, gojob robot.JobHandler)
RegisterJob registers a Go job
func RegisterPlugin ¶
func RegisterPlugin(name string, plug robot.PluginHandler)
RegisterPlugin allows Go plugins to register a PluginHandler in a func init(). Also called for new plugins loaded with a loadable module. When the bot initializes, it will call each plugin's handler with a command "init", empty channel, the bot's username, and no arguments, so the plugin can store this information for, e.g., scheduled jobs. See robot/structs.go for the pluginHandlers definition.
func RegisterPreload ¶
func RegisterPreload(s string)
RegisterPreload empty declaration for static builds
func RegisterSimpleBrain ¶
func RegisterSimpleBrain(name string, provider func(robot.Handler) robot.SimpleBrain)
RegisterSimpleBrain allows brain implementations to register a function with a named brain type that returns an SimpleBrain interface. This can only be called from a brain provider's init() function(s). Pass in a Logger so the brain can log it's own error messages if needed.
func RegisterTask ¶
func RegisterTask(name string, privRequired bool, gotask robot.TaskHandler)
RegisterTask registers a Go task. If prevRequired is set, the task can only be added to a privileged pipeline.
func StartTest ¶
StartTest will start a robot for testing, and return the exit / robot stopped channel
func WriteBase64 ¶
WriteBase64 writes out a #GOPHERBOT-BASE64-DATA file
func WriteBase64File ¶
WriteBase64File writes a byte slice to a #GOPHERBOT-BASE64-DATA file
Types ¶
type ChannelInfo ¶
type ChannelInfo struct {
ChannelName, ChannelID string // human-readable and protocol-internal channel representations
}
ChannelInfo maps channel IDs to channel names when the connector doesn't provide a sensible name for use in configuration files.
type ConfigLoader ¶
type ConfigLoader struct { AdminContact string // Contact info for whomever administers the robot MailConfig botMailer // configuration for sending email Protocol string // Name of the connector protocol to use, e.g. "slack" ProtocolConfig json.RawMessage // Protocol-specific configuration, type for unmarshalling arbitrary config BotInfo *UserInfo // Information about the robot UserRoster []UserInfo // List of users and related attributes ChannelRoster []ChannelInfo // List of channels mapping names to IDs Brain string // Type of Brain to use BrainConfig json.RawMessage // Brain-specific configuration, type for unmarshalling arbitrary config EncryptBrain bool // Whether the brain should be encrypted EncryptionKey string // used to decrypt the "real" encryption key HistoryProvider string // Name of provider to use for storing and retrieving job/plugin histories HistoryConfig json.RawMessage // History provider specific configuration WorkSpace string // Read/Write area the robot uses to do work DefaultElevator string // Elevator plugin to use by default for ElevatedCommands and ElevateImmediateCommands DefaultAuthorizer string // Authorizer plugin to use by default for AuthorizedCommands, or when AuthorizeAllCommands = true DefaultMessageFormat string // How the robot should format outgoing messages unless told otherwise; default: Raw DefaultAllowDirect bool // Whether plugins are available in a DM by default IgnoreUnlistedUsers bool // Drop all messages from id not in the UserRoster DefaultChannels []string // Channels where plugins are active by default, e.g. [ "general", "random" ] IgnoreUsers []string // Users the 'bot never talks to - like other bots JoinChannels []string // Channels the 'bot should join when it logs in (not supported by all protocols) DefaultJobChannel string // Where job status is posted by default TimeZone string // For evaluating the hour in a job schedule ExternalJobs map[string]TaskSettings // list of available jobs; config in conf/jobs/<jobname>.yaml ExternalPlugins map[string]TaskSettings // List of non-Go plugins to load; config in conf/plugins/<plugname>.yaml ExternalTasks map[string]TaskSettings // List executables that can be added to a pipeline (but can't start one) GoJobs map[string]TaskSettings // settings for go jobs; config in conf/jobs/<jobname>.yaml GoPlugins map[string]TaskSettings // settings for go plugins; config in conf/plugins/<plugname>.yaml GoTasks map[string]TaskSettings // settings for go tasks NameSpaces map[string]TaskSettings // namespaces for shared parameters & memory sharing LoadableModules map[string]LoadableModule // List of loadable modules to load ScheduledJobs []ScheduledTask // see tasks.go AdminUsers []string // List of users who can access administrative commands Alias string // One-character alias for commands directed at the 'bot, e.g. ';open the pod bay doors' LocalPort int // Port number for listening on localhost, for CLI plugins LogLevel string // Initial log level, can be modified by plugins. One of "trace" "debug" "info" "warn" "error" }
ConfigLoader defines 'bot configuration, and is read from conf/robot.yaml Digested content ends up in currentCfg, see bot_process.go.
type Event ¶
type Event int
Event is a type for message disposition events
const ( IgnoredUser Event = iota BotDirectMessage AdminCheckPassed AdminCheckFailed MultipleMatchesNoAction AuthNoRunMisconfigured AuthNoRunPlugNotAvailable AuthRanSuccess AuthRanFail AuthRanMechanismFailed AuthRanFailNormal AuthRanFailOther AuthNoRunNotFound ElevNoRunMisconfigured ElevNoRunNotAvailable ElevRanSuccess ElevRanFail ElevRanMechanismFailed ElevRanFailNormal ElevRanFailOther ElevNoRunNotFound CommandTaskRan AmbientTaskRan CatchAllsRan CatchAllTaskRan TriggeredTaskRan SpawnedTaskRan ScheduledTaskRan JobTaskRan GoPluginRan ExternalTaskBadPath ExternalTaskBadInterpreter ExternalTaskRan ExternalTaskStderrOutput ExternalTaskErrExit )
type InputMatcher ¶
type InputMatcher struct { Regex string // The regular expression string to match - bot adds ^\w* & \w*$ Command string // The name of the command to pass to the plugin with it's arguments Label string // ReplyMatchers use "Label" instead of "Command" Contexts []string // label the contexts corresponding to capture groups, for supporting "it" & optional args // contains filtered or unexported fields }
InputMatcher specifies the command or message to match for a plugin
type Job ¶
type Job struct { Quiet bool // whether to quash "job started/ended" messages KeepLogs int // how many runs of this job/plugin to keep history for Triggers []JobTrigger // user/regex that triggers a job, e.g. a git-activated webhook or integration Arguments []InputMatcher // list of arguments to prompt the user for *Task }
Job - configuration only applicable to jobs. Read in from conf/jobs/<job>.yaml, which can also include anything from a Task.
type JobTrigger ¶
type JobTrigger struct { Regex string // The regular expression string to match - bot adds ^\w* & \w*$ User string // required user to trigger this job, normally git-activated webhook or integration Channel string // required channel for the trigger // contains filtered or unexported fields }
JobTrigger specifies a user and message to trigger a job
type LoadableModule ¶
LoadableModule struct for loading external modules.
type NameSpace ¶
type NameSpace struct { Description string // optional description of the shared namespace Parameters []robot.Parameter // Parameters for the shared namespace // contains filtered or unexported fields }
NameSpace just stores a name, description, and parameters - they cannot be run.
type Plugin ¶
type Plugin struct { AdminCommands []string // A list of commands only a bot admin can use ElevatedCommands []string // Commands that require elevation, usually via 2fa ElevateImmediateCommands []string // Commands that always require elevation promting, regardless of timeouts AuthorizedCommands []string // Which commands to authorize AuthorizeAllCommands bool // when ALL commands need to be authorized Help []PluginHelp // All the keyword sets / help texts for this plugin CommandMatchers []InputMatcher // Input matchers for messages that need to be directed to the 'bot MessageMatchers []InputMatcher // Input matchers for messages the 'bot hears even when it's not being spoken to CatchAll bool // Whenever the robot is spoken to, but no plugin matches, plugins with CatchAll=true get called with command="catchall" and argument=<full text of message to robot> MatchUnlisted bool // Set to true if ambient messages matches should be checked for users not listed in the UserRoster *Task }
Plugin specifies the structure of a plugin configuration - plugins should include an example / default config. Custom plugin configuration will be loaded from conf/plugins/<plugin>.yaml, which can also include anything from a Task.
type PluginHelp ¶
type PluginHelp struct { Keywords []string // match words for 'help XXX' Helptext []string // help string to give for the keywords, conventionally starting with (bot) for commands or (hear) when the bot needn't be addressed directly }
PluginHelp specifies keywords and help text for the 'bot help system
type Robot ¶
Robot is the internal struct for a robot.Message, with bits copied from the pipeContext; see that struct for better descriptions. A new Robot is created for every task, plugin or job executed by callTask(...).
func (Robot) AddCommand ¶
AddCommand adds a plugin command to the pipeline. The command string argument should match a CommandMatcher for the given plugin.
func (Robot) AddJob ¶
AddJob puts another job in the queue for the pipeline. The added job will run in a new separate context, and when it completes the current pipeline will resume if the job succeeded.
func (Robot) AddTask ¶
AddTask puts another task (job or plugin) in the queue for the pipeline. Unlike other CI/CD tools, gopherbot pipelines are code generated, not configured; it is, however, trivial to write code that reads an arbitrary configuration file and uses AddTask to generate a pipeline. When the task is a plugin, cmdargs should be a command followed by arguments. For jobs, cmdargs are just arguments passed to the job.
func (Robot) CheckAdmin ¶
CheckAdmin returns true if the user is a configured administrator of the robot, and true for automatic tasks. Should be used sparingly, when a single plugin has multiple commands, some which require admin. Otherwise the plugin should just configure RequireAdmin: true
func (Robot) CheckinDatum ¶
CheckinDatum unlocks a datum without updating it, it always succeeds
func (Robot) CheckoutDatum ¶
func (r Robot) CheckoutDatum(key string, datum interface{}, rw bool) (locktoken string, exists bool, ret robot.RetVal)
CheckoutDatum gets a datum from the robot's brain and unmarshals it into a struct. If rw is set, the datum is checked out read-write and a non-empty lock token is returned that expires after lockTimeout (250ms). The bool return indicates whether the datum exists. Datum must be a pointer to a var.
func (Robot) Direct ¶
Direct is a convenience function for initiating a DM conversation with a user. Created initially so a plugin could prompt for a password in a DM.
func (Robot) Elevate ¶
Elevate lets a plugin request elevation on the fly. When immediate = true, the elevator should always prompt for 2fa; otherwise a configured timeout should apply.
func (Robot) Email ¶
Email provides a simple interface for sending the user an email from the bot. It relies on both the robot and the user having an email address. For the robot, this can be conifigured in gopherbot.conf, Email attribute. For the user, this should be provided by the chat protocol, or in gopherbot.conf. It returns an error and b.RetVal != 0 if there's a problem.
func (Robot) EmailAddress ¶
func (r Robot) EmailAddress(address, subject string, messageBody *bytes.Buffer, html ...bool) (ret robot.RetVal)
EmailAddress is a method for sending an email to a specified address. See Email.
func (Robot) EmailUser ¶
func (r Robot) EmailUser(user, subject string, messageBody *bytes.Buffer, html ...bool) (ret robot.RetVal)
EmailUser is a method for sending an email to a specified user. See Email.
func (Robot) Exclusive ¶
Exclusive lets a pipeline request exclusive execution, to prevent jobs from stomping on each other when it's not safe. The string argument ("" allowed) is appended to the pipeline namespace to allow for greater granularity; e.g. two builds of different packages could use the same pipeline and run safely together, but if it's the same package the pipeline might want to queue or just abort. The queueTask argument indicates whether the pipeline should queue up to be restarted, or abort at the end of the current task. When Exclusive returns false, the current task should exit. If the task requests queueing, it will either re-run (if the lock holder has finished) or queue up (if not) when the current task exits. When it's ready to run, the task will be started from the beginning with the same arguments, holding the Exclusive lock, and the call to Exclusive will always succeed. The safest way to use Exclusive is near the beginning of a pipeline.
func (Robot) ExtendNamespace ¶
ExtendNamespace is for CI/CD applications to support building multiple repositories from a single triggered job. When ExtendNamespace is called, all future long-term memory lookups are prefixed with the extended namespace, and a new history is started for the extended namespace, including the branch (needed to differentiate histories for differing branches). It is an error to call ExtendNamespace twice in a single job pipeline, or outside of a running job. The histories argument is interpreted as the number of histories to keep for the extended namespace, or -1 to inherit from the parent job. The jobName must match the repository Type, to protect secret parameters stored in repositories.yaml. Arguments: ext (extension) => "<repository>/<branch>", where repository is listed in
repositories.yaml
histories => number of histories to keep
func (Robot) FailCommand ¶
FailCommand adds a plugin command that runs whenever a pipeline fails, for e.g. emailing the job history. The command string argument should match a CommandMatcher for the given plugin.
func (Robot) FailTask ¶
FailTask adds a task that runs only if the pipeline fails. This can be used to e.g. notify a user / channel on failure.
func (Robot) FinalCommand ¶
FinalCommand adds a plugin command that always runs when a pipeline ends, for e.g. emailing the job history. The command string argument should match a CommandMatcher for the given plugin.
func (Robot) FinalTask ¶
FinalTask adds a task that always runs when the pipeline ends, whether it succeeded or failed. This can be used to ensure that cleanup tasks like terminating a VM or stopping the ssh-agent will run, regardless of whether the pipeline failed. Note that unlike other tasks, final tasks are run in reverse of the order they're added.
func (Robot) Fixed ¶
Fixed is a deprecated convenience function for sending a message with fixed width font.
func (Robot) GetBotAttribute ¶
GetBotAttribute returns an attribute of the robot or "" if unknown. Current attributes: name, alias, fullName, contact
func (Robot) GetMessage ¶
GetMessage returns a pointer to the message struct
func (Robot) GetParameter ¶
GetParameter retrieves the value of a parameter for a namespace. Only useful for Go plugins; external scripts have all parameters for the NameSpace stored as environment variables. Note that runtasks.go populates the environment with Stored parameters, too. So GetParameter is useful for both short-term parameters in a pipeline, and for getting long-term parameters such as credentials.
func (Robot) GetRepoData ¶
func (r Robot) GetRepoData() map[string]robot.Repository
GetRepoData returns the contents of configPath/conf/repodata.yaml, or an empty map/dict/hash. Mainly for GopherCI, Methods for Python and Ruby will retrieve it. Returns nil and logs an error if the calling task isn't a job, or the namespace has already been extended.
func (Robot) GetSenderAttribute ¶
GetSenderAttribute returns a AttrRet with - The string Attribute of the sender, or "" if unknown/error - A RetVal which is one of Ok, UserNotFound, AttributeNotFound Current attributes: name(handle), fullName, email, firstName, lastName, phone, internalID TODO: (see above)
func (Robot) GetTaskConfig ¶
GetTaskConfig sets a struct pointer to point to a config struct populated from configuration when plugins were loaded. To use, a plugin should define a struct for it's configuration data, e.g.:
type pConf struct { Username, Password string }
In conf/plugins/<pluginname>.yaml, you would add a Config: stanza, e.g.:
Config: Username: foo Password: bar
When registering the plugin, you pass a pointer to an empty config template, which the robot will use to populate a struct when configuration is loaded:
func init() { bot.RegisterPlugin("memes", bot.PluginHandler{ DefaultConfig: defaultConfig, // yaml string providing default configuration Handler: plugfunc, // callback function Config: &pConf{}, // pointer to empty config struct }) }
Then, to get a current copy of configuration when the plugin runs, define a struct pointer and call GetTaskConfig with a double-pointer:
var c *pConf r.GetTaskConfig(&c)
... And voila! *pConf is populated with the contents from the configured Config: stanza
func (Robot) GetUserAttribute ¶
GetUserAttribute returns a AttrRet with - The string Attribute of a user, or "" if unknown/error - A RetVal which is one of Ok, UserNotFound, AttributeNotFound Current attributes: name(handle), fullName, email, firstName, lastName, phone, internalID TODO: supplement data with robot.yaml user's table, if an admin wants to supplment whats available from the protocol.
func (Robot) Log ¶
Log logs a message to the robot's log file (or stderr) if the level is lower than or equal to the robot's current log level
func (Robot) MessageFormat ¶
func (r Robot) MessageFormat(f robot.MessageFormat) robot.Robot
MessageFormat returns a robot object with the given format, most likely for a plugin that will mostly use e.g. Variable format.
func (Robot) PromptForReply ¶
func (r Robot) PromptForReply(regexID string, prompt string, v ...interface{}) (string, robot.RetVal)
PromptForReply lets a plugin direct a prompt string to a user and temporarily register a regex for a reply expected to a multi-step command when the robot needs more info. If the regular expression matches, it returns the matched text and RetVal = Ok. If there's an error getting the reply, it returns an empty string with one of the following RetVals:
UserNotFound ChannelNotFound Interrupted - the user canceled with '-' UseDefaultValue - user supplied a single "=", meaning "use the default value" ReplyNotMatched - didn't successfully match for any reason MatcherNotFound - the regexId didn't correspond to a valid regex TimeoutExpired - the user didn't respond within the timeout window
Plugin authors can define regex's for regexId's in the plugin's JSON config, with the restriction that the regexId must start with a lowercase letter. A pre-definied regex from the following list can also be used:
Email Domain - an alpha-numeric domain name OTP - a 6-digit one-time password code IPAddr SimpleString - Characters commonly found in most english sentences, doesn't include special characters like @, {, etc. YesNo
func (Robot) PromptUserChannelForReply ¶
func (r Robot) PromptUserChannelForReply(regexID string, user string, channel string, prompt string, v ...interface{}) (string, robot.RetVal)
PromptUserChannelForReply is identical to PromptForReply, but prompts a specific user in a given channel.
func (Robot) PromptUserForReply ¶
func (r Robot) PromptUserForReply(regexID string, user string, prompt string, v ...interface{}) (string, robot.RetVal)
PromptUserForReply is identical to PromptForReply, but prompts a specific user with a DM.
func (Robot) RaisePriv ¶
RaisePriv lets go plugins raise privilege for a thread, allowing filesystem access in GOPHER_HOME.
func (Robot) RandomInt ¶
RandomInt uses the robot's seeded random to return a random int 0 <= retval < n
func (Robot) RandomString ¶
RandomString is a convenience function for returning a random string from a slice of strings, so that replies can vary.
func (Robot) Remember ¶
Remember adds a short-term memory (with no backing store) to the robot's brain. This is used internally for resolving the meaning of "it", but can be used by plugins to remember other contextual facts. Since memories are indexed by user and channel, but not plugin, these facts can be referenced between plugins. This functionality is considered EXPERIMENTAL.
func (Robot) RememberContext ¶
RememberContext is a convenience function that stores a context reference in short term memories. e.g. RememberContext("server", "web1.my.dom") means that next time the user uses "it" in the context of a "server", the robot will substitute "web1.my.dom".
func (Robot) SendChannelMessage ¶
SendChannelMessage lets a plugin easily send a message to an arbitrary channel. Use Robot.Fixed().SendChannelMessage(...) for fixed-width font.
func (Robot) SendUserChannelMessage ¶
SendUserChannelMessage lets a plugin easily send a message directed to a specific user in a specific channel without fiddling with the robot object. Note that this will fail with UserNotFound if the connector can't resolve usernames, or the username isn't mapped to a user ID in the UserRoster.
func (Robot) SendUserMessage ¶
SendUserMessage lets a plugin easily send a DM to a user. If a DM fails, an error should be returned, since DMs may be used for sending secret/sensitive information.
func (Robot) SetParameter ¶
SetParameter sets a parameter for the current pipeline, useful only for passing parameters (as environment variables) to tasks later in the pipeline.
func (Robot) SetWorkingDirectory ¶
SetWorkingDirectory sets the working directory of the pipeline for all scripts executed. The value of path is interpreted as follows:
- "/absolute/path" - tasks that follow will start with this workingDirectory; "cleanup" won't work, see tasks/cleanup.sh (unsafe)
- "relative/path" - sets workingDirectory relative to baseDirectory; workSpace or $(pwd) depending on value of Homed for the job/plugin starting the pipeline
- "./sub/directory" - appends to the current workingDirectory
- "." - resets workingDirectory to baseDirectory
Fails if the new working directory doesn't exist See also: tasks/setworkdir.sh for updating working directory in a pipeline
type ScheduledTask ¶
type ScheduledTask struct { Schedule string // timespec for https://godoc.org/github.com/robfig/cron TaskSpec }
ScheduledTask items defined in robot.yaml, mostly for scheduled jobs
type Task ¶
type Task struct { Path string // Path to the external executable for external scripts NameSpace string // callers that share namespace share long-term memories and environment vars; defaults to name if not otherwise set Parameters []robot.Parameter // Fixed parameters for a given job; many jobs will use the same script with differing parameters Description string // description of job or plugin AllowDirect bool // Set this true if this plugin can be accessed via direct message DirectOnly bool // Set this true if this plugin ONLY accepts direct messages Channel string // channel where a job can be interracted with, channel where a scheduled task (job or plugin) runs Channels []string // plugins only; Channels where the plugin is available - rifraf like "memes" should probably only be in random, but it's configurable. If empty uses DefaultChannels AllChannels bool // If the Channels list is empty and AllChannels is true, the plugin should be active in all the channels the bot is in RequireAdmin bool // Set to only allow administrators to access a plugin / run job Users []string // If non-empty, list of all the users with access to this plugin Elevator string // Use an elevator other than the DefaultElevator Authorizer string // a plugin to call for authorizing users, should handle groups, etc. AuthRequire string // an optional group/role name to be passed to the Authorizer plugin, for group/role-based authorization determination // taskID string // 32-char random ID for identifying plugins/jobs ReplyMatchers []InputMatcher // store this here for prompt*reply methods Config json.RawMessage // Arbitrary Plugin configuration, will be stored and provided in a thread-safe manner via GetTaskConfig() Disabled bool // Privileged jobs/plugins run with the privileged UID, privileged tasks // require privileged pipelines. Privileged bool // Homed for jobs/plugins starts the pipeline with c.basePath = ".", Homed tasks // always run in ".", e.g. "ssh-init" Homed bool // contains filtered or unexported fields }
Task configuration is common to tasks, plugins or jobs. Any task, plugin or job can call bot methods. Note that tasks are only defined in robot.yaml, and no external configuration is read in.
type TaskSettings ¶
type TaskSettings struct {
Name, Path, Description, NameSpace string
Disabled bool
Homed bool
Privileged *bool
Parameters []robot.Parameter
}
TaskSettings struct used for configuration of: ExternalPlugins, ExternalJobs, ExternalTasks, GoPlugins, GoJobs, GoTasks and NameSpaces in robot.yaml. Not every field is used in every case.
type TaskSpec ¶
type TaskSpec struct { Name string // name of the job or plugin Command string // plugins only Arguments []string // contains filtered or unexported fields }
TaskSpec is the structure for ScheduledJobs (robot.yaml) and AddTask (robot method)
type UserInfo ¶
type UserInfo struct { UserName string // name that refers to the user in bot config files UserID string // unique/persistent ID given to the user by the connector Email, Phone string // for Get*Attribute() FullName string // for Get*Attribute() FirstName, LastName string // for Get*Attribute() BotUser bool // these users aren't checked against MessageMatchers / ambient messages, and never fall-through to "catchalls" // contains filtered or unexported fields }
UserInfo is listed in the UserRoster of robot.yaml to provide: - Attributes and info that might not be provided by the connector:
- Mapping of protocol internal ID to username
- Additional user attributes such as first / last name, email, etc.
- Additional information needed by bot internals
- BotUser flag
type VersionInfo ¶
type VersionInfo struct {
Version, Commit string
}
VersionInfo holds information about the version, duh. (stupid linter)
type Wrapper ¶
type Wrapper struct { // Breakpoints defines which characters should be able to break a line. // By default, this follows the usual English rules of spaces, and hyphens. // Default: " -" Breakpoints string // Newline defines which characters should be used to split and create new lines. // Default: "\n" Newline string // OutputLinePrefix is prepended to any output lines. This can be useful // for wrapping code-comments and prefixing new lines with "// ". // Default: "" OutputLinePrefix string // OutputLineSuffix is appended to any output lines. // Default: "" OutputLineSuffix string // LimitIncludesPrefixSuffix can be set to false if you don't want prefixes // and suffixes to be included in the length limits. // Default: true LimitIncludesPrefixSuffix bool // TrimPrefix can be set to remove a prefix on each input line. // This can be paired up with OutputPrefix to create a block of C-style // comments (/* * */ ) from a long single-line comment. // Default: "" TrimInputPrefix string // TrimSuffix can be set to remove a suffix on each input line. // Default: "" TrimInputSuffix string // StripTrailingNewline can be set to true if you want the trailing // newline to be removed from the return vailue. // Default: false StripTrailingNewline bool }
Wrapper contains settings for customisable word-wrapping.
func NewWrapper ¶
func NewWrapper() Wrapper
NewWrapper returns a new instance of a Wrapper initialised with defaults.
Source Files ¶
- aescrypt.go
- authorize.go
- available.go
- base64_io.go
- bot_process.go
- brain.go
- builtins.go
- calltask.go
- cli_commands.go
- cli_dump.go
- conf.go
- config_load.go
- constants.go
- debug.go
- dispatch.go
- elevate.go
- email.go
- emit_noop.go
- event_string.go
- events.go
- exclusive.go
- filebrain.go
- go_jobs.go
- handler.go
- history.go
- http.go
- jobbuiltins.go
- jobrun.go
- linebuffer.go
- log.go
- logbuffers.go
- logging.go
- membrain.go
- memhistory.go
- null_connector.go
- pipe_tasks.go
- pipeaddflavor_string.go
- pipeaddtype_string.go
- pipecontext.go
- pipelinetype_string.go
- privsep.go
- replyprompt.go
- robot.go
- robot_connector_methods.go
- robot_pipecmd.go
- run_pipelines.go
- scheduled_jobs.go
- send_message.go
- signal.go
- start.go
- start_t.go
- static.go
- taskconf.go
- tasks.go
- tasktype_string.go
- term_connector.go
- term_sendmessage.go
- util.go
- wrap.go