~alexwennerberg/ymtc_bot

48143c031d87f2570d94e31bda5fb5cf7ff6e47d — alex wennerberg a month ago 8b4b734
Clean up regex, convert to XML
1 files changed, 87 insertions(+), 17 deletions(-)

M src/main.rs
M src/main.rs => src/main.rs +87 -17
@@ 27,9 27,9 @@ struct MTGCard {
    mana_cost: String,
    type_line: String,
    text: String,
    power_toughness: Option<String>,
    loyalty: Option<String>,
    creator: Option<String>
    power_toughness: String,
    loyalty: String,
    creator: String,
}

impl MTGCard {


@@ 39,17 39,19 @@ impl MTGCard {
        let content = re.replace_all(msg, "$1");
        let re = Regex::new(r#"<:([wubrgc])[wubrgc]:\d*>"#).unwrap();
        let content = re.replace_all(&content, "$1");
        let re = Regex::new(r#"(?si)^([\w| ]*)\b[ |-]*([wubrg\d]+)\n(.*?)\n(.*?)(\d?/?\d?)$"#).unwrap();
        // mis-typed emojis
        let re = Regex::new(r#":([wubrgc])[wubrgc]:"#).unwrap();
        let content = re.replace_all(&content, "$1");
        let re = Regex::new(r#"(?si)^(.*)\b[ |-]*([wubxrg\d]+)\s*\n(.*?)\n(.*?)(\d?/?\d?)$"#).unwrap();
        match re.captures(&content) {
            Some(caps) => {
                println!("{:?}", caps);
                let pt = match &caps[5].contains("/") {
                    true => Some(caps[5].to_owned()),
                    false => None
                    true => caps[5].to_owned(),
                    false => String::new(),
                };
                let loyalty = match &caps[5].contains("/") {
                    true => None,
                    false => Some(caps[5].to_owned())
                    true => String::new(),
                    false => caps[5].to_owned()
                };
                // get cap 5
                Some(Self {


@@ 59,18 61,55 @@ impl MTGCard {
                text: caps[4].to_owned(),
                power_toughness: pt,
                loyalty: loyalty,
                creator: None,
                creator: String::new(), // TODO
            })},
            None => {
                for maybe in vec!["creature", "instant", "sorcery", "enchantment", "land", "artifact", "planeswalker"] {
                // cant parse lands at the moment
                for maybe in vec!["creature", "instant", "sorcery", "enchantment", "artifact", "planeswalker"] {
                    if msg.to_lowercase().contains(&format!("\n{}", maybe)) {
                        println!("Maybe missing: {}", msg);
                        // println!("Maybe missing: {}", msg);
                        // println!("{:?}", content);
                    }
                }
                None
            }
        }
    }

    fn into_xml(&self) -> String {
        // lazy and not using an xml library. probably should escape stuff.
        return format!(r#"
<card>
<name>{}</name>
<text>{}</text>
<prop>
<side>front</side>
<layout>normal</layout>
<manacost>{}</manacost>
<type>{}</type>
<creator>{}</creator>
<pt>{}</pt>
<loyalty>{}</loyalty>
</prop>
<set>YMTC</set>
</card>"#, clean_xml(&self.name), 
            clean_xml(&self.text), 
            clean_xml(&self.mana_cost), 
            clean_xml(&self.type_line), 
            clean_xml(&self.creator), 
            clean_xml(&self.power_toughness), 
            clean_xml(&self.loyalty) // uggo
                )
    }
}

// TODO use a library
fn clean_xml(s: &str) -> String { 
    let mut outstring = s.to_owned();
    for (character, replacement) in vec![("'", "&apos;"), ("\"", "&quot;"), ("&", "&amp;"), ("<", "&lt;"), (">", "&gt;")] {
        outstring = outstring.replace(character, replacement)
    }
    outstring
}

fn main() {


@@ 78,23 117,49 @@ fn main() {
    // TODO swap out reqwest with http
    let client = reqwest::blocking::Client::new();
    let mut last_id: Option<String> = None;
    let mut xml: String = r#"
<cockatrice_carddatabase version="4">
  <sets>
    <set>
    <name>YMTC</name>
    <longname>You Make the Card from Discord Chat</longname>
    <settype>Expansion</settype>
    <releasedate>2020-01-01</releasedate>
  </set>
  </sets>
  <cards>"#.to_owned();
    loop {
        let mut query: HashMap<&str, String> = HashMap::new();
        query.insert("limit", "100".to_owned());
        if let Some(lid) = last_id {
            query.insert("before", lid);
        }
        let body: Vec<Message> = client
        let body: Option<Vec<Message>> = client
            .get(&format!("https://discord.com/api/channels/{}/messages", var("CHANNEL_ID").unwrap()))
            .header("Authorization", format!("Bot {}", var("YMTC_BOT_TOKEN").unwrap()))
            .query(&query)
            .send()
            .unwrap().json().unwrap();
        last_id = Some(body.get(1).unwrap().id.clone());
        for message in body {
            let card = MTGCard::from_string(&message.content);
            .unwrap().json().ok();
        if let Some(b) = body {
            if b.len() > 0 {
                last_id = Some(b.get(b.len()-1).unwrap().id.clone());
            }
            else {
                break;
            }
            for message in b {
                  let card = MTGCard::from_string(&message.content);
                  if let Some(c) = card {
                      xml.push_str(&c.into_xml());
                  }
            }
        }
        else {
            break;
        }
    }
    xml.push_str("</cards></cockatrice_carddatabase>");
    println!("{}", xml);
    }

#[cfg(test)]


@@ 152,4 217,9 @@ Islandwalk
        assert_eq!(mtgc.name, "Grizzly Bear");
        assert_eq!(mtgc.power_toughness, Some("2/2".to_owned()));
    }

    #[test]

    fn test_broken_card() {
    }
}