TCL Google Win

Google Win

set google(MAX) 10
set google(VER) 0.2b

bind pub - !google pub_google

proc putnot {nick msg} { putserv "NOTICE $nick :$msg" }

proc pub_google {nick uhost hand chan arg} {
  global google
  if {$arg==""} {
    putnot $nick "Usage: !google <dumi>"
    putnot $nick "Flags: -c1(Broj rezultati)"
    return 0
  }
  set type "q"
  set results 1
  foreach flag $arg {
    if {$flag=="-a"} { set type as_q ; continue } else {
      if {[regexp -- {-c[0-9]*} $flag]} {
	set results [string range $flag 2 end]
        continue
      }
    }
    lappend search $flag
  }
  if {$results>$google(MAX)} {
    putnot $nick "Max results allowed is \002$google(MAX)\002, omitting extra"
    set results $google(MAX)
  }
  search_google $nick $results $type $search
}

proc search_google {nick results type search} {
  regsub -all " " $search "+" search
  set sock [socket -async www.google.com 80]
  fconfigure $sock -blocking no -buffering full -buffersize 4096
  fileevent $sock readable "reada $sock $nick $results"
  puts $sock "GET /search?q=$search&num=$results"
  flush $sock
}

putlog "Google script $google(VER) by erupt loaded"

proc reada {sock who results} {
  set fh [open "test" a+]
  if {[eof $sock]} { close $sock ; return}
  set data [read $sock]
  foreach line [split $data \n] {
	puts $fh "|$line^\n"
	while {[regexp "<p class=g><a href=(.*?)>" $line]} {
	  set list [regexp -inline "<p class=g><a href=(.*?)>" $line]
	  regsub {<p class=g><a href=(.*?)>} $line "" line
	  putserv "NOTICE $who :Result: \002[lindex $list 1]\002"
	}
  }
  close $fh
}