Advertisement
Guest User

newtime.tcl

a guest
Mar 20th, 2015
141
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
TCL 15.11 KB | None | 0 0
  1. ###
  2. #
  3. #  Название: newtime.tcl
  4. #  Версия: 1.3
  5. #  Автор: tvrsh
  6. #  Оффсайт: http://egghelp.ru/
  7. #
  8. ###
  9. #
  10. # Описание: Скрипт забирает с сайта http://www.timeserver.ru точное время в городах России.
  11. #
  12. ###
  13. #
  14. # Установка:
  15. #         1. Скопируйте скрипт newtime.tcl в папку scripts вашего бота.
  16. #         2. В файле eggdrop.conf впишите строку source scripts/newtime.tcl
  17. #         3. Сделайте .rehash боту.
  18. #
  19. ###
  20. #
  21. # Версион хистори:
  22. #
  23. #              1.0(28.08.2010) Первая паблик версия.
  24. #              1.1(29.08.2010) Добавлена поддрежка Suzi ботов.
  25. #                              + сравнение времени в друх городах.
  26. #              1.2(11.11.2010) + работа с многословными городами.
  27. #                              + показ даты.
  28. #              1.3(13.11.2010) + показ времени каждый час.
  29. #
  30. ###
  31.  
  32. namespace eval newtime {
  33. # Сбрасываем значения всех переменных.
  34. foreach p [array names newtime *] { catch {unset newtime($p) } }
  35.  
  36. # Указываем канальный флаг(.chanset #chan +newtime для включения скрипта).
  37. setudef flag newtime
  38.  
  39. ###                            ###
  40. # Меню настроек ниже этой линии: #
  41. # ______________________________ #
  42. ###                            ###
  43.     variable newtime
  44.     array set newtime {
  45.     pref {!}
  46.     binds {time время dhtvz ешьу}
  47.     msg 1
  48.     delay 5
  49.        autotimer {}
  50.        color1 \00314
  51.        color2 \00303
  52.        color3 \00305
  53.     version "newtime.tcl version 1.3"
  54.     author "tvrsh"
  55.     }
  56.  
  57. ###                                                                  ###
  58. # Ниже этой линии начинается код, не изменяйте его если не знаете TCL: #
  59. # ____________________________________________________________________ #
  60. ###                                                                  ###
  61.  
  62. # Обработка биндов.
  63. foreach bind [split $newtime(binds) " "] {
  64.     bind pub -|- "$newtime(pref)$bind" ::newtime::newtime_pub
  65.     if {$newtime(msg) >= 1} {
  66.         bind msg -|- "$newtime(pref)$bind" ::newtime::newtime_msg
  67.     }
  68. }
  69.  
  70. # начальный счетчик редиректов
  71. variable redirs 0
  72.  
  73. # Биндим ежечасный показ времени.
  74. if {$newtime(autotimer) != ""} {
  75.     bind time - "00 * * * *" ::newtime::newtime_onhour
  76. }
  77.  
  78. proc ::newtime::newtime_onhour {min hour day month year} {
  79.     variable newtime
  80.     foreach elem [split $newtime(autotimer) "\n"] {
  81.         if {[llength $elem]} {
  82.             ::newtime::newtime_proc nick uhost hand [lindex [split [join $elem]] 0] 1 [lrange [split [join $elem]] 1 end]
  83.         }
  84.     }
  85. }
  86.  
  87. # Процедура обработки приватных команд.
  88. proc ::newtime::newtime_msg {nick uhost hand text} {
  89.     variable newtime
  90.     ::newtime::newtime_proc $nick $uhost $hand $nick 0 $text
  91. }
  92.  
  93. # Процедура обработки паблик команд.
  94. proc ::newtime::newtime_pub {nick uhost hand chan text} {
  95.     variable newtime
  96.  
  97.     # Проверяем наличие флага.
  98.     if {![channel get $chan newtime]} {
  99.         return 0
  100.     }
  101.     ::newtime::newtime_proc $nick $uhost $hand $chan 0 $text
  102. }
  103.  
  104. # Процедура обработки запроса.
  105. proc ::newtime::newtime_proc {nick uhost hand chan auto text} {
  106.     global lastbind
  107.     variable newtime
  108.  
  109.     if {[info exists newtime(lasttime,$chan)] && [expr $newtime(lasttime,$chan) + $newtime(delay)] > [clock seconds]} {
  110.         putserv "NOTICE $nick :$newtime(color1)Запрос не чаще одного раза в $newtime(color2)$newtime(delay) $newtime(color1)[lindex {. секунду секунды секунд} [::newtime::numgrp $newtime(delay)]]."
  111.         putserv "NOTICE $nick :$newtime(color1)Подождите $newtime(color3)[expr $newtime(delay) - [expr [clock seconds] - $newtime(lasttime,$chan)]] $newtime(color1)[lindex {. секунду секунды секунд} [::newtime::numgrp [expr $newtime(delay) - [expr [clock seconds] - $newtime(lasttime,$chan)]]]] до следующего запроса."
  112.         return 0
  113.     }
  114.  
  115.     set newtime(start) [clock clicks]
  116.  
  117.     if {[llength [split $text]] == "0"} {
  118.         putserv "PRIVMSG $chan :$newtime(color1)Используйте $newtime(color3)\002$lastbind город\002 $newtime(color1)для просмотра точного текущего времени в городах России ...\003"
  119.        # putserv "PRIVMSG $chan :$newtime(color1)... или $newtime(color3)\002$lastbind город1+город2\002 $newtime(color1)для просмотра разницы во времени между городами.\003"
  120.         return 0
  121.     }
  122.  
  123.     set text [stripcodes bc [::newtime::en2ru $text]]
  124.     set tmp [list]
  125.     set text_ $text
  126.     foreach _ [split $text] {lappend tmp [string totitle $_]}
  127.     if {[llength $tmp]} {set text [join $tmp]}
  128.  
  129.     if {![string match "*+*" $text]} {
  130.         # Поддержка Suzi?
  131.         if {![info exists ::sp_version]} {
  132.             set text [encoding convertfrom cp1251 $text]
  133.         }
  134.  
  135.         set newtime_tok [::http::config -urlencoding utf-8 -useragent "Mozilla/4.0 (compatible; MSIE 4.01; Windows CE; PPC; 240x320)"]
  136.         set newtime_tok [::http::geturl "http://www.timeserver.ru/city/search.html?query=[string map {%20 +} [::http::formatQuery $text]]" -timeout 25000 -command [list ::newtime::data $nick $chan $text_ 1 $auto]]  
  137.        
  138.         }
  139.        
  140.        
  141.         }
  142.        
  143.        
  144.         proc ::newtime::data {nick chan text type auto newtime_tok} {
  145.        
  146.        
  147.         set status [::http::status $newtime_tok]
  148.         set ncode [::http::ncode $newtime_tok]
  149.         array set meta [::http::meta $newtime_tok]
  150.         variable redirs
  151.         variable newtime
  152.        
  153.         if {$status eq "ok"} {
  154.        
  155.         if {[string range $ncode 0 1] == "30" && [info exists meta(Location)] && $redirs < 2} {
  156.         if {[string index $meta(Location) 0] == "/"} {
  157.             set url "http://www.timeserver.ru$meta(Location)"
  158.         } else {
  159.             set url $meta(Location)
  160.         }
  161.         ::http::cleanup $newtime_tok
  162.         ::http::geturl $url -timeout 25000 -command [list ::newtime::data $nick $chan $text $type $auto]
  163.         incr redirs
  164.         return
  165.         }
  166.        
  167.         set redirs 0
  168.        
  169.         if {[http::ncode $newtime_tok] != "200"} {
  170.         putserv "PRIVMSG $chan :$newtime(color3)\002$nick\002\00304, ошибка запроса $newtime(color1)... ([http::code $newtime_tok])"
  171.         ::http::cleanup $newtime_tok
  172.         return
  173.         }
  174.        
  175.        
  176.        
  177.          set data [::http::data $newtime_tok]
  178.         ::http::cleanup $newtime_tok
  179.        
  180.         if {$type == "1"} {
  181.        
  182.         if {[info exists ::sp_version]} {
  183.             putlog "\[newtime\] $nick/$chan/$text"
  184.           #  set data [encoding convertfrom cp1251 $data]
  185.         } else {
  186.             putlog "\[newtime\] $nick/$chan/[encoding convertto utf-8 $text]"
  187.         }
  188.  
  189.         regsub -nocase -- {^.*?<div id="container">} $data "" data
  190.         regsub -nocase -- {<div class="selected">.*?$} $data "" data
  191.     egglib::writedata newtime.txt [list $data]
  192. if 0 { 
  193.     <div class="mainContent">
  194.     <div class="current-time">
  195.         <div class="time">
  196.             <h3><span>ТОЧНОЕ ВРЕМЯ В  Зеленоград</span></h3>
  197.             <div class="date" id="main1_global_date">четверг, 17 ноября 2011</div>
  198.             <div class="clock" id="main_clock1">12:36<span class="seconds">:04</span></div>
  199.             <div class="utc"><span class="main1_utc_offset" data-timeformat="am">UTC+4</span></div>
  200.             <div class="daytime night" id="main_clock1_daytime">Ночь</div>
  201.             <div class="clearfloat"></div>
  202.             <span id="main1_sub_timezone_offset">MSK+0</span>, <span id="main1_sub_timezone">Europe/Moscow</span>
  203.         </div>
  204.        
  205.     }
  206.    
  207.     if 0 {
  208.     <h3><span class="homecity_name_text text_tgl">Точное время в Москве</span></h3><div class="city_view_clock city_clock"><div class="city_clock_board">15:27<span class="city_clock_board_secs">15</span></div><div class="city_clock_info"><span class="timeofday with_icon day">День</span>UTC+0&nbsp;&nbsp;MSK-3<span class="timeofday">Europe/London</span><div class="sunrise_sunset"><span class="timeofday"><strong>Восход:</strong> </span><span class="timeofday"><strong>Заход:</strong> </span></div></div></div><p class="city_view_date">пятница, 20 марта 2015</p>
  209.    
  210.     }
  211.  
  212.         set nmsg [list]
  213.        
  214.         if {![regexp -nocase -- {<div class="city_view_box">(.+?)<noindex>} $data - data]} {
  215.                 putserv "PRIVMSG $chan :$newtime(color3)\002$nick\002$newtime(color1), Такого города не существует или нет в нашей базе городов, или ошибка обработки $newtime(color1)..."
  216.                 set newtime(lasttime,$chan) [clock seconds]
  217.                 return 0
  218.         }
  219.        
  220.        
  221.             if {[regexp -nocase -- {<div class="city_clock_board">(.+?)</div>.*?<p class="city_view_date">(.+?)</p>} $data -> time date]} {
  222.             regsub -all -- {<.*?>} $date {} date
  223.             regsub -all -- {<.*?>} $time {:} time
  224.                 lappend nmsg "$newtime(color3)[string totitle $date], [string trim $time ":"] $newtime(color1)::"
  225.             }
  226.  
  227.  
  228.             if {[regexp -nocase -- {<h\d+.*?">Точное время в(.*?)</span>.*?<span class="timeofday">(.*?)</span><div class="sunrise_sunset">} $data -> city region]} {
  229.                lappend nmsg "$newtime(color1)Точное текущее время в г. $newtime(color2)[string trim $city]$newtime(color1), $newtime(color2)[string trim $region]$newtime(color1),"
  230.            }
  231.            
  232.        
  233.             if {[regexp -nocase -- {</span>(UTC[\+\-]\d+).*?(MSK[\+\-]\d+)<span} $data - utc msk]} {
  234.             lappend nmsg "$newtime(color2)$utc (по Гринвичу), $msk (по Московскому времени)"
  235.            
  236.             }
  237.            
  238.            
  239.            if {![llength $nmsg]} {
  240.                putserv "PRIVMSG $chan :$newtime(color3)\002$nick\002$newtime(color1), Такого города не существует или нет в нашей базе городов $newtime(color1)..."
  241.                set newtime(lasttime,$chan) [clock seconds]
  242.                return 0
  243.            }
  244.            
  245.             set nmsg [regsub -all -- {[\x20\x09]+} [regsub -all -- {<.*?>} [join $nmsg] { }] { }]
  246.  
  247.            if {[regexp -nocase -- {<div class="info">(.*?)</div>} $data -> ninfo]} {
  248.                regsub -all -- {\s+} $ninfo { } ninfo
  249.                regsub -all -- {<br>} $ninfo {$newtime(color1),$newtime(color2)} ninfo
  250.                set ninfo [string trim $ninfo]
  251.                lappend nmsg "$newtime(color2)[subst -nocommand $ninfo]\003$newtime(color1)."
  252.            }
  253.            
  254.  
  255.            if {$auto == "0"} {
  256.                putserv "PRIVMSG $chan :$nmsg \00315([format "%.2f" [expr ([clock clicks] - $newtime(start))/1000.0/1000.0]]c.)\003"
  257.                set newtime(lasttime,$chan) [clock seconds]
  258.                return 0
  259.            } else {
  260.                putserv "PRIVMSG $chan :$nmsg \00315([format "%.2f" [expr ([clock clicks] - $newtime(start))/1000.0/1000.0]]c.)\003"
  261.            }
  262.        
  263.      
  264.    } else {
  265.        # Поддержка Suzi?
  266.        if {[info exists ::sp_version]} {
  267.            set ntext $text
  268.        } else {
  269.            set ntext [encoding convertfrom cp1251 $text]
  270.        }
  271.  
  272.        set newtime_tok [::http::config -useragent "Mozilla/4.0 (compatible; MSIE 4.01; Windows CE; PPC; 240x320)"]
  273.        set newtime_tok [::http::geturl "http://www.timeserver.ru/compare/[lindex [split $ntext "+"] 0]/[lindex [split $ntext "+"] 1]" -timeout 15000]  
  274.        set data [::http::data $newtime_tok]
  275.        ::http::cleanup $newtime_tok
  276.  
  277.        if {[info exists ::sp_version]} {
  278.            putlog "\[newtime\] $nick/$chan/Compare: [lindex [split $ntext] 0]/[lindex [split $ntext] 1]"
  279.            set data [encoding convertfrom cp1251 $data]
  280.        } else {
  281.            putlog "\[newtime\] $nick/$chan/Compare: [encoding convertto utf-8 [lindex [split $ntext] 0]/[lindex [split $ntext] 1]]"
  282.        }
  283.  
  284.        regsub -all -- "\n" $data "" data
  285.        regsub -all -- {\s+} $data { } data
  286.        if {[regexp -nocase -- {</fieldset> </form> </div> <div>(.*?)\..*?<a } $data -> error]} {
  287.            regexp {<div>\ (.*?)\ -} $error "" city
  288.            putserv "PRIVMSG $chan :$newtime(color3)$nick$newtime(color1), города $newtime(color2)$city $newtime(color1)не существует или нет в нашей базе городов.\003"
  289.            set newtime(lasttime,$chan) [clock seconds]
  290.            return 0
  291.        }
  292.  
  293.        foreach line [split $data "\n"] {
  294.            if {[regexp -nocase -- {<div>(.*?)<span id="clock_head">.*?</span></div>} $line -> date]} {
  295.                set date "$newtime(color3)$date $newtime(color1)::"
  296.            }
  297.        }
  298.  
  299.        regexp {<div class="difference">(.*?)</div>} $data "" diff
  300.        regsub -all -- "<strong>| </strong>" $diff "\002" diff
  301.        regexp {<div\ class=\"compared\ \">(.*?)<br } $data "" data
  302.        regsub -all -- "<div class=\"city\">" $data "|" data
  303.         regsub -all -- "<a .*?>" $data "" data
  304.         regsub -all -- "</a>" $data "" data
  305.         regsub -all -- "<br>" $data "," data
  306.         foreach line [split $data "|"] {
  307.             if {[regexp -nocase -- {<h2>(.*?) <span>\((.*?)\)</span>.*?</h2> <div class="time"> <div class="clock" id=".*?">(.*?)</div> <div class="info">\ (.*?),} $line -> ncity nregion ntime ninfo]} {
  308.                 lappend compare "$newtime(color2)$ncity$newtime(color1), $newtime(color2)$nregion $newtime(color1)($newtime(color3)$ntime$newtime(color1), $newtime(color2)$ninfo$newtime(color1))"
  309.             }
  310.         }
  311.  
  312.         putserv "PRIVMSG $chan :$date $newtime(color1)Между [lindex $compare 0] $newtime(color1)и [lindex $compare 1] $newtime(color3)$diff \00315([expr ([clock clicks] - $newtime(start))/1000.0]мc.)\003"
  313.         set newtime(lasttime,$chan) [clock seconds]
  314.         return 0
  315.         }  
  316.        
  317.                
  318.         } else {
  319.         ::http::cleanup $newtime_tok
  320.         putserv "NOTICE $nick :Не удалось соединиться с сервером. Попробуйте позже."
  321.         return
  322.         }
  323. }
  324.  
  325. # Процедура переводит текст набранный в неправильно раксладке.
  326. proc ::newtime::en2ru {t} {
  327.     return [string map {f а \, б d в u г l д t е \` ё \; ж p з b и q й r к k л v м y н j о g п h р c с n т e у a ф \[ х w ц x ч i ш m ь o щ \] ъ \' э s ы \. ю z я} [string tolower $t]]
  328. }
  329.  
  330. # Возвращает правильное окончание слов.
  331. proc ::newtime::numgrp {number} {
  332.    switch -glob -- "$number" {
  333.        *11 {return 3}
  334.        *12 {return 3}
  335.        *13 {return 3}
  336.        *14 {return 3}
  337.        *1 {return 1}
  338.        *2 {return 2}
  339.        *3 {return 2}
  340.        *4 {return 2}
  341.        default {return 3}
  342.    }
  343. }
  344.  
  345. # Выводим сообщение о том, что скрипт удачно загружен.
  346. putlog "\[newtime\] $newtime(version) by $newtime(author) loaded"
  347. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement