Skip to content

Instantly share code, notes, and snippets.

@oieioi
Last active October 22, 2015 10:14
Show Gist options
  • Save oieioi/e132dc06cfd30fe5849f to your computer and use it in GitHub Desktop.
Save oieioi/e132dc06cfd30fe5849f to your computer and use it in GitHub Desktop.
hubot script which gets a random O'Reilly book
# Description:
# Let's study with O'Reilly books
#
# Dependencies:
# "cheerio-httpcli": "^0.3.3"
#
# Commands:
# hubot 勉強したい - get a オライリー book
cheerio = require 'cheerio-httpcli'
# Get a random item from array
sample = (ary)->
index = Math.floor Math.random() * ary.length
ary[index]
# Fetch book list from O'Reilly web site
# @return thenbale object
fetchBooks = do ->
# memo
books = null
return ->
if books?
return new Promise (resolve)->resolve books
cheerio.fetch "http://www.oreilly.co.jp/catalog/"
.then ({$})->
books = $('#bookTable tbody td a').map (item)->
href = $(@).attr 'href'
id = href.match(/\d+/)[0]
{
title: $(@).text()
path: href
id: id
url: "http://www.oreilly.co.jp/books/#{id}/"
}
.get()
books
# Fetch book detail JSON
# @return thenbale object
fetchBookDetailFromJSON = (id)->
cheerio
.fetch "http://www.oreilly.co.jp/books/#{id}/biblio.json"
.then ({body}) ->
json = JSON.parse body
json.site = "http://www.oreilly.co.jp/books/#{id}/"
json.id = id
json
fetchBookDetailFromSite = (id)->
cheerio
.fetch "http://www.oreilly.co.jp/books/#{id}"
.then ({$})->
$('#detail').text()
module.exports = (robot) ->
robot.respond /.*(オライリー|勉強|技術書)/i, (msg)->
fetchBooks().then (books)->
book = sample books
fetchBookDetailFromJSON book.id
.then (bookDetail)->
msg.reply "『#{bookDetail.title}#{(bookDetail.subtitle and ' 〜 ' + bookDetail.subtitle) or ''}』"
msg.reply "#{bookDetail.site} #{bookDetail.picture}"
fetchBookDetailFromSite bookDetail.id
.then (bookDetail)->
msg.reply "#{bookDetail.split('。')[0].replace(/^\s*/, '')}!?"
.catch (err)->
robot.logger.error err
msg.reply "よくわかりません"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment