###
#
#  Название/Name: hsq.tcl
#  Версия/Version: 1.0
#  Оффсайт/Homepage: http://egghelp.ru/
#  Автор/Author: tvrsh 
#
###
#
# Описание: Скрипт забирает с сайта www.smacie.com цитаты Барта и Гомера Симпсонов, Эрика Картмана, Стиви Гриффина и Бората.
# Description: This script paste random Bart and Homer Simpson, Eric Cartman, Stewie Griffin and Borat quotes from www.smacie.com to channel.
#
###
#
# Установка/Setup: 
#         1. Скопируйте скрипт hsq.tcl в папку scripts вашего бота.
#         2. В файле eggdrop.conf впишите строку source scripts/hsq.tcl 
#         3. Сделайте .rehash боту.
#         1en. Copy hsq.tcl to scripts folder.
#         2en. Add line source scripts/hsq.tcl to the end of eggdrop.conf file.
#         3en. .rehash your bot from partyline.
#
###
#
# Версион хистори/Version history:
#
#              1.0(18.12.2010) Первая паблик версия/First public release.
#
###

namespace eval hsq {
# Сбрасываем значения всех переменных.
foreach p [array names hsq *] { catch {unset hsq($p) } }

# Указываем канальный флаг(.chanset #chan +hsq для включения скрипта).
# Set .chanset #chan +hsq to enable script.
setudef flag hsq

###                            ###
# Меню настроек ниже этой линии: #
# ______________________________ #
###                            ###
	variable hsq
	array set hsq {
	pref {!}
	binds {hsq bsq ecq sgq bq}
	msg 1
	delay 10
       color1 \00314
       color2 \00303
       color3 \00305
	version "hsq.tcl version 1.0"
	author "tvrsh"
	}

###                                                                  ###
# Ниже этой линии начинается код, не изменяйте его если не знаете TCL: #
# ____________________________________________________________________ #
###                                                                  ###

# Обработка биндов./Bindings.
foreach bind [split $hsq(binds) " "] {
    bind pub -|- "$hsq(pref)$bind" ::hsq::hsq_pub
    if {$hsq(msg) >= 1} {
        bind msg -|- "$hsq(pref)$bind" ::hsq::hsq_msg
    }
}

# Процедура обработки приватных команд./Msg binds.
proc ::hsq::hsq_msg {nick uhost hand text} {
    variable hsq
    ::hsq::hsq_proc $nick $uhost $hand $nick
}

# Процедура обработки паблик команд./Pub binds.
proc ::hsq::hsq_pub {nick uhost hand chan text} {
    variable hsq

    # Проверяем наличие флага./Chanflag checking.
    if {![channel get $chan hsq]} { 
        return 
    }
    ::hsq::hsq_proc $nick $uhost $hand $chan
}

# Процедура обработки запроса./Main proc.
proc ::hsq::hsq_proc {nick uhost hand chan} {
    global lastbind
    variable hsq 

    if {[info exists hsq(lasttime,$chan)] && [expr $hsq(lasttime,$chan) + $hsq(delay)] > [clock seconds]} {
        putserv "NOTICE $nick :$hsq(color1)You can use 1 request in $hsq(color2)$hsq(delay) $hsq(color1)[lindex {. second seconds seconds} [hsq_numgrp $hsq(delay)]].\003"
        putserv "NOTICE $nick :$hsq(color1)Wait $hsq(color3)[expr $hsq(delay) - [expr [clock seconds] - $hsq(lasttime,$chan)]] $hsq(color1)[lindex {. second seconds seconds} [hsq_numgrp [expr $hsq(delay) - [expr [clock seconds] - $hsq(lasttime,$chan)]]]] before next request.\003"

#ru#    putserv "NOTICE $nick :$hsq(color1)Запрос не чаще одного раза в $hsq(color2)$hsq(delay) $hsq(color1)[lindex {. секунду секунды секунд} [hsq_numgrp $hsq(delay)]].\003"
#ru#    putserv "NOTICE $nick :$hsq(color1)Подождите $hsq(color3)[expr $hsq(delay) - [expr [clock seconds] - $hsq(lasttime,$chan)]] $hsq(color1)[lindex {. секунду секунды секунд} [hsq_numgrp [expr $hsq(delay) - [expr [clock seconds] - $hsq(lasttime,$chan)]]]] до следующего запроса.\003"
        return 0
    }
    set hsq_tok [::http::config -useragent "Mozilla/4.0 (compatible; MSIE 4.01; Windows CE; PPC; 240x320)"]

    switch $lastbind {
        "!hsq" {set url http://smacie.com/randomizer/simpsons/homer.html}
        "!bsq" {set url http://smacie.com/randomizer/simpsons/bart.html}
        "!ecq" {set url http://smacie.com/randomizer/southpark/cartman.html}
        "!sgq" {set url http://smacie.com/randomizer/family_guy/stewie_griffin.html}
        "!bq" {set url http://smacie.com/randomizer/borat.html}
        default {set url http://smacie.com/randomizer/simpsons/homer.html}
    }
    catch {set hsq_tok [::http::geturl "$url" -timeout "20000"]} error

    if {[string match -nocase "*couldn't open socket*" $error]} {
        putserv "PRIVMSG $chan :$hsq(color1)Error: $hsq(color2)\"Сouldn't open socket\"$hsq(color1). Url $hsq(color2)\"http://smacie.com/randomizer/simpsons/homer.html\" $hsq(color1)didnt exists.\003"
#ru#    putserv "PRIVMSG $chan :$hsq(color1)Ошибка: $hsq(color2)\"Сouldn't open socket\"$hsq(color1). Адрес $hsq(color2)\"http://www.ac-soft.ru/pub/aforisms/aforismjs1251.php\" $hsq(color1)не существует.\003"
        return 0 
    }
    if {[::http::status $hsq_tok] == "timeout"} {
        putserv "PRIVMSG $chan :$hsq(color1)Error: $hsq(color2)\"Сonnect timeout\"$hsq(color1). Check your internet connection speed.\003"
#ru#    putserv "PRIVMSG $chan :$hsq(color1)Ошибка: $hsq(color2)\"Сonnect timeout\"$hsq(color1). Проверьте скорость соединения своего бота.\003"
        return 0 
    }

    set data [::http::data $hsq_tok]
    ::http::cleanup $hsq_tok
    putlog "\[hsq\] $nick/$chan"
    regexp {<big><font face="Comic Sans MS">(.*?)</font>} $data "" data
    switch $lastbind {
        "!hsq" {set msg "$hsq(color3)Homer says:$hsq(color1)"}
        "!bsq" {set msg "$hsq(color3)Bart says:$hsq(color1)"}
        "!ecq" {set msg "$hsq(color3)Eric says:$hsq(color1)"}
        "!sgq" {set msg "$hsq(color3)Stewie says:$hsq(color1)"}
        "!bq" {set msg "$hsq(color3)Borat says:$hsq(color1)"}
        default {set msg "$hsq(color3)Homer says:$hsq(color1)"}
    }
    putserv "PRIVMSG $chan :[join [lappend msg $data]]\003"
    set hsq(lasttime,$chan) [clock seconds]
    return 0
}

proc hsq_numgrp {number} { 
    switch -glob -- "$number" { 
        *11 {return 3} 
        *12 {return 3} 
        *13 {return 3} 
        *14 {return 3} 
        *1 {return 1} 
        *2 {return 2} 
        *3 {return 2} 
        *4 {return 2} 
        default {return 3} 
    }
}

# Выводим сообщение о том, что скрипт удачно загружен./Script loaded successfully.
putlog "\[hsq\] $hsq(version) by $hsq(author) loaded"
}