Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Push Packt Free Book of the Day alert into your slack channel

Push alerts about the daily 🆓 Packt eBook into Slack

Install this globally. Yes, globally.

$ npm install -g scrape-html

Now create a local project somewhere:

$ cd free_the_books
$ npm init
$ npm install --save node-slack scrape-html

Copy in index.js from below and fill in your slack webhook config. Schedule it to run with cron:

$ crontab -e

I have mine setup to run at 9am, which looks like the following. If you need help learning cron snytax I like http://crontab.guru

0 9 * * * /usr/local/bin/node /Users/atcodes/DEV/free_the_books/index.js

For non-default node-global-install-location people:

By default node wants to install globals into /usr/local/lib/node_modules/ (and this is why you probably have to sudo every time you install a global). If you've wisely changed your default install location, this is how you adjust for it:

Your crontab line will need to set the environment variable NODE_PATH before executing the program. Change it to look like the following:

0 9 * * * NODE_PATH=NODE_PATH=/Users/atcodes/.npm_globals/lib/node_modules/scrape-html/node_modules/ /usr/local/bin/node /Users/atcodes/DEV/free_the_books/index.js

Note that in the example above, my username is atcodes and I install node globals to ~/.npm_globals/

const Slack = require( 'node-slack' );
const scrape = require( 'scrape-html' );
const listing = 'https://www.packtpub.com/packt/offers/free-learning';
let slackConfig = {
webhook_url: 'https://hooks.slack.com/..............'
,token: '{your-webhook-token-here}'
,chan: '#general'
,botName: 'FreeBooksBot'
};
const print = ( title, img ) => {
const slack = new Slack( slackConfig.webhook_url );
const message = `Today's :free: eBook from Packt is: *${title}*\n${img}\n\nGet it now: ${listing}`;
slack.send( {
text: message
,channel: '@atuttle'
,username: 'FreeBooksBot'
}
,( err ) => {
if ( err ) {
return console.error( err );
}
} );
};
const titleSelector = '.dotd-title h2';
const imgSelector = '.dotd-main-book-image img';
const handler = ( err, window ) => {
const title = window.$( titleSelector )[0].innerHTML.trim();
const img = 'https:' + window.$( imgSelector ).data( 'original' ).trim();
print( title, img );
};
scrape( listing, titleSelector, handler );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.