SlideShare a Scribd company logo
1 of 51
Download to read offline
Programación de Bots para Slack
Richard B. Kaufman-López
@sparragus
Slack
Programacion de Bots para
Herramientas
basicas
Tipos de bots
Incoming Webhooks
Outgoing Webhooks
Bot User
Slash Commands
Incoming
Webhooks
Slack
Incoming 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-finish
http://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-snowden
Envía mensajes anónimos a #random.
http://ledhack.org/slack-bot-edward-snowden/
Slash Commands
Slack
Slash Commands
Bot App
Slack
Message?Command
Text
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: @sparragus
slack: richard
Laboratorio del Error Diseñado
twitter.com/ledhack
facebook.com/ledhack
ledhack.org
Get the code!
https://github.com/Sparragus/slack-bots-chela-js
Programación de Bots para Slack

More Related Content

Featured

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by HubspotMarius Sescu
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTExpeed Software
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsPixeldarts
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfmarketingartwork
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 

Featured (20)

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 

Programación de Bots para Slack

  • 1. Programación de Bots para Slack Richard B. Kaufman-López @sparragus
  • 2.
  • 3.
  • 4.
  • 5.
  • 8. Tipos de bots Incoming Webhooks Outgoing Webhooks Bot User Slash Commands
  • 10.
  • 11.
  • 12. 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);
  • 13.
  • 14. 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 });
  • 17.
  • 18.
  • 19. 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/)
  • 20. 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 });
  • 21.
  • 22. 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 });
  • 23.
  • 24. 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 });
  • 25.
  • 26. Kanye West interrumpe tus conversaciones imma-let-you-finish http://ledhack.org/imma-let-you-finish/
  • 28. Kanye West interrumpe tus conversaciones. Tiene un 0.5% de probabilidad de que aparezca. Ejemplo imma-let-you-finish
  • 29. Bots como usuario Bot Slack Message Message Action Event
  • 30.
  • 31.
  • 32.
  • 33. 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
  • 34. 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();
  • 35. 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
  • 36.
  • 37. 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 });
  • 39. slack-bot-edward-snowden Envía mensajes anónimos a #random. http://ledhack.org/slack-bot-edward-snowden/
  • 40.
  • 41. Slash Commands Slack Slash Commands Bot App Slack Message?Command Text Incoming Webhooks
  • 42.
  • 43.
  • 44. 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 });
  • 46. 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 });
  • 49. Laboratorio del Error Diseñado twitter.com/ledhack facebook.com/ledhack ledhack.org

Editor's Notes

  1. La comunidad usa Slack para chatear entre nosotros. Y también lo usan varias compañías. Pero antes de Slack…
  2. Muchas antes de Slack estaba IRC. Es el mismo concepto. Canales de chats. La mayoría de los proyectos open source usan IRC como su chat.
  3. Recuerdo que hace mucho tiempo buscaba canales de IRC donde estaba este bot: triviabot. Alguien mas jugaba? De forma sencilla, un bot es un programa metido en el chat. Extienden la función básica de enviar mensajes.
  4. No todos los bots de chat estaban en IRC. Cleverbot es ejemplo clásico. Estos bots cada año son mejores y mejores. En cada competencia de la prueba turing, lo bots no dejan de impresionar.
  5. me divierte mucho hacer estos bots. Como recientemente hemos comenzado a usar Slack bastante, se me hizo que es buena idea dar esta platica.
  6. Herramientas que vamos a estar usando
  7. Con Slack podemos bots usando cuatro integrations que Slack ofrece. Cual usamos depende de que queremos hacer.
  8. Feature principal: Puedes enviar mensajes a un canal del Team. Como funciona: Slack te provee un URL a donde puedes enviar POSTs con la data que quieres enviar a Twitter. Ademas te permite: enviar mensajes sencillos, o con formato estilo attachment.
  9. La buscamos como un integration.
  10. En la pagina de configuracion tomamos nota de la URL a donde hay que enviar los POSTs Tambien le configuramos que canal va a recibir los mensajes, el username, y un icono.
  11. El clásico hello world.
  12. Hello, Chelas!
  13. Hagamos un ejemplo donde tengamos un evento que activa el enviar un mensajes. Twitter. Stream escuchando hashtag “Tacos” Desde codigo tambien podemos configurar el username e icono. En este caso estamos haciendo un attachment. Va a tener un titulo, un mensaje, y una barra de color que demuestra que es attachment.
  14. Feature principal: escuchar/recibir mensajes en tiempo real. Como funciona: Le damos a slack un URL a donde va a hacer POST de los mensajes enviados a un canal especifico. Ademas te permite: responder (o no) al POST con un mensaje.
  15. Creamos la integracion. Aparece como Outgoing Webhooks
  16. La configuración básica es: determinar en que canal opera nuestro bot. Añadir la URL donde está el app de nuestro bot.
  17. Además podemos darle un username al bot y un icono o avatar.
  18. Este app lo voy a poner en Heroku, y voy a hacer un servidor con Express para recibir y escuchar los mensajes.
  19. Nuestro app es una app de express muy básica.
  20. Aquí están los datos que nos llegan en el POST JSON básico con el que podemos responder.
  21. A probarlo…
  22. slackbot escucha sus propios mensajes… La realidad es que en el cliente de Slack, el bot se llama “background-bot” pero internamente se llama “Slackbot”. Hay que bloquear cualquier mensaje de Slackbot. Si no tenemos un loop.
  23. Listo
  24. Tiene un 0.5% de probabilidad de que aparezca.
  25. Feature principal: Tiene acceso al API de Slack. Como funciona: Conectando tu app a un API basado en WebSockets. Ademas te permite: Apareces como un usuario en el Team.
  26. Metodos del API Podemos entrar y salirnos de canales. Enviar mensajes. …
  27. En este caso en la configuración obtenemos las llaves para conectarnos al API. Vamos hacer un bot que corrija la gramática de los que escriben mal. Un grammar-nazi
  28. En este caso no es necesario deploy el app al cloud. Lo podemos correr desde nuestra computadora. El app se va a conectar al API de slack usando WebSockets y van a estar comunicándose directamente. Esa dependencia en realidad no es la mejor. La documentación es poca, no la están manteniendo (tiene 15 pull requests y varios issues) pero es la que se usar.
  29. Hello, World! Abrimos la conexión y esperamos a escuchar mensajes. Cuando se escribe uno, contestamos con Hello, World!
  30. Corremos el app con node, y esperamos a que conecté.
  31. Vean como aparece como user.
  32. Encontre un modulo que hace spellchecking. Ahora el bot escucha todos los mensajes y si hay un error gramatical, te lo va a corregir.
  33. Lo que haces es enviarle un mensaje a edward snowden y el lo envia a #random de forma anonima. Imaginense que #random es 4chan.
  34. Feature principal: Creas comandos que puedes ejecutar desde Slack. Como funciona: Cuando escribes la diagonal, aparece la lista de comandos que puedes usar.
  35. En la configuración decimos cual es el nombre de comando que queremos crear. Ademas le decimos a que URL debe enviar el comando.
  36. Vamos a crear un comando que le pedirmos que busque una foto en instagram.
  37. Si le añadimos un incoming-integration como habiamos hecho con Twitter, podemos hacer que todo el mundo vea la foto.
  38. me pueden escribir a:
  39. El Laboratorio del Error Diseñado (LED) es un colectivo de artistas y programadores donde exploramos la tecnología con fines artísticos. En el blog hay posts sobre los bots que he hecho.
  40. Preguntas Ojala comience a ver bots en nuestro Slack.
  41. Gracias! A tomar chelas!