Split to / from message formats for the bot

This commit is contained in:
Graham Christensen 2018-01-10 19:55:05 -05:00
parent 5c06fc3d26
commit bc5c1ba69b
No known key found for this signature in database
GPG key ID: 06121D366FE9435C
2 changed files with 25 additions and 8 deletions

View file

@ -24,11 +24,18 @@ use ircbot::config;
use std::env;
#[derive(Serialize, Deserialize, Debug)]
struct Message {
struct MessageToIRC {
target: String,
body: String
}
#[derive(Serialize, Deserialize, Debug)]
struct MessageFromIRC {
from: String,
sender: String,
body: String
}
fn main() {
if let Err(_) = env::var("RUST_LOG") {
env::set_var("RUST_LOG", "info");
@ -58,12 +65,12 @@ fn main() {
let consumer_name = channel.basic_consume(
move |chan: &mut Channel, _deliver: Deliver, _headers: BasicProperties, body: Vec<u8>| {
debug!("Got a message");
let msg: Result<Message, serde_json::Error> = serde_json::from_slice(&body);
let msg: Result<MessageFromIRC, serde_json::Error> = serde_json::from_slice(&body);
if let Ok(msg) = msg {
let trigger = msg.body.trim();
if let Some(response) = factoids.get(trigger) {
let resp = Some(Message{
target: msg.target.clone(),
let resp = Some(MessageToIRC{
target: msg.from.clone(),
body: response.clone(),
});

View file

@ -28,11 +28,18 @@ use std::thread;
use std::env;
#[derive(Serialize, Deserialize, Debug)]
struct Message {
struct MessageToIRC {
target: String,
body: String
}
#[derive(Serialize, Deserialize, Debug)]
struct MessageFromIRC {
from: String,
sender: String,
body: String
}
fn main() {
if let Err(_) = env::var("RUST_LOG") {
env::set_var("RUST_LOG", "info");
@ -72,7 +79,7 @@ fn main() {
thread::spawn(move || {
let consumer_name = readchan.basic_consume(
move |_channel: &mut Channel, _deliver: Deliver, _headers: BasicProperties, body: Vec<u8>| {
let msg: Result<Message, serde_json::Error> = serde_json::from_slice(&body);
let msg: Result<MessageToIRC, serde_json::Error> = serde_json::from_slice(&body);
if let Ok(msg) = msg {
server.send_privmsg(&msg.target, &msg.body).unwrap();
}
@ -90,10 +97,13 @@ fn main() {
reader.for_each_incoming(|message| {
match message.command {
Command::PRIVMSG(ref _target, ref msg) => {
let msg = serde_json::to_string(&Message{
target: message.response_target()
let msg = serde_json::to_string(&MessageFromIRC{
from: message.response_target()
.expect("a response target for a privmsg")
.to_owned(),
sender: message.source_nickname()
.expect("a source nickname for a privmsg")
.to_owned(),
body: msg.clone(),
}).unwrap();