Skip to content

Instantly share code, notes, and snippets.

@kyak
Created August 31, 2016 08:01
Show Gist options
  • Save kyak/b54bbad22a4109c95e062e1c1a72aae5 to your computer and use it in GitHub Desktop.
Save kyak/b54bbad22a4109c95e062e1c1a72aae5 to your computer and use it in GitHub Desktop.
Google custom search API eggdrop script
package require http
package require tls
::http::register https 443 [list ::tls::socket -tls1 1]
package require json
bind pub -|- "!google" google::bind
bind pub -|- "!g" google::bind
namespace eval google {
#Get here: https://console.developers.google.com/apis
variable key "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
#Get here: https://cse.google.com/cse/all
variable cx "000000000000000000000:xxxxxxxxxxx"
}
proc google::bind {nick host hand channel terms} {
google::parse ${nick} ${channel} [google::search ${terms}]
}
proc google::search {terms} {
#Get search results from google custom search api
set query [http::formatQuery cx $google::cx key $google::key q ${terms}]
set data [http::data [http::geturl "https://www.googleapis.com/customsearch/v1?$query" -timeout 10000]]
return $data
}
proc google::parse {nick chan data} {
#Convert JSON object returned by google::search into a valid TCL list
set datadict [::json::json2dict $data]
#Get search results and search information
set items [dict get $datadict "items"]
set searchInformation [dict get $datadict "searchInformation"]
#Get total results count
set totalResults [dict get $searchInformation "totalResults"]
putserv "PRIVMSG $chan :Total results count: \002$totalResults"
#Only work on first result
set item [lindex $items 0]
#Get link, title and preview
set link [dict get $item "link"]
set title [dict get $item "title"]
set title [encoding convertfrom "utf-8" $title]
set snippet [dict get $item "snippet"]
set snippet [encoding convertfrom "utf-8" $snippet]
putserv "PRIVMSG $chan :\00302$title\00302 - \00303$link\00303"
putserv "PRIVMSG $chan :$snippet"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment