irc-summon: Share list of bot users with `irc-identpass'.
[ircbot] / usebnbot.tcl
1 # Code for starting up bnbot
2
3 proc def_bnbot {name argl body} {
4 proc "bnbot_$name" [concat botid $argl] \
5 "bnbot__vars\n
6 $body"
7 }
8
9 proc bnbot__vars {} {
10 global bnbot_callervars
11 upvar 1 botid botid
12 foreach v [concat {
13 host port nick pass channel
14 chan mbokafter state chanfn
15 } $bnbot_callervars] {
16 uplevel 1 [list upvar #0 "bot/$botid/$v" bn$v]
17 }
18 }
19
20 def_bnbot ensure_connecting {} {
21 global muststartby_ms bnbot
22
23 if {[info exists bnchan]} return
24 defset bnport 6112
25 set bnchan [open [list | $bnbot $bnhost $bnport] w+]
26 fconfigure $bnchan -buffering line
27 set bnmbokafter [after $muststartby_ms \
28 "fail {bot $botid not ok within timeout}"]
29 set bnstate Connected
30 fileevent $bnchan readable [list bnbot_onread $botid]
31 }
32
33 def_bnbot write {str} {
34 log "[clock seconds] -$botid-> $str"
35 puts $bnchan $str
36 }
37
38 def_bnbot writemsg {str} {
39 if {[regexp {^/} $str]} { set str " $str" }
40 bnbot_write $botid $str
41 }
42
43 def_bnbot onread {args} {
44 global channel
45 if {[gets $bnchan l] == -1} { fail "bot $botid EOF/error on input" }
46 if {[regexp {^1005 TALK ([^ ]+) \w+ \"(.*)\"$} $l dummy n text]} {
47 sendprivmsg $channel "\[$n] $text"
48 return
49 } elseif {[regexp {^1023 EMOTE ([^ ]+) \w+ \"(.*)\"$} $l dummy n text]} {
50 if {![ircnick_compare $n $bnnick]} return
51 sendprivmsg $channel "* $n $text"
52 return
53 }
54 log "[clock seconds] <-$botid- $l"
55 if {[string length $bnstate] && [regexp "^$bnstate" $l]} {
56 switch -exact $bnstate {
57 Connected { set bnstate Username }
58 Username { set bnstate Password; bnbot_write $botid $bnnick }
59 Password {
60 set bnstate "1007 CHANNEL"
61 puts $bnchan $bnpass
62 }
63 {1007 CHANNEL} {
64 set bnstate {}
65 bnbot_write $botid "/CHANNEL $bnchannel"
66 }
67 default { error "wrong bnstate: $bnstate" }
68 }
69 } elseif {[regexp {^1007 CHANNEL "(.*)"} $l dummy bnchanfn]} {
70 after cancel $bnmbokafter
71 unset bnmbokafter
72 } elseif {[info exists bnchanfn]} {
73 bnbot_event $botid $l
74 }
75 }