hubotio / hubot

A customizable life embetterment robot.
https://hubotio.github.io/hubot/
MIT License
16.66k stars 3.75k forks source link

Hubot Documentation example not working (Dynamic matching of messages) #1535

Closed oscarssanchez closed 1 year ago

oscarssanchez commented 4 years ago

Hi there,

I am working with Dynamic matching of messages per documentation here https://hubot.github.com/docs/patterns/ however, when I paste this code

module.exports = (robot) ->
  # Dynamically populated list of factoids
  facts =
    fact1: 'stuff'
    fact2: 'other stuff'

  robot.listen(
    # Matcher
    (message) ->
      match = message.match(/^~(.*)$/)
      # Only match if there is a matching factoid
      if match and match[1] in facts
        match[1]
      else
        false
    # Callback
    (response) ->
      fact = response.match
      res.reply "#{fact} is #{facts[fact]}"
  )

I get message.match is not a function, unfortunately i have been trying different approaches but none of them actually get me a response from hubot.

Is there any other documentation that can be shared or can this one be corrected? Unfortunately i was not able to find any other examples.

Thanks!

joeyguerra commented 1 year ago

The matcher function is called a 2nd time where message is of type CathAllMessage which does not have match as a method. Try this instead:

// use case: Hubot>fact1
// This listener doesn't require you to type the bot's name first

const {TextMessage} = require('../src/message')
module.exports = (robot) => {
    // Dynamically populated list of factoids
    const facts = {
        fact1: 'stuff',
        fact2: 'other stuff'
    }
    robot.listen(
        // Matcher
        (message) => {
            // Check that message is a TextMessage type because
            // if there is no match, this matcher function will 
            // be called again but the message type will be CatchAllMessage
            // which doesn't have a `match` method.
            if(!(message instanceof TextMessage)) return false
            const match = message.match(/^(.*)$/)
            // Only match if there is a matching factoid
            if (match && match[1] in facts) {
                return match[1]
            } else {
                return false 
            }
        },
        // Callback
        (response) => {
            const fact = response.match
            response.reply(`${fact} is ${facts[fact]}`)
        }
    )
}