programación de bots para slack

51
Programación de Bots para Slack Richard B. Kaufman-López @sparragus

Upload: richard-kaufman

Post on 18-Aug-2015

117 views

Category:

Internet


6 download

TRANSCRIPT

Programación de Bots para SlackRichard B. Kaufman-López @sparragus

SlackProgramacion de Bots para

Herramientas

basicas

Tipos de bots

Incoming Webhooks

Outgoing Webhooks

Bot User

Slash Commands

Incoming

Webhooks

SlackIncoming Webhooks Bot App

Instagram Twitter Slack

Event? Message

1 var request = require('request'); 2 3 var webhookURL = 'https://hooks.slack.com/services/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'; 4 5 var payload = { 6 text: 'Hello, World!' 7 }; 8 9 var requestOptions = { 10 uri: webhookURL, 11 method: 'POST', 12 body: JSON.stringify(payload) 13 }; 14 15 request(requestOptions);

1 twitter.stream('statuses/filter', {track: hashtag}, function(stream) { 2 stream.on('data', function(tweet) { 3 var tweetUser = tweet.user.screen_name; 4 var tweetText = tweet.text; 5 6 console.log(tweetUser, tweetText); 7 8 var payload = { 9 username: 'Tacos de México', 10 icon_url: 'http://hilahcooking.com/wp-content/uploads/2010/06/tacos-al-pastor.jpg', 11 12 fallback: '@' + tweetUser + ': ' + tweetText, 13 14 pretext: 'Tacos <3', 15 16 color: '#33aaff', 17 18 fields: [{ 19 title: '@' + tweetUser, 20 value: tweetText, 21 short: true 22 }], 23 24 unfurl_links: false 25 }; 26 27 var requestOptions = { 28 uri: webhookURL, 29 method: 'POST', 30 body: JSON.stringify(payload) 31 }; 32 33 request(requestOptions); 34 }); 35 });

Video https://youtu.be/ZaYt9CRBqo4

Outgoing

Webhooks

Slack Outgoing Webhooks Bot App Slack

Message?Message

1 # Crear directorio donde vamos a trabajar 2 $ mkdir slack-background-bot 3 $ cd slack-background-bot 4 5 # Crear repositorio de git 6 $ git init 7 $ touch README.md 8 $ git add README.md 9 $ git commit -m "Initial commit." 10 11 # Crear aplicación de heroku 12 $ heroku apps:create 13 $ heroku ps:scale web=1 14 $ echo "web: node index.js" > Procfile 15 16 # Instalar dependencias 17 $ npm init 18 $ npm install --save express body-parser

