~alexwennerberg/ymtc_bot

e26f0091c90924b324a82f92f988de9a2e2c8b88 — alex wennerberg a month ago c8c339d master
Run cargo fmt
1 files changed, 65 insertions(+), 43 deletions(-)

M src/main.rs
M src/main.rs => src/main.rs +65 -43
@@ 1,10 1,10 @@
use titlecase::titlecase;
use dotenv;
use regex::Regex;
use reqwest;
use std::env::var;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use regex::Regex;
use std::env::var;
use titlecase::titlecase;

#[derive(Deserialize, Debug)]
struct Message {


@@ 14,10 14,9 @@ struct Message {
    timestamp: String,
}


#[derive(Deserialize, Debug)]
struct User {
    username: String
    username: String,
}

// https://github.com/Cockatrice/Cockatrice/wiki/Custom-Cards-&-Sets


@@ 42,7 41,8 @@ impl MTGCard {
        // 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();
        let re =
            Regex::new(r#"(?si)^(.*)\b[ |-]*([wubxrg\d]+)\s*\n(.*?)\n(.*?)(\d?/?\d?)$"#).unwrap();
        match re.captures(&content) {
            Some(caps) => {
                let pt = match &caps[5].contains("/") {


@@ 51,21 51,29 @@ impl MTGCard {
                };
                let loyalty = match &caps[5].contains("/") {
                    true => String::new(),
                    false => caps[5].to_owned()
                    false => caps[5].to_owned(),
                };
                // get cap 5
                Some(Self {
                name: titlecase(&caps[1]),
                mana_cost: caps[2].to_owned(),
                type_line: titlecase(&caps[3]),
                text: caps[4].to_owned(),
                power_toughness: pt,
                loyalty: loyalty,
                creator: String::new(), // TODO
            })},
                    name: titlecase(&caps[1]),
                    mana_cost: caps[2].to_owned(),
                    type_line: titlecase(&caps[3]),
                    text: caps[4].to_owned(),
                    power_toughness: pt,
                    loyalty: loyalty,
                    creator: String::new(), // TODO
                })
            }
            None => {
                // cant parse lands at the moment
                for maybe in vec!["creature", "instant", "sorcery", "enchantment", "artifact", "planeswalker"] {
                for maybe in vec![
                    "creature",
                    "instant",
                    "sorcery",
                    "enchantment",
                    "artifact",
                    "planeswalker",
                ] {
                    if msg.to_lowercase().contains(&format!("\n{}", maybe)) {
                        // println!("Maybe missing: {}", msg);
                        // println!("{:?}", content);


@@ 78,7 86,8 @@ impl MTGCard {

    fn into_xml(&self) -> String {
        // lazy and not using an xml library. probably should escape stuff.
        return format!(r#"
        return format!(
            r#"
<card>
<name>{}</name>
<text>{}</text>


@@ 92,21 101,28 @@ impl MTGCard {
<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), 
</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 { 
fn clean_xml(s: &str) -> String {
    let mut outstring = s.to_owned();
    for (character, replacement) in vec![("'", "&apos;"), ("\"", "&quot;"), ("&", "&amp;"), ("<", "&lt;"), (">", "&gt;")] {
    for (character, replacement) in vec![
        ("'", "&apos;"),
        ("\"", "&quot;"),
        ("&", "&amp;"),
        ("<", "&lt;"),
        (">", "&gt;"),
    ] {
        outstring = outstring.replace(character, replacement)
    }
    outstring


@@ 114,7 130,7 @@ fn clean_xml(s: &str) -> String {

fn main() {
    dotenv::dotenv().ok(); // TODO swap out with config file
    // TODO swap out reqwest with http
                           // TODO swap out reqwest with http
    let client = reqwest::blocking::Client::new();
    let mut last_id: Option<String> = None;
    let mut xml: String = r#"


@@ 127,7 143,8 @@ fn main() {
    <releasedate>2020-01-01</releasedate>
  </set>
  </sets>
  <cards>"#.to_owned();
  <cards>"#
        .to_owned();
    loop {
        let mut query: HashMap<&str, String> = HashMap::new();
        query.insert("limit", "100".to_owned());


@@ 135,32 152,38 @@ fn main() {
            query.insert("before", lid);
        }
        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()))
            .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().ok();
            .unwrap()
            .json()
            .ok();
        if let Some(b) = body {
            if b.len() > 0 {
                last_id = Some(b.get(b.len()-1).unwrap().id.clone());
            }
            else {
                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());
                  }
                let card = MTGCard::from_string(&message.content);
                if let Some(c) = card {
                    xml.push_str(&c.into_xml());
                }
            }
        }
        else {
        } else {
            break;
        }
    }
    xml.push_str("</cards></cockatrice_carddatabase>");
    println!("{}", xml);
    }
}

#[cfg(test)]
mod tests {


@@ 220,6 243,5 @@ Islandwalk

    #[test]

    fn test_broken_card() {
    }
    fn test_broken_card() {}
}