Write IRC stats to file (e.g. to show on a website)

# chanstats.tcl
#
# Copyright (c) 2004 Jochen "Y0Gi" Kupperschmidt <http://homework.nwsnet.de/>
# Version: 17-Sep-2004
# Released under the terms of the MIT License.
#
# Periodically writes channel states to files (as plain
# text and XML by default) so you can use it e.g. on a
# website by retrieving and parsing it using PHP, Perl,
# Python or whatever is your language or tool of choice.
#
# Note: Does no checks, so correct XML is not guaranteed.

# configuration
set channels [list #somechannel1 #somechannel2 #somechannel3]
set output(text) 1
set output(xml) 1

bind time - "30 * * * *" chst:time:update

proc chst:time:update { min hour day month year } {
    global channels
    foreach chan $channels {
        chst:output [chst:getstats $chan]
    }
    return 0
}

proc chst:getstats { chan } {
    set stats(channel) $chan
    set stats(users_total) [llength [chanlist $chan]]
    set stats(users_op) 0
    set stats(users_voice) 0
    set stats(users_normal) 0
    foreach nickname [chanlist $chan] {
        if { [isop $nickname $chan] } {
            incr stats(users_op)
        } elseif { [isvoice $nickname $chan] } {
            incr stats(users_voice)
        } else {
            incr stats(users_normal)
        }
    }
    set stats(topic) [topic $chan]
    set stats(timestamp) [clock format [clock scan now] -format "%Y-%m-%d %R"]
    return [array get stats]
}

proc chst:output { stats } {
    global output
    if { $output(text) } {
        chst:output_text $stats
    }
    if { $output(xml) } {
        chst:output_xml $stats
    }
}

proc chst:output_text { stats } {
    array set stats_tmp $stats
    set fs [open "chanstats.$stats_tmp(channel).txt" w]
    foreach key [lsort [array names stats_tmp]] {
        puts $fs "$key: $stats_tmp($key)"
    }
    close $fs
}

proc chst:output_xml { stats } {
    array set stats_tmp $stats
    set fs [open "chanstats.$stats_tmp(channel).xml" w]
    puts $fs "<chanstats>"
    foreach key [lsort [array names stats_tmp]] {
        puts $fs "    <$key>$stats_tmp($key)</$key>"
    }
    puts $fs "</chanstats>"
    close $fs
}

putlog "chanstats.tcl loaded."