idx int64 0 41.8k | question stringlengths 69 3.84k | target stringlengths 11 1.18k |
|---|---|---|
200 | func ( e Environment ) String ( name string ) ( string , error ) { return e . value ( name )
} | String returns a string if it exists in the set environment variables . |
201 | func NewJSONFromFile ( path string ) * JSON { return NewJSON ( func ( ) ( io . Reader , error ) { return os . Open ( path )
} )
} | NewJSONFromFile returns an instance of the JSON checker . It reads its data from a file which its location has been specified through the path parameter |
202 | func ( j * JSON ) Setup ( ) error { r , err := j . gen ( )
if err != nil { return err
}
dec := json . NewDecoder ( r )
j . values = make ( map [ string ] interface { } )
return dec . Decode ( & j . values )
} | Setup initializes the JSON Checker |
203 | func ( j * JSON ) Int ( name string ) ( int , error ) { v , err := j . value ( name )
if err != nil { return 0 , err
}
f , ok := v . ( float64 )
if ! ok { return 0 , errors . New ( fmt . Sprintf ( "%T unable" , v ) )
}
return int ( f ) , nil
} | Int returns an int if it exists within the marshalled JSON io . Reader . |
204 | func ( j * JSON ) Bool ( name string ) ( bool , error ) { v , err := j . value ( name )
if err != nil { return false , err
}
b , ok := v . ( bool )
if ! ok { return false , errors . New ( "unable to cast" )
}
return b , nil
} | Bool returns a bool if it exists within the marshalled JSON io . Reader . |
205 | func ( j * JSON ) String ( name string ) ( string , error ) { v , err := j . value ( name )
if err != nil { return "" , err
}
s , ok := v . ( string )
if ! ok { return "" , errors . New ( fmt . Sprintf ( "unable to cast %T" , v ) )
}
return s , nil
} | String returns a string if it exists within the marshalled JSON io . Reader . |
206 | func NewFlag ( ) * Flag { f := & Flag { args : os . Args , defaults : defaultsPrinter , }
return f
} | NewFlag returns a new instance of the Flag Checker using os . Args as its flag source . |
207 | func NewFlagWithUsage ( defaulter func ( ) string ) * Flag { f := & Flag { args : os . Args , defaults : defaulter , }
return f
} | NewFlagWithUsage returns a new instance of the Flag Checker with a custom usage printer . It uses os . Args as its flag source . |
208 | func ( f Flag ) Int ( name string ) ( int , error ) { v , err := f . value ( name )
if err != nil { return 0 , err
}
i , err := strconv . Atoi ( v )
if err != nil { return 0 , err
}
return i , nil
} | Int returns an int if it exists in the set flags . |
209 | func ( f * Flag ) Bool ( name string ) ( bool , error ) { v , err := f . value ( name )
if err != nil { return false , err
}
return strconv . ParseBool ( v )
} | Bool returns a bool if it exists in the set flags . |
210 | func ( f Flag ) String ( name string ) ( string , error ) { return f . value ( name )
} | String returns a string if it exists in the set flags . |
211 | func SetContext ( ctx context . Context , e Entry ) context . Context { return context . WithValue ( ctx , ctxIdent , e )
} | SetContext sets a log entry into the provided context |
212 | func GetContext ( ctx context . Context ) Entry { v := ctx . Value ( ctxIdent )
if v == nil { return newEntryWithFields ( nil )
}
return v . ( Entry )
} | GetContext returns the log Entry found in the context or a new Default log Entry if none is found |
213 | func HandleEntry ( e Entry ) { if ! e . start . IsZero ( ) { e = e . WithField ( "duration" , time . Since ( e . start ) )
}
e . Timestamp = time . Now ( )
rw . RLock ( )
for _ , h := range logHandlers [ e . Level ] { h . Log ( e )
}
rw . RUnlock ( )
} | HandleEntry handles the log entry and fans out to all handlers with the proper log level This is exposed to allow for centralized logging whereby the log entry is marshalled passed to a central logging server unmarshalled and finally fanned out from there . |
214 | func F ( key string , value interface { } ) Field { return Field { Key : key , Value : value }
} | F creates a new Field using the supplied key + value . it is shorthand for defining field manually |
215 | func AddHandler ( h Handler , levels ... Level ) { rw . Lock ( )
for _ , level := range levels { handler := append ( logHandlers [ level ] , h )
logHandlers [ level ] = handler
}
rw . Unlock ( )
} | AddHandler adds a new log handler and accepts which log levels that handler will be triggered for |
216 | func RemoveHandler ( h Handler ) { rw . Lock ( )
OUTER : for lvl , handlers := range logHandlers { for i , handler := range handlers { if h == handler { n := append ( handlers [ : i ] , handlers [ i + 1 : ] ... )
if len ( n ) == 0 { delete ( logHandlers , lvl )
continue OUTER
}
logHandlers [ lvl ] = n
continue OUTER
}
}
}
rw . Unlock ( )
} | RemoveHandler removes an existing handler |
217 | func RemoveHandlerLevels ( h Handler , levels ... Level ) { rw . Lock ( )
OUTER : for _ , lvl := range levels { handlers := logHandlers [ lvl ]
for i , handler := range handlers { if h == handler { n := append ( handlers [ : i ] , handlers [ i + 1 : ] ... )
if len ( n ) == 0 { delete ( logHandlers , lvl )
continue OUTER
}
logHandlers [ lvl ] = n
continue OUTER
}
}
}
rw . Unlock ( )
} | RemoveHandlerLevels removes the supplied levels if no more levels exists for the handler it will no longer be registered and need to to added via AddHandler again . |
218 | func WithTrace ( ) Entry { ne := newEntryWithFields ( logFields )
ne . start = time . Now ( )
return ne
} | WithTrace withh add duration of how long the between this function call and the susequent log |
219 | func WithError ( err error ) Entry { ne := newEntryWithFields ( logFields )
return withErrFn ( ne , err )
} | WithError add a minimal stack trace to the log Entry |
220 | func Infof ( s string , v ... interface { } ) { e := newEntryWithFields ( logFields )
e . Infof ( s , v ... )
} | Infof logs a normal . information entry with formatiing |
221 | func ErrorsGoWithError ( e log . Entry , err error ) log . Entry { ne := new ( log . Entry )
* ne = * ( & e )
flds := make ( [ ] log . Field , 0 , len ( e . Fields ) )
flds = append ( flds , e . Fields ... )
flds = append ( flds , log . Field { Key : "error" , Value : err . Error ( ) } )
ne . Fields = flds
var frame errors . Frame
_ , types , tags , stacks , _ := errors . Inspect ( err )
if len ( stacks ) > 0 { frame = stacks [ len ( stacks ) - 1 ] [ 0 ]
} else { frame = errors . WithStack ( err ) . ( stackTracer ) . StackTrace ( ) [ 2 : ] [ 0 ]
}
name := fmt . Sprintf ( "%n" , frame )
file := fmt . Sprintf ( "%+s" , frame )
line := fmt . Sprintf ( "%d" , frame )
ne . Fields = append ( ne . Fields , log . Field { Key : "source" , Value : fmt . Sprintf ( "%s: %s:%s" , name , file , line ) } )
for _ , tag := range tags { ne . Fields = append ( ne . Fields , log . Field { Key : tag . Name , Value : tag . Value } )
}
if len ( types ) > 0 { ne . Fields = append ( ne . Fields , log . Field { Key : "types" , Value : strings . Join ( types , "," ) } )
}
return * ne
} | ErrorsGoWithError is a custom WithError function that can be used by using log s SetWithErrorFn function . |
222 | func New ( redirectSTDOut bool ) * Console { if redirectSTDOut { done := make ( chan struct { } )
go handleStdLogger ( done )
<- done
}
return & Console { colors : defaultColors , writer : os . Stderr , timestampFormat : "2006-01-02 15:04:05.000000000Z07:00" , displayColor : true , }
} | New returns a new instance of the console logger |
223 | func handleStdLogger ( done chan <- struct { } ) { r , w := io . Pipe ( )
defer func ( ) { _ = r . Close ( )
_ = w . Close ( )
} ( )
stdlog . SetOutput ( w )
scanner := bufio . NewScanner ( r )
go func ( ) { done <- struct { } { }
} ( )
for scanner . Scan ( ) { log . WithField ( "stdlog" , true ) . Info ( scanner . Text ( ) )
}
} | this will redirect the output of |
224 | func ( e Entry ) Debug ( v ... interface { } ) { e . Message = fmt . Sprint ( v ... )
e . Level = DebugLevel
HandleEntry ( e )
} | Debug logs a debug entry |
225 | func ( e Entry ) Info ( v ... interface { } ) { e . Message = fmt . Sprint ( v ... )
e . Level = InfoLevel
HandleEntry ( e )
} | Info logs a normal . information entry |
226 | func ( e Entry ) Infof ( s string , v ... interface { } ) { e . Message = fmt . Sprintf ( s , v ... )
e . Level = InfoLevel
HandleEntry ( e )
} | Infof logs a normal . information entry with formatting |
227 | func ( e Entry ) Notice ( v ... interface { } ) { e . Message = fmt . Sprint ( v ... )
e . Level = NoticeLevel
HandleEntry ( e )
} | Notice logs a notice log entry |
228 | func ( e Entry ) Warn ( v ... interface { } ) { e . Message = fmt . Sprint ( v ... )
e . Level = WarnLevel
HandleEntry ( e )
} | Warn logs a warn log entry |
229 | func ( e Entry ) Panic ( v ... interface { } ) { e . Message = fmt . Sprint ( v ... )
e . Level = PanicLevel
HandleEntry ( e )
exitFunc ( 1 )
} | Panic logs a panic log entry |
230 | func ( e Entry ) Alert ( v ... interface { } ) { e . Message = fmt . Sprint ( v ... )
e . Level = AlertLevel
HandleEntry ( e )
} | Alert logs an alert log entry |
231 | func ( e Entry ) Fatal ( v ... interface { } ) { e . Message = fmt . Sprint ( v ... )
e . Level = FatalLevel
HandleEntry ( e )
exitFunc ( 1 )
} | Fatal logs a fatal log entry |
232 | func ( e Entry ) Error ( v ... interface { } ) { e . Message = fmt . Sprint ( v ... )
e . Level = ErrorLevel
HandleEntry ( e )
} | Error logs an error log entry |
233 | func ErrorsWithError ( e log . Entry , err error ) log . Entry { ne := new ( log . Entry )
* ne = * ( & e )
flds := make ( [ ] log . Field , 0 , len ( e . Fields ) )
flds = append ( flds , e . Fields ... )
flds = append ( flds , log . Field { Key : "error" , Value : err . Error ( ) } )
ne . Fields = flds
var frame errors . Frame
if s , ok := err . ( stackTracer ) ; ok { frame = s . StackTrace ( ) [ 0 ]
} else { frame = errors . WithStack ( err ) . ( stackTracer ) . StackTrace ( ) [ 2 : ] [ 0 ]
}
name := fmt . Sprintf ( "%n" , frame )
file := fmt . Sprintf ( "%+s" , frame )
line := fmt . Sprintf ( "%d" , frame )
parts := strings . Split ( file , "\n\t" )
\n
\t
if len ( parts ) > 1 { file = parts [ 1 ]
}
} | ErrorsWithError is a custom WithError function that can be used by using log s SetWithErrorFn function . |
234 | func ( s * Syslog ) GetDisplayColor ( level log . Level ) ansi . EscSeq { return s . colors [ level ]
} | GetDisplayColor returns the color for the given log level |
235 | func New ( host string , port int , username string , password string , from string , to [ ] string ) * Email { e := & Email { enabled : true , timestampFormat : log . DefaultTimeFormat , host : host , port : port , username : username , password : password , from : from , to : to , formatFunc : defaultFormatFunc , }
e . SetTemplate ( defaultTemplate )
return e
} | New returns a new instance of the email logger |
236 | func ( email * Email ) SetTemplate ( htmlTemplate string ) { email . rw . Lock ( )
defer email . rw . Unlock ( )
email . template = template . Must ( template . New ( "email" ) . Funcs ( template . FuncMap { "ts" : func ( e log . Entry ) ( ts string ) { ts = e . Timestamp . Format ( email . timestampFormat )
return
} , } , ) . Parse ( htmlTemplate ) )
} | SetTemplate sets Email s html template to be used for email body |
237 | func ( email * Email ) SetFormatFunc ( fn FormatFunc ) { email . rw . Lock ( )
defer email . rw . Unlock ( )
email . formatFunc = fn
} | SetFormatFunc sets FormatFunc each worker will call to get a Formatter func |
238 | func ( email * Email ) SetEmailConfig ( host string , port int , username string , password string , from string , to [ ] string ) { email . rw . Lock ( )
defer email . rw . Unlock ( )
email . host = host
email . port = port
email . username = username
email . password = password
email . from = from
email . to = to
email . formatter = email . formatFunc ( email )
} | SetEmailConfig allows updating of the email config in flight and is thread safe . |
239 | func ( email * Email ) SetEnabled ( enabled bool ) { email . rw . Lock ( )
defer email . rw . Unlock ( )
email . enabled = enabled
} | SetEnabled enables or disables the email handler sending emails |
240 | func ( c * CustomHandler ) Log ( e log . Entry ) { b := new ( bytes . Buffer )
b . Reset ( )
b . WriteString ( e . Message )
for _ , f := range e . Fields { fmt . Fprintf ( b , " %s=%v" , f . Key , f . Value )
}
fmt . Println ( b . String ( ) )
} | Log accepts log entries to be processed |
241 | func New ( remoteHost string , method string , header stdhttp . Header ) ( * HTTP , error ) { if _ , err := url . Parse ( remoteHost ) ; err != nil { return nil , err
}
h := & HTTP { remoteHost : remoteHost , timestampFormat : log . DefaultTimeFormat , header : header , method : method , client : stdhttp . Client { } , formatFunc : defaultFormatFunc , }
return h , nil
} | New returns a new instance of the http logger |
242 | func New ( api APIVersion , remoteHost string , contentType string , authToken string , application string ) ( * HipChat , error ) { authToken = "Bearer " + authToken
client := & stdhttp . Client { }
req , err := stdhttp . NewRequest ( "GET" , remoteHost + "?auth_test=true" , nil )
if err != nil { return nil , err
}
req . Header . Add ( "Authorization" , authToken )
resp , err := client . Do ( req )
if err != nil { return nil , err
}
if resp . StatusCode != stdhttp . StatusAccepted { bt , _ := ioutil . ReadAll ( resp . Body )
return nil , fmt . Errorf ( "HipChat authorization failed\n %s" , \n )
}
string ( bt )
header := make ( stdhttp . Header )
header . Set ( "Content-Type" , contentType )
header . Set ( "Authorization" , authToken )
hc := & HipChat { colors : defaultColors , api : api , application : application , }
hc . HTTP , _ = http . New ( strings . TrimRight ( remoteHost , "/" ) + "/notification" , method , header )
hc . HTTP . SetFormatFunc ( formatFunc ( hc ) )
hc . SetTemplate ( defaultTemplate )
} | New returns a new instance of the HipChat logger |
243 | func ( hc * HipChat ) SetTemplate ( htmlTemplate string ) { hc . template = template . Must ( template . New ( "hipchat" ) . Funcs ( template . FuncMap { "ts" : func ( e log . Entry ) ( ts string ) { ts = e . Timestamp . Format ( hc . TimestampFormat ( ) )
return
} , } , ) . Parse ( htmlTemplate ) )
} | SetTemplate sets Hipchats html template to be used for email body |
244 | func RandAlphaNumSeq ( n int ) string { b := make ( [ ] rune , n )
for i := range b { b [ i ] = alphaNum [ rand . Intn ( len ( alphaNum ) ) ]
}
return string ( b )
} | RandAlphaNumSeq generates a random sequence of alpha - numeric characters of length n . |
245 | func ( s * ScheduledEvent ) Send ( c * sms . Conn ) error { switch s . FlexIDType { case FIDTPhone : if err := c . Send ( s . FlexID , s . Content ) ; err != nil { return err
}
default : return fmt . Errorf ( "unrecognized flexidtype: %d" , s . FlexIDType )
}
return nil
} | Send a scheduled event . Currently only phones are supported . |
246 | func preprocess ( r * http . Request ) ( * dt . Msg , error ) { req := & dt . Request { }
err := json . NewDecoder ( r . Body ) . Decode ( req )
if err != nil { log . Info ( "could not parse empty body" , err )
return nil , err
}
sendPostReceiveEvent ( & req . CMD )
u , err := dt . GetUser ( db , req )
if err != nil { return nil , err
}
sendPreProcessingEvent ( & req . CMD , u )
return NewMsg ( u , req . CMD )
} | preprocess converts a user input into a Msg that s been persisted to the database |
247 | func NewMsg ( u * dt . User , cmd string ) ( * dt . Msg , error ) { tokens := TokenizeSentence ( cmd )
stems := StemTokens ( tokens )
si := ner . classifyTokens ( tokens )
for pluginID , c := range bClassifiers { scores , idx , _ := c . ProbScores ( stems )
log . Debug ( "intent score" , pluginIntents [ pluginID ] [ idx ] , scores [ idx ] )
if scores [ idx ] > 0.7 { si . Intents = append ( si . Intents , string ( pluginIntents [ pluginID ] [ idx ] ) )
}
}
m := & dt . Msg { User : u , Sentence : cmd , Tokens : tokens , Stems : stems , StructuredInput : si , }
if err := saveContext ( db , m ) ; err != nil { return nil , err
}
if err := addContext ( db , m ) ; err != nil { return nil , err
}
return m , nil
} | NewMsg builds a message struct with Tokens Stems and a Structured Input . |
248 | func GetMsg ( db * sqlx . DB , id uint64 ) ( * Msg , error ) { q := `SELECT id, sentence, abotsent FROM messages WHERE id=$1`
m := & Msg { }
if err := db . Get ( m , q , id ) ; err != nil { return nil , err
}
return m , nil
} | GetMsg returns a message for a given message ID . |
249 | func ( m * Msg ) Update ( db * sqlx . DB ) error { q := `UPDATE messages SET needstraining=$1 WHERE id=$2`
if _ , err := db . Exec ( q , m . NeedsTraining , m . ID ) ; err != nil { return err
}
return nil
} | Update a message as needing training . |
250 | func ( m * Msg ) Save ( db * sqlx . DB ) error { var pluginName string
if m . Plugin != nil { pluginName = m . Plugin . Config . Name
}
q := `INSERT INTO messages (userid, sentence, plugin, route, abotsent, needstraining, flexid, flexidtype, trained) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) RETURNING id`
row := db . QueryRowx ( q , m . User . ID , m . Sentence , pluginName , m . Route , m . AbotSent , m . NeedsTraining , m . User . FlexID , m . User . FlexIDType , m . Trained )
if err := row . Scan ( & m . ID ) ; err != nil { return err
}
return nil
} | Save a message to the database updating the message ID . |
251 | func ( m * Msg ) GetLastPlugin ( db * sqlx . DB ) ( string , string , error ) { var res struct { Plugin string
Route string
}
var err error
if m . User . ID > 0 { q := `SELECT route, plugin FROM messages WHERE userid=$1 AND abotsent IS FALSE ORDER BY createdat DESC`
err = db . Get ( & res , q , m . User . ID )
} else { q := `SELECT route, plugin FROM messages WHERE flexid=$1 AND flexidtype=$2 AND abotsent IS FALSE ORDER BY createdat DESC`
err = db . Get ( & res , q , m . User . FlexID , m . User . FlexIDType )
}
if err != nil && err != sql . ErrNoRows { return "" , "" , err
}
return res . Plugin , res . Route , nil
} | GetLastPlugin for a given user so the previous plugin can be called again if no new trigger is detected . |
252 | func Open ( driverName , auth string ) ( * Conn , error ) { driversMu . RLock ( )
driveri , ok := drivers [ driverName ]
driversMu . RUnlock ( )
if ! ok { return nil , fmt . Errorf ( "sms: unknown driver %q (forgotten import?)" , driverName )
}
conn , err := driveri . Open ( auth )
if err != nil { return nil , err
}
c := & Conn { driver : driveri , conn : conn , }
return c , nil
} | Open a connection to a registered driver . |
253 | func ( c * Conn ) SendHTML ( to [ ] string , from , subj , html string ) error { return c . conn . SendHTML ( to , from , subj , html )
} | SendHTML email through the opened driver connection . |
254 | func ( c * Conn ) SendPlainText ( to [ ] string , from , subj , plaintext string ) error { return c . conn . SendPlainText ( to , from , subj , plaintext )
} | SendPlainText email through the opened driver connection . |
255 | func saveContext ( db * sqlx . DB , in * dt . Msg ) error { if err := saveTimeContext ( db , in ) ; err != nil { return err
}
if err := savePeopleContext ( db , in ) ; err != nil { return err
}
return nil
} | saveContext records context in the database across multiple categories . |
256 | func saveTimeContext ( db * sqlx . DB , in * dt . Msg ) error { if len ( in . StructuredInput . Times ) == 0 { return nil
}
byt , err := json . Marshal ( in . StructuredInput . Times )
if err != nil { return err
}
if in . User . ID > 0 { q := `INSERT INTO states (key, value, userid, pluginname) VALUES ($1, $2, $3, '') ON CONFLICT (userid, pluginname, key) DO UPDATE SET value=$2`
_ , err = db . Exec ( q , keyContextTime , byt , in . User . ID )
} else { q := `INSERT INTO states (key, value, flexid, flexidtype, pluginname) VALUES ($1, $2, $3, $4, '') ON CONFLICT (flexid, flexidtype, pluginname, key) DO UPDATE SET value=$2`
_ , err = db . Exec ( q , keyContextTime , byt , in . User . FlexID , in . User . FlexIDType )
}
if err != nil { return err
}
return nil
} | saveTimeContext records contextual information about the time being discussed enabling Abot to replace things like then with the time it should represent . |
257 | func savePeopleContext ( db * sqlx . DB , in * dt . Msg ) error { if len ( in . StructuredInput . People ) == 0 { return nil
}
byt , err := json . Marshal ( in . StructuredInput . People )
if err != nil { return err
}
if in . User . ID > 0 { q := `INSERT INTO states (key, value, userid, pluginname) VALUES ($1, $2, $3, '') ON CONFLICT (userid, pluginname, key) DO UPDATE SET value=$2`
_ , err = db . Exec ( q , keyContextPeople , byt , in . User . ID )
} else { q := `INSERT INTO states (key, value, flexid, flexidtype, pluginname) VALUES ($1, $2, $3, $4, '') ON CONFLICT (flexid, flexidtype, pluginname, key) DO UPDATE SET value=$2`
_ , err = db . Exec ( q , keyContextPeople , byt , in . User . FlexID , in . User . FlexIDType )
}
if err != nil { return err
}
return nil
} | savePeopleContext records contextual information about people being discussed enabling Abot to replace things like him her or they with the names the pronouns represent . |
258 | func addTimeContext ( db * sqlx . DB , in * dt . Msg ) error { var addContext bool
for _ , stem := range in . Stems { if stem == "then" { addContext = true
break
}
}
if ! addContext { return nil
}
var byt [ ] byte
var err error
if in . User . ID > 0 { q := `SELECT value FROM states WHERE userid=$1 AND key=$2`
err = db . Get ( & byt , q , in . User . ID , keyContextTime )
} else { q := `SELECT value FROM states WHERE flexid=$1 AND flexidtype=$2 AND key=$3`
err = db . Get ( & byt , q , in . User . FlexID , in . User . FlexIDType , keyContextTime )
}
if err == sql . ErrNoRows { return nil
}
if err != nil { return err
}
var times [ ] time . Time
if err = json . Unmarshal ( byt , & times ) ; err != nil { return err
}
in . StructuredInput . Times = times
return nil
} | addTimeContext adds a time context to a Message if the word then is found . |
259 | func addPeopleContext ( db * sqlx . DB , in * dt . Msg ) error { var addContext , singular bool
var sex dt . Sex
for _ , stem := range in . Stems { switch stem { case "us" : addContext = true
case "him" , "he" : addContext , singular = true , true
if sex == dt . SexFemale { sex = dt . SexEither
} else if sex != dt . SexEither { sex = dt . SexMale
}
case "her" , "she" : addContext , singular = true , true
if sex == dt . SexMale { sex = dt . SexEither
} else if sex != dt . SexEither { sex = dt . SexFemale
}
case "them" : addContext = true
sex = dt . SexEither
}
}
if ! addContext { return nil
}
var byt [ ] byte
var err error
if in . User . ID > 0 { q := `SELECT value FROM states WHERE userid=$1 AND key=$2`
err = db . Get ( & byt , q , in . User . ID , keyContextPeople )
} else { q := `SELECT value FROM states WHERE flexid=$1 AND flexidtype=$2 AND key=$3`
err = db . Get ( & byt , q , in . User . FlexID , in . User . FlexIDType , keyContextPeople )
}
if err == sql . ErrNoRows { return nil
}
if err != nil { return err
}
var people [ ] dt . Person
if err = json . Unmarshal ( byt , & people ) ; err != nil { return err
}
if ! singular { in . StructuredInput . People = people
return nil
}
if sex == dt . SexEither { in . StructuredInput . People = [ ] dt . Person { people [ 0 ] }
return nil
}
for _ , person := range people { if person . Sex == sex { in . StructuredInput . People = [ ] dt . Person { person }
break
}
}
return nil
} | addPeopleContext adds people based on context to the sentence when appropriate pronouns are found like us him her or them . |
260 | func ( c classifier ) classifyTokens ( tokens [ ] string ) * dt . StructuredInput { var s dt . StructuredInput
var sections [ ] string
for _ , t := range tokens { var found bool
lower := strings . ToLower ( t )
_ , exists := c [ "C" + lower ]
if exists { s . Commands = append ( s . Commands , lower )
found = true
}
_ , exists = c [ "O" + lower ]
if exists { s . Objects = append ( s . Objects , lower )
found = true
}
var sex dt . Sex
_ , exists = c [ "PM" + lower ]
if exists { _ , exists = c [ "PF" + lower ]
if exists { sex = dt . SexEither
} else { sex = dt . SexMale
}
person := dt . Person { Name : t , Sex : sex , }
s . People = append ( s . People , person )
found = true
}
if sex == dt . SexInvalid { _ , exists = c [ "PF" + lower ]
if exists { person := dt . Person { Name : t , Sex : dt . SexFemale , }
s . People = append ( s . People , person )
found = true
}
}
if found || len ( sections ) == 0 { sections = append ( sections , t )
} else { switch t { case "." , "," , ";" , "?" , "-" , "_" , "=" , "+" , "#" , "@" , "!" , "$" , "%" , "^" , "&" , "*" , "(" , ")" , "'" : continue
}
sections [ len ( sections ) - 1 ] += " " + t
}
}
for _ , sec := range sections { if len ( sec ) == 0 { continue
}
s . Times = append ( s . Times , timeparse . Parse ( sec ) ... )
}
return & s
} | classifyTokens builds a StructuredInput from a tokenized sentence . |
261 | func buildOffensiveMap ( ) ( map [ string ] struct { } , error ) { o := map [ string ] struct { } { }
p := filepath . Join ( "data" , "offensive.txt" )
fi , err := os . Open ( p )
if err != nil { return o , err
}
scanner := bufio . NewScanner ( fi )
scanner . Split ( bufio . ScanLines )
for scanner . Scan ( ) { o [ scanner . Text ( ) ] = struct { } { }
}
err = fi . Close ( )
return o , err
} | buildOffensiveMap creates a map of offensive terms for which Abot will refuse to respond . This helps ensure that users are somewhat respectful to Abot and her human trainers since sentences caught by the OffensiveMap are rejected before any human ever sees them . |
262 | func RespondWithNicety ( in * dt . Msg ) string { for _ , w := range in . Stems { switch w { case "thank" : return "You're welcome!"
case "cool" , "sweet" , "awesom" , "neat" , "perfect" : return "I know!"
case "sorri" : return "That's OK. I forgive you."
case "hi" , "hello" : return "Hi there. :)"
}
}
return ""
} | RespondWithNicety replies to niceties that humans use but Abot can ignore . Words like Thank you are not necessary for a robot but it s important Abot respond correctly nonetheless . |
263 | func RespondWithHelp ( in * dt . Msg ) string { if len ( in . StructuredInput . Commands ) != 1 { return ""
}
if in . StructuredInput . Commands [ 0 ] != "help" { return ""
}
if in . Plugin != nil { use := randUseForPlugin ( in . Plugin )
use2 := randUseForPlugin ( in . Plugin )
if use == use2 { return fmt . Sprintf ( "Try telling me %q" , use )
}
return fmt . Sprintf ( "Try telling me %q or %q" , use , use2 )
}
switch len ( PluginsGo ) { case 0 : return ""
case 1 : return fmt . Sprintf ( "Try saying %q" , randUse ( ) )
default : use := randUse ( )
use2 := randUse ( )
if use == use2 { return fmt . Sprintf ( "Try telling me %q" , use )
}
return fmt . Sprintf ( "Try telling me %q or %q" , use , use2 )
}
} | RespondWithHelp replies to the user when he or she asks for help . |
264 | func RespondWithHelpConfused ( in * dt . Msg ) string { if in . Plugin != nil { use := randUseForPlugin ( in . Plugin )
use2 := randUseForPlugin ( in . Plugin )
if use == use2 { return fmt . Sprintf ( "%s You can try telling me %q" , ConfusedLang ( ) , use )
}
return fmt . Sprintf ( "%s You can try telling me %q or %q" , ConfusedLang ( ) , use , use2 )
}
if len ( PluginsGo ) == 0 { return ConfusedLang ( )
}
use := randUse ( )
use2 := randUse ( )
if use == use2 { return fmt . Sprintf ( "%s How about %q" , ConfusedLang ( ) , use )
}
return fmt . Sprintf ( "%s How about %q or %q" , ConfusedLang ( ) , use , use2 )
} | RespondWithHelpConfused replies to the user when Abot is confused . |
265 | func randUse ( ) string { if len ( PluginsGo ) == 0 { return ""
}
pluginUses := PluginsGo [ rand . Intn ( len ( PluginsGo ) ) ] . Usage
if pluginUses == nil || len ( pluginUses ) == 0 { return ""
}
return pluginUses [ rand . Intn ( len ( pluginUses ) ) ]
} | randUse returns a random use from among all plugins . |
266 | func randUseForPlugin ( plugin * dt . Plugin ) string { if plugin . Config . Usage == nil { return ""
}
return plugin . Config . Usage [ rand . Intn ( len ( plugin . Config . Usage ) ) ]
} | randUseForPlugin returns a random use from a specific plugin . |
267 | func RespondWithOffense ( in * dt . Msg ) string { for _ , w := range in . Stems { _ , ok := offensive [ w ]
if ok { return "I'm sorry, but I don't respond to rude language."
}
}
return ""
} | RespondWithOffense is a one - off function to respond to rude user language by refusing to process the command . |
268 | func Parse ( s string ) ( * dt . Address , error ) { s = regexAddress . FindString ( s )
if len ( s ) == 0 { log . Debug ( "missing address" )
return nil , ErrInvalidAddress
}
log . Debug ( "address" , s )
tmp := regexZip . FindStringIndex ( s )
var zip string
if tmp != nil { zip = s [ tmp [ 0 ] : tmp [ 1 ] ]
s = s [ : tmp [ 0 ] ]
} else { log . Debug ( "no zip found" )
}
tmp2 := regexState . FindStringIndex ( s )
if tmp2 == nil && tmp == nil { log . Debug ( "no state found AND no zip found" )
return & dt . Address { } , ErrInvalidAddress
}
var city , state string
if tmp2 != nil { state = s [ tmp2 [ 0 ] : tmp2 [ 1 ] ]
s = s [ : tmp2 [ 0 ] ]
state = strings . Trim ( state , ", \n" )
\n
if len ( state ) > 2 { state = strings . ToLower ( state )
state = states [ state ]
}
tmp = regexCity . FindStringIndex ( s )
if tmp == nil { log . Debug ( "no city found" )
return & dt . Address { } , ErrInvalidAddress
}
city = s [ tmp [ 0 ] : tmp [ 1 ] ]
} else s = s [ : tmp [ 0 ] ]
{ log . Debug ( "no state found" )
}
tmp = regexApartment . FindStringIndex ( s )
var apartment string
if tmp != nil { apartment = s [ tmp [ 0 ] : tmp [ 1 ] ]
s2 := s [ : tmp [ 0 ] ]
if len ( s2 ) == 0 { apartment = ""
} else { s = s2
}
} else { log . Debug ( "no apartment found" )
}
tmp = regexStreet . FindStringIndex ( s )
if tmp == nil { log . Debug ( s )
log . Debug ( "no street found" )
return & dt . Address { } , ErrInvalidAddress
}
street := s [ tmp [ 0 ] : tmp [ 1 ] ]
} | Parse a string to return a fully - validated U . S . address . |
269 | func compileAssets ( ) error { p := filepath . Join ( "cmd" , "compileassets.sh" )
outC , err := exec . Command ( "/bin/sh" , "-c" , p ) . CombinedOutput ( )
if err != nil { log . Debug ( string ( outC ) )
return err
}
return nil
} | compileAssets compresses and merges assets from Abot core and all plugins on boot . In development this step is repeated on each server HTTP request prior to serving any assets . |
270 | func ConnectDB ( name string ) ( * sqlx . DB , error ) { if len ( name ) == 0 { dir , err := os . Getwd ( )
if err != nil { return nil , err
}
name = filepath . Base ( dir )
}
dbConnStr := DBConnectionString ( name )
log . Debug ( "connecting to db" )
return sqlx . Connect ( "postgres" , dbConnStr )
} | ConnectDB opens a connection to the database . The name is the name of the database to connect to . If empty it defaults to the current directory s name . |
271 | func DBConnectionString ( name string ) string { dbConnStr := os . Getenv ( "ABOT_DATABASE_URL" )
if dbConnStr == "" { dbConnStr = "host=127.0.0.1 user=postgres"
}
if len ( dbConnStr ) <= 11 || dbConnStr [ : 11 ] != "postgres://" { dbConnStr += " sslmode=disable dbname=" + name
if strings . ToLower ( os . Getenv ( "ABOT_ENV" ) ) == "test" { dbConnStr += "_test"
}
}
return dbConnStr
} | DBConnectionString returns the connection parameters for connecting to the database . |
272 | func LoadConf ( ) error { p := filepath . Join ( "plugins.json" )
okVal := fmt . Sprintf ( "open %s: no such file or directory" , p )
contents , err := ioutil . ReadFile ( p )
if err != nil && err . Error ( ) != okVal { return err
}
return json . Unmarshal ( contents , conf )
} | LoadConf plugins . json into a usable struct . |
273 | func LoadEnvVars ( ) error { if envLoaded { return nil
}
if len ( os . Getenv ( "ABOT_PATH" ) ) == 0 { p := filepath . Join ( os . Getenv ( "GOPATH" ) , "src" , "github.com" , "itsabot" , "abot" )
log . Debug ( "ABOT_PATH not set. defaulting to" , p )
if err := os . Setenv ( "ABOT_PATH" , p ) ; err != nil { return err
}
}
if len ( os . Getenv ( "ITSABOT_URL" ) ) == 0 { log . Debug ( "ITSABOT_URL not set, using https://www.itsabot.org" )
err := os . Setenv ( "ITSABOT_URL" , "https://www.itsabot.org" )
if err != nil { return err
}
}
p := filepath . Join ( "abot.env" )
fi , err := os . Open ( p )
if os . IsNotExist ( err ) { return nil
}
if err != nil { return err
}
defer func ( ) { if err = fi . Close ( ) ; err != nil { log . Info ( "failed to close file" )
}
} ( )
scn := bufio . NewScanner ( fi )
for scn . Scan ( ) { line := scn . Text ( )
fields := strings . SplitN ( line , "=" , 2 )
if len ( fields ) != 2 { continue
}
key := strings . TrimSpace ( fields [ 0 ] )
if len ( key ) == 0 { continue
}
if len ( os . Getenv ( fields [ 0 ] ) ) > 0 { continue
}
val := strings . TrimSpace ( fields [ 1 ] )
if len ( val ) >= 2 { if val [ 0 ] == '"' || val [ 0 ] == '\'' { val = val [ 1 : len ( val ) - 1 ]
}
}
if err = os . Setenv ( key , val ) ; err != nil { return err
}
}
if err = scn . Err ( ) ; err != nil { return err
}
envLoaded = true
return nil
} | LoadEnvVars from abot . env into memory |
274 | func LoadPluginsGo ( ) error { p := filepath . Join ( "plugins.go" )
okVal := fmt . Sprintf ( "open %s: no such file or directory" , p )
contents , err := ioutil . ReadFile ( p )
if err != nil && err . Error ( ) != okVal { return err
}
var val [ ] byte
var foundStart bool
var nestLvl int
for _ , b := range contents { switch b { case '{' : nestLvl ++
if nestLvl == 1 { foundStart = true
}
case '}' : nestLvl --
if nestLvl == 0 { val = append ( val , b )
val = append ( val , [ ] byte ( "," ) ... )
foundStart = false
}
}
if ! foundStart { continue
}
val = append ( val , b )
}
if len ( val ) == 0 { return nil
}
val = append ( [ ] byte ( "[" ) , val ... )
val = append ( val [ : len ( val ) - 1 ] , [ ] byte ( "]" ) ... )
return json . Unmarshal ( val , & PluginsGo )
} | LoadPluginsGo loads the plugins . go file into memory . |
275 | func trainClassifiers ( ) error { for _ , pconf := range PluginsGo { ss , err := fetchTrainingSentences ( pconf . ID , pconf . Name )
if err != nil { return err
}
m := map [ string ] struct { } { }
for _ , s := range ss { _ , ok := m [ s . Intent ]
if ok { continue
}
log . Debug ( "learning intent" , s . Intent )
m [ s . Intent ] = struct { } { }
pluginIntents [ s . PluginID ] = append ( pluginIntents [ s . PluginID ] , bayesian . Class ( s . Intent ) )
}
for _ , s := range ss { intents := pluginIntents [ s . PluginID ]
if len ( intents ) == 0 { break
}
if len ( intents ) == 1 { intents = append ( intents , bayesian . Class ( "__no_intent" ) )
}
c := bayesian . NewClassifier ( intents ... )
bClassifiers [ s . PluginID ] = c
}
for _ , s := range ss { tokens := TokenizeSentence ( s . Sentence )
stems := StemTokens ( tokens )
c , exists := bClassifiers [ s . PluginID ]
if exists { c . Learn ( stems , bayesian . Class ( s . Intent ) )
}
}
}
return nil
} | trainClassifiers trains classifiers for each plugin . |
276 | func ( u * Uint64Slice ) Scan ( src interface { } ) error { asBytes , ok := src . ( [ ] byte )
if ! ok { return errors . New ( "scan source was not []bytes" )
}
str := string ( asBytes )
str = str [ 1 : len ( str ) - 1 ]
csvReader := csv . NewReader ( strings . NewReader ( str ) )
slice , err := csvReader . Read ( )
if err != nil && err . Error ( ) != "EOF" { return err
}
var s [ ] uint64
for _ , sl := range slice { tmp , err := strconv . ParseUint ( sl , 10 , 64 )
if err != nil { return err
}
s = append ( s , tmp )
}
* u = Uint64Slice ( s )
return nil
} | Scan converts to a slice of uint64 . |
277 | func ( u Uint64Slice ) Value ( ) ( driver . Value , error ) { var ss [ ] string
for i := 0 ; i < len ( u ) ; i ++ { tmp := strconv . FormatUint ( u [ i ] , 10 )
ss = append ( ss , tmp )
}
return "{" + strings . Join ( ss , "," ) + "}" , nil
} | Value converts to a slice of uint64 . |
278 | func ( s StringSlice ) String ( ) string { if len ( s ) == 0 { return ""
}
var ss string
for _ , w := range s { ss += " " + w
}
return ss [ 1 : ]
} | String converts a StringSlice into a string with each word separated by spaces . |
279 | func ( s StringSlice ) Map ( ) map [ string ] struct { } { m := map [ string ] struct { } { }
for _ , w := range s { m [ w ] = struct { } { }
}
return m
} | Map converts a StringSlice into a map to check quickly if words exist within it . |
280 | func ForgotPasswordEmail ( name , secret string ) string { h := `<html><body>`
h += fmt . Sprintf ( "<p>Hi %s:</p>" , name )
h += "<p>Please click the following link to reset your password. This link will expire in 30 minutes.</p>"
h += fmt . Sprintf ( "<p>%s</p>" , os . Getenv ( "ABOT_URL" ) + "/reset_password?s=" + secret )
h += "<p>If you received this email in error, please ignore it.</p>"
h += "<p>Have a great day!</p>"
h += "<p>-Abot</p>"
h += "</body></html>"
return h
} | ForgotPasswordEmail takes a user s name and a secret token stored in the database and returns an HTML - format email . |
281 | func NewAtomicWebSocketSet ( ) AtomicWebSocketSet { return AtomicWebSocketSet { sockets : map [ uint64 ] * websocket . Conn { } , mutex : & sync . Mutex { } , }
} | NewAtomicWebSocketSet returns an AtomicWebSocketSet to maintain open WebSocket connections on a per - user basis . |
282 | func ( as AtomicWebSocketSet ) Get ( userID uint64 ) * websocket . Conn { var conn * websocket . Conn
as . mutex . Lock ( )
conn = as . sockets [ userID ]
as . mutex . Unlock ( )
runtime . Gosched ( )
return conn
} | Get returns a WebSocket connection for a given userID in a thread - safe way . |
283 | func ( as AtomicWebSocketSet ) NotifySockets ( uid uint64 , cmd , ret string ) error { s := as . Get ( uid )
if s == nil { return nil
}
t := time . Now ( )
data := [ ] struct { Sentence string
AvaSent bool
CreatedAt * time . Time
} { { Sentence : cmd , AvaSent : false , CreatedAt : & t , } , }
if len ( ret ) > 0 { data = append ( data , struct { Sentence string
AvaSent bool
CreatedAt * time . Time
} { Sentence : ret , AvaSent : true , CreatedAt : & t , } )
}
return websocket . JSON . Send ( s , & data )
} | NotifySockets sends listening clients new messages over WebSockets eliminating the need for trainers to constantly reload the page . |
284 | func ( pm PkgMap ) Get ( k string ) * dt . Plugin { var p * dt . Plugin
pm . mutex . Lock ( )
p = pm . plugins [ k ]
pm . mutex . Unlock ( )
runtime . Gosched ( )
return p
} | Get is a thread - safe locking way to access the values of a PkgMap . |
285 | func ( pm PkgMap ) Set ( k string , v * dt . Plugin ) { pm . mutex . Lock ( )
pm . plugins [ k ] = v
pm . mutex . Unlock ( )
runtime . Gosched ( )
} | Set is a thread - safe locking way to set the values of a PkgMap . |
286 | func GetPlugin ( db * sqlx . DB , m * dt . Msg ) ( p * dt . Plugin , route string , directroute , followup bool , err error ) { for _ , i := range m . StructuredInput . Intents { route = "I_" + strings . ToLower ( i )
log . Debug ( "searching for route" , route )
if p = RegPlugins . Get ( route ) ; p != nil { return p , route , true , false , nil
}
}
log . Debug ( "getting last plugin route" )
prevPlugin , prevRoute , err := m . GetLastPlugin ( db )
if err != nil && err != sql . ErrNoRows { return nil , "" , false , false , err
}
if len ( prevPlugin ) > 0 { log . Debugf ( "found user's last plugin route: %s - %s\n" , \n , prevPlugin )
}
prevRoute
eng := porter2 . Stemmer
for _ , c := range m . StructuredInput . Commands { c = strings . ToLower ( eng . Stem ( c ) )
for _ , o := range m . StructuredInput . Objects { o = strings . ToLower ( eng . Stem ( o ) )
route := "CO_" + c + "_" + o
log . Debug ( "searching for route" , route )
if p = RegPlugins . Get ( route ) ; p != nil { followup := prevPlugin == p . Config . Name
return p , route , true , followup , nil
}
}
}
if prevRoute != "" { if p = RegPlugins . Get ( prevRoute ) ; p != nil { return p , prevRoute , false , true , nil
}
}
log . Debug ( "could not match user input to any plugin" )
} | GetPlugin attempts to find a plugin and route for the given msg input if none can be found it checks the database for the last route used and gets the plugin for that . If there is no previously used plugin we return errMissingPlugin . The bool value return indicates whether this plugin is different from the last plugin used by the user . |
287 | func updateAnalytics ( interval time . Duration ) { t := time . NewTicker ( time . Hour )
select { case now := <- t . C : updateAnalyticsTick ( now )
updateAnalytics ( interval )
}
} | updateAnalytics recursively calls itself to continue running . |
288 | func ( p * Plugin ) DeleteMemory ( in * Msg , k string ) { var err error
if in . User . ID > 0 { q := `DELETE FROM states WHERE userid=$1 AND pluginname=$2 AND key=$3`
_ , err = p . DB . Exec ( q , in . User . ID , p . Config . Name , k )
} else { q := `DELETE FROM states WHERE flexid=$1 AND flexidtype=$2 AND pluginname=$3 AND key=$4`
_ , err = p . DB . Exec ( q , in . User . FlexID , in . User . FlexIDType , p . Config . Name , k )
}
if err != nil { p . Log . Infof ( "could not delete memory for key %s. %s" , k , err . Error ( ) )
}
} | DeleteMemory deletes a memory for a given key . It is not an error to delete a key that does not exist . |
289 | func ( p * Plugin ) GetSetting ( name string ) string { if p . Config . Settings [ name ] == nil { pluginName := p . Config . Name
if len ( pluginName ) == 0 { pluginName = "plugin"
}
m := fmt . Sprintf ( "missing setting %s. please declare it in the %s's plugin.json" , name , pluginName )
log . Fatal ( m )
}
var val string
q := `SELECT value FROM settings WHERE name=$1 AND pluginname=$2`
err := p . DB . Get ( & val , q , name , p . Config . Name )
if err == sql . ErrNoRows { return p . Config . Settings [ name ] . Default
}
if err != nil { log . Info ( "failed to get plugin setting." , err )
return ""
}
return val
} | GetSetting retrieves a specific setting s value . It throws a fatal error if the setting has not been declared in the plugin s plugin . json file . |
290 | func Greeting ( r * rand . Rand , name string ) string { var n int
if len ( name ) == 0 { n = r . Intn ( 3 )
switch n { case 0 : return fmt . Sprintf ( "Hi, %s." , name )
case 1 : return fmt . Sprintf ( "Hello, %s." , name )
case 2 : return fmt . Sprintf ( "Hi there, %s." , name )
}
} else { n = r . Intn ( 3 )
switch n { case 0 : return "Hi. How can I help you?"
case 1 : return "Hello. What can I do for you?"
}
}
log . Debug ( "greeting failed to return a response" )
return ""
} | Greeting returns a randomized greeting . |
291 | func SuggestedPlace ( s string ) string { n := rand . Intn ( 4 )
switch n { case 0 : return "How does this place look? " + s
case 1 : return "How about " + s + "?"
case 2 : return "Have you been here before? " + s
case 3 : return "You could try this: " + s
}
log . Debug ( "suggestedPlace failed to return a response" )
return ""
} | SuggestedPlace returns a randomized place suggestion useful for recommending restaurants businesses etc . |
292 | func SuggestedProduct ( s string , num uint ) string { var n int
var val , flair string
if num > 0 { n = rand . Intn ( 3 )
switch n { case 0 , 1 : flair = ", then"
case 2 : }
}
n = rand . Intn ( 6 )
switch n { case 0 : val = "I found just the thing"
case 1 : val = "This is the one for you"
case 2 : val = "You'll love this"
case 3 : val = "This is a real treat"
case 4 : val = "This will amaze you"
case 5 : val = "I found just the thing for you"
}
return val + flair + ". " + s
} | SuggestedProduct returns natural language randomized text for a product suggestion . |
293 | func QuestionLocation ( loc string ) string { if len ( loc ) == 0 { n := rand . Intn ( 10 )
switch n { case 0 : return "Where are you?"
case 1 : return "Where are you now?"
case 2 : return "Sure thing. Where are you?"
case 3 : return "Sure thing. Where are you now?"
case 4 : return "Happy to help. Where are you?"
case 5 : return "Happy to help. Where are you now?"
case 6 : return "I can help with that. Where are you?"
case 7 : return "I can help with that. Where are you now?"
case 8 : return "I can help solve this. Where are you?"
case 9 : return "I can help solve this. Where are you now?"
}
}
return fmt . Sprintf ( "Are you still near %s?" , loc )
} | QuestionLocation returns a randomized question asking a user where they are . |
294 | func Yes ( s string ) bool { s = strings . ToLower ( s )
_ , ok := yes [ s ]
return ok
} | Yes determines if a specific word is a positive Yes response . For example yeah returns true . |
295 | func No ( s string ) bool { s = strings . ToLower ( s )
_ , ok := no [ s ]
return ok
} | No determines if a specific word is a No response . For example nah returns true . |
296 | func RemoveStopWords ( ss [ ] string ) [ ] string { var removal [ ] int
for i , s := range ss { if Contains ( StopWords , s ) { removal = append ( removal , i )
}
}
for _ , i := range removal { ss = append ( ss [ : i ] , ss [ i + 1 : ] ... )
}
return ss
} | RemoveStopWords finds and removes stopwords from a slice of strings . |
297 | func New ( pluginName string ) * Logger { lg := log . New ( os . Stdout , "" , log . Ldate | log . Ltime )
if len ( pluginName ) == 0 { return & Logger { logger : lg }
}
return & Logger { prefix : fmt . Sprintf ( "[%s] " , pluginName ) , logger : lg , }
} | New returns a Logger which supports a custom prefix representing a plugin s name . |
298 | func ( l * Logger ) Fatal ( v ... interface { } ) { l . logger . Fatalf ( "%s" , l . prefix + fmt . Sprintln ( v ... ) )
} | Fatal logs a statement and kills the running process . |
299 | func Iterate ( p * dt . Plugin , label string , opts OptsIterate ) [ ] dt . State { if len ( label ) == 0 { label = "__iterableStart"
}
return [ ] dt . State { { Label : label , OnEntry : func ( in * dt . Msg ) string { var ss [ ] string
mem := p . GetMemory ( in , opts . IterableMemKey )
if len ( mem . Val ) == 0 { mem . Val = [ ] byte ( `[]` )
}
err := json . Unmarshal ( mem . Val , & ss )
if err != nil { p . Log . Info ( "failed to get iterable memory." , err )
return ""
}
if len ( ss ) == 0 { return "I'm afraid I couldn't find any results like that."
}
var idx int64
if p . HasMemory ( in , keySelection ) { idx = p . GetMemory ( in , keySelection ) . Int64 ( ) + 1
}
if idx >= int64 ( len ( ss ) ) { return "I'm afraid that's all I have."
}
p . SetMemory ( in , keySelection , idx )
return fmt . Sprintf ( "How about %s?" , ss [ idx ] )
} , OnInput : func ( in * dt . Msg ) { yes , err := language . ExtractYesNo ( in . Sentence )
if err != nil { return
}
if yes { idx := p . GetMemory ( in , keySelection ) . Int64 ( )
p . SetMemory ( in , opts . ResultMemKeyIdx , idx )
return
}
} , Complete : func ( in * dt . Msg ) ( bool , string ) { if p . HasMemory ( in , opts . ResultMemKeyIdx ) { return true , ""
}
return false , p . SM . ReplayState ( in )
} , } , }
} | Iterate through a set of options allowing the user to select one before continuing . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.