Last active
June 14, 2016 17:03
-
-
Save emasaka/160551 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
require 'uri' | |
require 'open-uri' | |
require 'nokogiri' | |
module Termtter | |
class AsinSearch | |
URLBASE = "https://www.amazon.co.jp/s/ref=nb_sb_noss?__mk_ja_JP=#{URI.escape('カタカナ')}&url=search-alias%3Dstripbooks&field-keywords=" | |
def initialize(word) | |
@list = [] | |
open(URLBASE + URI.escape(word), get_options) do |io| | |
Nokogiri::HTML(io).xpath('//div[@id="atfResults"]//div[@class="s-item-container"]').each do |node| | |
title = node.css('a.s-access-detail-page')[0].text | |
node.css('h3').each do |h3| | |
edition = h3.parent # parent is a node | |
asin = edition[:href].scan(%r{/dp/([0-9A-Z]+)})[0][0] | |
@list << { 'title' => "#{title} (#{edition.text})", 'asin' => asin } | |
end | |
end | |
end | |
end | |
def select | |
@list.each_with_index do |n, i| | |
puts "#{i}: #{n['title']}" | |
end | |
sel = Readline.readline('Enter number or "q"> ', false) | |
sel == 'q' and raise | |
@list[sel.to_i]['asin'] | |
end | |
def empty? | |
@list.empty? | |
end | |
private | |
def get_options | |
options = {} | |
options['User-Agent'] = 'Mozilla' | |
unless config.proxy.host.nil? or config.proxy.host.empty? | |
proxy_url = "http://#{config.proxy.host}:#{config.proxy.port}" | |
if config.proxy.user_name | |
options[:proxy_http_basic_authentication] = | |
[proxy_url, config.proxy.user_name, config.proxy.password] | |
else | |
options[:proxy] = proxy_url | |
end | |
end | |
options | |
end | |
end | |
module Client | |
register_command( | |
:name => :yonda4, | |
:exec_proc => lambda {|arg| | |
arg =~ /^\s*"([^"]+)"\s*(.*)$/ or arg =~ /^\s*([^\s]+)\s*(.*)$/ or | |
return | |
keyword = $1; message = $2 | |
books = Termtter::AsinSearch.new(keyword) | |
if books.empty? | |
puts 'No match.' | |
else | |
asin = books.select rescue nil | |
if asin | |
text = "@yonda4 #{asin}#{message ? ' ' + message : ''}" | |
Termtter::API.twitter.update(text) | |
puts "=> #{text}" | |
end | |
end | |
}, | |
:help => ['yonda4 KEYWORD [MESSAGE]', 'search book and send to yonda4'] | |
) | |
end | |
end | |
# yonda4.rb | |
# search books, make select from menu, and send to yonda4 | |
# | |
# examples: | |
# > yonda4 つみきのいえ | |
# > yonda4 つみきのいえ そのいえは とても ちいさな いえでした | |
# > yonda4 "もやしもん 8" | |
# > yonda4 "もやしもん 8" ビール! 祭! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment