summaryrefslogtreecommitdiffstats
path: root/examples
diff options
context:
space:
mode:
authorJesse Luehrs <doy@tozt.net>2014-09-10 16:41:58 -0400
committerJesse Luehrs <doy@tozt.net>2014-09-10 16:41:58 -0400
commit3bbca4cdd221d392c8628773201d514b90ed40ce (patch)
tree2155ab512174b2d03c1269b9681ca169a4cd7fe0 /examples
parent5bca38d9af67001ea6d406c1a447e7cc80a41e29 (diff)
downloadrust-irc-master.tar.gz
rust-irc-master.zip
turn the client example into a simple karma botHEADmaster
Diffstat (limited to 'examples')
-rw-r--r--examples/client.rs48
1 files changed, 46 insertions, 2 deletions
diff --git a/examples/client.rs b/examples/client.rs
index db3b244..d4cc997 100644
--- a/examples/client.rs
+++ b/examples/client.rs
@@ -1,13 +1,57 @@
extern crate irc;
-pub struct ExampleClient;
+use std::collections::HashMap;
+use std::io;
+
+pub struct ExampleClient {
+ karma: HashMap<String, i32>,
+}
+
+impl ExampleClient {
+ pub fn new () -> ExampleClient {
+ ExampleClient { karma: HashMap::new() }
+ }
+}
impl irc::ClientCallbacks for ExampleClient {
+ fn on_rpl_welcome (&mut self, client: &mut irc::Client, _m: &irc::Message) -> io::IoResult<()> {
+ client.join(["#doytest"], [])
+ }
+
+ fn on_privmsg (&mut self, client: &mut irc::Client, from: Option<&str>, receivers: &[&str], text: &str) -> io::IoResult<()> {
+ let incr = if text.ends_with("++") { 1 }
+ else if text.ends_with("--") { -1 }
+ else { 0 };
+ if incr != 0 {
+ let text = text.slice(0, text.len() - 2);
+ let giving_user = String::from_utf8(
+ from.unwrap().bytes().take_while(|&c| c != b'!').collect()
+ ).unwrap();
+ if giving_user.as_slice() == text {
+ try!(client.notice(receivers[0], "You can't give karma to yourself!"));
+ }
+ else {
+ self.karma.insert_or_update_with(
+ text.to_string(),
+ incr,
+ |_k, v| { *v += incr }
+ );
+ }
+ }
+ else if text.starts_with("karma ") {
+ let text = text.slice_from(6);
+ let default = 0;
+ let karma = self.karma.find(&text.to_string()).unwrap_or(&default);
+ try!(client.notice(receivers[0], format!("Karma for {} is {}", text, karma).as_slice()));
+ }
+
+ Ok(())
+ }
}
fn main () {
let mut builder = irc::ClientBuilder::new("doytest", "chat.freenode.net");
builder.set_debug(true);
let client = builder.connect();
- client.run_loop_with_callbacks(ExampleClient);
+ client.run_loop_with_callbacks(ExampleClient::new());
}