heroku nos regresa la URL de nuestra app. (https://nameless-journey-4425.herokuapp.com/)

1 var express = require('express'); 2 var bodyParser = require('body-parser'); 3 4 var app = express(); 5 app.set('port', process.env.PORT || 3000); 6 7 // body parser middleware 8 app.use(bodyParser.urlencoded({ extended: true })); 9 10 // Slack nos va a enviar los mensajes aqui 11 app.post(‘/', function (req, res) { 12 // Paso 1: Recibir mensaje 13 // Paso 2: Contestar (o no) el mensaje 14 }); 15 16 app.listen(app.get('port'), function () { 17 console.log('Background bot is listening on port ' + app.get('port')); 18 });

1 // Slack nos va a enviar los mensajes aquí 2 app.post(‘/', function (req, res) { 3 // Paso 1: Recibir mensaje 4 var username = req.body.user_name; 5 var message = req.body.text; 6 7 // Paso 2: Contestar (o no) el mensaje 8 9 // Virar el mensaje y construir la contestación 10 var reversedMessage = message.split('').reverse().join(''); 11 var reply = { 12 text: reversedMessage 13 }; 14 15 // Enviar la contestación. 16 res.json(reply); 17 18 // Si por alguna razón no queremos contestar, es importante 19 // res.end() 20 });

1 // Slack nos va a enviar los mensajes aqui 2 app.post('*', function (req, res) { 3 // Paso 1: Recibir mensaje 4 var username = req.body.user_name; 5 var message = req.body.text; 6 7 // Paso 1.5: verificar si el mensaje viene de slackbot 8 if (username === 'slackbot') { 9 res.end(); 10 return; 11 } 12 13 // Paso 2: Contestar (o no) el mensaje 14 15 // Construir la contestacion 16 var reversedMessage = message.split('').reverse().join(''); 17 var reply = { 18 text: reversedMessage 19 }; 20 21 res.json(reply); 22 23 });

Kanye West interrumpe tus conversaciones

imma-let-you-finishhttp://ledhack.org/imma-let-you-finish/

Video https://www.youtube.com/watch?v=3K21rLBEfeM

Kanye West interrumpe tus conversaciones. Tiene un 0.5% de probabilidad de que aparezca.

Ejemplo

imma-let-you-finish

Bots como usuario

Bot Slack

Message

Message

Action

Event

1 # Crear directorio donde vamos a trabajar 2 $ mkdir slack-bot 3 $ cd slack-bot … 16 # Instalar dependencias 17 $ npm init 18 $ npm install --save slack-client

Nuestra única dependencia

1 var Slack = require('slack-client'); 2 3 var token = 'xoxb-8392211527-6STZVyHnmuV33VKsmVt0wHKn'; 4 var autoReconnect = true; 5 var autoMark = true; 6 7 var slack = new Slack(token, autoReconnect, autoMark); 8 9 slack.on('open', function() { 10 console.log('Bienvenido a Slack. Eres @' + slack.self.name + ' de ' + slack.team.name); 11 }); 12 13 slack.on('message', function (message) { 14 // Ver de que canal llego el mensaje y responder a ese canal 15 var channel = slack.getChannelGroupOrDMByID(message.channel); 16 channel.send(‘Hello, World!’); 17 }); 18 19 slack.on('error', function (error) { 20 console.error('Error:', error); 21 }); 22 23 slack.login();

1 richardkaufman @ kaufman in ~/D/h/m/C/P/c/bot master 2 $ node index.js 3 [Wed Jul 29 2015 17:47:09 GMT-0500 (CDT)] INFO Connecting... 4 Bienvenido a Slack. Eres @grammar-nazi de richardbkaufman

1 var getSpellingSuggestions = require('./spellcheckerSuggestions'); 2 3 slack.on('message', function (message) { 4 // Ver de que canal llego el mensaje y responder a ese canal 5 var channel = slack.getChannelGroupOrDMByID(message.channel); 6 var user = slack.getUserByID(message.user).name; 7 8 // Hacer spellcheck 9 var suggestions = getSpellingSuggestions(message.text); 10 11 // Si no hay correciones, return. 12 if (!suggestions.suggestion) { 13 return; 14 } 15 16 // Componer mensaje y enviar. 17 var suggestion = suggestions.suggestion; 18 var response = 'FTFY @' + user + ': ' + suggestion; 19 channel.send(response); 20 });

Video https://youtu.be/9VaaFv9pCag

slack-bot-edward-snowdenEnvía mensajes anónimos a #random.http://ledhack.org/slack-bot-edward-snowden/

Slash Commands

Slack Slash Commands Bot App Slack

Message?CommandText

Incoming Webhooks

1 var express = require('express'); 2 var app = express(); 3 4 var Instagram = require('instagram-node-lib'); 5 6 // Set Instagram keys and global callback url. 7 Instagram.set('client_id', '1e6e75e94695423285b11b68181bf5e6'); 8 Instagram.set('client_secret', 'c54e930a781844228bc7ec6060e73547'); 9 // Instagram.set('callback_url', ''); 10 11 var port = process.env.PORT || 3000; 12 app.set('port', port); 13 14 app.get('/', function(req, res) { 15 var tag = req.query.text; 16 17 Instagram.tags.recent({ 18 name: tag, 19 complete: function(result) { 20 var pictureURL = result[0].images.standard_resolution.url; 21 res.send(pictureURL); 22 } 23 }); 24 25 }); 26 27 app.listen(app.get('port'), function() { 28 console.log('Listening at port ' + app.get('port')); 29 });

Video https://youtu.be/5nwTxLr6nKQ

1 function sendMessageToSlack(tag, pictureURL) { 2 var webhookURL = 'https://hooks.slack.com/services/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'; 3 4 var payload = { 5 username: 'Instagram Bot', 6 icon_url: 'http://a.deviantart.net/avatars/i/n/instahack.png?1', 7 attachments: [ 8 { 9 fallback: 'A picture of ' + tag, 10 color: '#F99157', 11 pretext: '/instagram ' + tag, 12 image_url: pictureURL 13 } 14 ] 15 }; 16 17 var requestOptions = { 18 uri: webhookURL, 19 method: 'POST', 20 body: JSON.stringify(payload) 21 }; 22 23 request(requestOptions); 24 } 25 26 27 app.get('/', function(req, res) { 28 var tag = req.query.text; 29 30 Instagram.tags.recent({ 31 name: tag, 32 complete: function(result) { 33 var pictureURL = result[0].images.standard_resolution.url; 34 res.status(200).end(); 35 36 return sendMessageToSlack(tag, pictureURL); 37 } 38 }); 39 40 });

Video https://youtu.be/77wH0hC3Tvo

Richard Kaufman

twitter: @sparragusslack: richard

Laboratorio del Error Diseñado

twitter.com/ledhackfacebook.com/ledhackledhack.org

Get the code! https://github.com/Sparragus/slack-bots-chela-js