irc-bot/infobot.ml

74 lines
1.6 KiB
OCaml
Raw Normal View History

2010-12-08 17:18:07 -07:00
type t = {
filename: string;
mutable db: Cdb.cdb_file;
}
2009-11-08 22:18:18 -07:00
let _ = Random.self_init ()
2010-12-08 17:18:07 -07:00
let create filename =
{
filename = filename;
db = Cdb.open_cdb_in filename;
}
2009-11-08 22:18:18 -07:00
let choice l =
let n = Random.int (List.length l) in
List.nth l n
2010-12-08 17:18:07 -07:00
let strip s =
let rec lastchar n =
match s.[n-1] with
| '.'
| '!'
| '?'
| ' ' ->
lastchar (n - 1)
| _ ->
n
in
let len = lastchar (String.length s) in
if (len = String.length s) then
None
else
Some (String.sub s 0 len)
let choose_one ib key =
match (Cdb.get_matches ib.db key) with
| [] ->
raise Not_found
| keys ->
choice keys
2009-11-08 22:18:18 -07:00
2010-12-08 17:18:07 -07:00
let handle_privmsg store iobuf sender target text =
2009-11-08 22:18:18 -07:00
try
2010-12-08 17:18:07 -07:00
let text, factoid =
try
(text, choose_one store text)
with Not_found ->
match (strip text) with
| None ->
raise Not_found
| Some stext ->
(stext, choose_one store stext)
in
2009-11-08 22:18:18 -07:00
let response =
match factoid.[0] with
| ':' ->
"\001ACTION " ^ (Str.string_after factoid 1) ^ "\001"
| '\\' ->
Str.string_after factoid 1
| _ ->
2010-12-08 17:18:07 -07:00
Printf.sprintf "I overheard that %s is %s" text factoid
2009-11-08 22:18:18 -07:00
in
Iobuf.write iobuf (Command.create None "PRIVMSG" [target] (Some response))
with Not_found ->
()
2010-12-08 17:18:07 -07:00
let handle_command store iobuf cmd =
2009-11-08 22:18:18 -07:00
match Command.as_tuple cmd with
| (Some sender, "PRIVMSG", [target], Some text) ->
if Irc.is_channel target then
2010-12-08 17:18:07 -07:00
handle_privmsg store iobuf sender target text
2009-11-08 22:18:18 -07:00
| _ ->
()