Skip to content

Instantly share code, notes, and snippets.

@suhr

suhr/dobrochat.rs Secret

Last active Aug 29, 2015
Embed
What would you like to do?
Tox groupbot for dobrochan
#![feature(globs,phase)]
#![feature(slicing_syntax)]
extern crate tox;
//extern crate debug;
#[phase(plugin, link)] extern crate log;
use tox::core::*;
use std::io::{File,Truncate,Write,FileNotFound};
use std::io::Timer;
use std::time::{Duration};
use std::os::args;
static BOOTSTRAP_IP: &'static str = "192.254.75.98";
static BOOTSTRAP_PORT: u16 = 33445;
static BOOTSTRAP_KEY: &'static str = "951C88B7E75C867418ACDB5D273821372BB5BD652740BCDF623A4FA293E75D2F";
static BOT_NAME: &'static str = "dobrobot";
fn usage(prog: &str) {
println!("usage: {} [tox_save]", prog);
}
fn save(tox: &Tox, path: Option<&Path>, tock: &Receiver<()>) {
if path.is_none() { return };
match tock.try_recv() {
Ok(_) => {
let mut out = File::open_mode(path.unwrap(), Truncate, Write).unwrap();
match out.write(tox.save()[]) {
Ok(_) => (),
Err(e) => {
error!("cannot save tox data: {}", e)
},
}
},
Err(_) => ()
}
}
fn main() {
let tox = Tox::new(ToxOptions::new()).unwrap();
tox.set_name(BOT_NAME.to_string()).unwrap();
let args = args();
let path; // pls, make a more elegant way to follow lifetimes
let tox_save: Option<&Path>;
match args.len() {
1 => {
tox_save = None;
},
2 => {
path = Path::new(args[1][]);
tox_save = Some(&path);
match File::open(tox_save.unwrap()) {
Ok(mut f) => match tox.load(f.read_to_end().unwrap()) {
Ok(_) => (),
Err(_) => error!("tox_save loaded with error"),
},
Err(e) => {
if e.kind != FileNotFound {
panic!("io error: {}", e);
}
}
}
},
_ => {
usage(args[0][]);
return;
}
}
let bootstrap_key = from_str(BOOTSTRAP_KEY).unwrap();
tox.bootstrap_from_address(BOOTSTRAP_IP.to_string(), BOOTSTRAP_PORT, box bootstrap_key).unwrap();
println!("Bot key: {}", tox.get_address());
let gchat = tox.add_groupchat().unwrap();
let mut bomb = Timer::new().unwrap(); // Oh my God! JC! A bomb!
let tick = bomb.periodic(Duration::milliseconds(500));
loop {
for ev in tox.events() {
match ev {
FriendRequest(id, msg) => {
match msg[] {
"dobrochan" => {
tox.add_friend_norequest(id).unwrap();
},
_ => ()
}
},
FriendMessage(fnum, msg) => {
match msg[] {
"invite" => tox.invite_friend(fnum, gchat).unwrap(),
_ => ()
}
},
GroupMessage(gid, _, msg) => {
match (gid, msg[]) {
(gchat, "%ping") => {
tox.group_message_send(gchat, "pong".to_string());
},
_ => ()
}
},
// GroupInvite(id, ref addr) if id == groupbot_id => {
// tox.join_groupchat(id, addr.clone()).unwrap();
// println!("invited to group");
// },
_ => { }
};
save(&tox, tox_save, &tick);
}
std::io::timer::sleep(Duration::milliseconds(50));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment