Skip to content

Instantly share code, notes, and snippets.

@ryanramage
Created July 14, 2016 15:36
Show Gist options
  • Save ryanramage/7ff1faac9174ae19cf5260a8e5a3f9c7 to your computer and use it in GitHub Desktop.
Save ryanramage/7ff1faac9174ae19cf5260a8e5a3f9c7 to your computer and use it in GitHub Desktop.
Slackbot form for multi-user
#!/usr/bin/env node
const isPhone = require('is-phone')
const RtmClient = require('@slack/client').RtmClient
const MemoryDataStore = require('@slack/client').MemoryDataStore
const RTM_EVENTS = require('@slack/client').RTM_EVENTS
const token = process.env.SLACK_TOKEN || ''
const rtm = new RtmClient(token, {
logLevel: 'error',
// logLevel: 'debug',
// Initialise a data store for our client, this will load additional helper functions for the storing and retrieval of data
dataStore: new MemoryDataStore(),
// Boolean indicating whether Slack should automatically reconnect after an error response
autoReconnect: true,
// Boolean indicating whether each message should be marked as read or not after it is processed
autoMark: true
})
/* proxy for now, for flexibility in this area later */
const setState = (user, newState) => {
state[user] = newState
}
const states = {
DEFAULT: 'DEFAULT',
GET_NAME: 'GET_NAME',
GET_ADDRESS: 'GET_ADDRESS',
GET_PHONE: 'GET_PHONE',
GET_MESSAGE: 'GET_MESSAGE'
}
/* init state, set initial state */
let state = {}
let responses = {}
/* functions that send responses and set state, called based on state */
const handlers = {}
handlers.DEFAULT = (message) => {
rtm.sendMessage("Welcome! What's your name?", message.channel)
setState(message.user, states.GET_NAME)
}
handlers.GET_NAME = (message) => {
responses[message.user] = { name: message.text }
console.log(responses)
rtm.sendMessage("Ok, what's your address?", message.channel)
setState(message.user, states.GET_ADDRESS)
}
handlers.GET_ADDRESS = (message) => {
responses[message.user].address = message.text
console.log(responses)
rtm.sendMessage("What's your phone number?", message.channel)
setState(message.user, states.GET_PHONE)
}
handlers.GET_PHONE = (message) => {
if (isPhone(message.text)) {
responses[message.user].phone = message.text
console.log(responses)
rtm.sendMessage('Do you have a message you want to leave?', message.channel)
setState(message.user, states.GET_MESSAGE)
} else {
rtm.sendMessage('not a valid phone', message.channel)
}
}
handlers.GET_MESSAGE = (message) => {
responses[message.user].message = message.text
console.log('User FORM result', responses[message.user])
rtm.sendMessage('All set', message.channel)
setState(message.user, states.DEFAULT)
}
const router = (message) => {
let userState = state[message.user]
if (!userState) {
state[message.user] = 'DEFAULT'
}
handlers[state[message.user]](message)
}
// Listens to all `message` events from the team
rtm.on(RTM_EVENTS.MESSAGE, (message) => {
router(message)
})
rtm.start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment