Skip to content

Commit

Permalink
add commands
Browse files Browse the repository at this point in the history
  • Loading branch information
hails committed Mar 19, 2020
1 parent dd0a219 commit fbd78fe
Show file tree
Hide file tree
Showing 3 changed files with 128 additions and 2 deletions.
8 changes: 8 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,11 @@ edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
telegram-bot = { git = "https://github.com/telegram-rs/telegram-bot" }
tokio = { version = "0.2", features = ["full"] }
futures = "0.3.4"
scraper = { git = "https://github.com/causal-agent/scraper"}
reqwest = { version = "0.10.4" }
select = {version = "0.4.3"}
regex = "1"

86 changes: 86 additions & 0 deletions src/commands.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
use regex::Regex;
use reqwest;
use select::document::Document;
use select::predicate::{Class, Name, Predicate};
use telegram_bot::*;

pub async fn start(api: &Api, message: &Message) -> Result<(), Error> {
api.send(message.text_reply(format!(
"Olá, {}! Esse bot irá lhe ajudar a acompanhar o estado do seu processo.\n\
Para começarmos, preciso que me envie o código do processo.\n\
Simplesmente digite /code CODIGO que comecarei a acompanhar.",
message.from.first_name
)))
.await?;
Ok(())
}

pub async fn invalid(api: &Api, message: &Message) -> Result<(), Error> {
api.send(message.text_reply(
"Command not found!\n\
Use /help to list the available commands",
))
.await?;

Ok(())
}

pub async fn code(api: &Api, message: &Message, data: &String) -> Result<(), Error> {
let code: String = data.split_whitespace().skip(1).take(1).collect();

let reply = if code.is_empty() {
String::from("Você me precisa me enviar algum código")
} else {
let process = fetch_citizenship_status(&code).await.unwrap();
format!(
"Status: {}\n\
Mensagem: {}",
process.status, process.info
)
};

api.send(message.text_reply(reply)).await?;

Ok(())
}

struct Process {
status: String,
info: String,
}

async fn fetch_citizenship_status(code: &String) -> Result<Process, reqwest::Error> {
let res = reqwest::Client::new()
.post("https://nacionalidade.justica.gov.pt/Home/GetEstadoProcessoAjax")
.form(&[("SenhaAcesso", code)])
.send()
.await?;
let body = res.text().await?;

let document = Document::from(body.as_str());

let mut process = Process {
status: String::from("Unknown"),
info: String::from(""),
};

if let Some(st) = document.find(Class("active1").descendant(Name("p"))).last() {
process.status = st.text();
}

if let Some(st) = document.find(Class("active2").descendant(Name("p"))).last() {
process.status = st.text();
}

if let Some(st) = document.find(Class("active3").descendant(Name("p"))).last() {
process.status = st.text();
}

if let Some(st) = document.find(Class("container")).nth(5) {
let re = Regex::new(r"\s+").unwrap();

process.info = re.replace_all(&st.text(), " ").trim().to_string();
}

Ok(process)
}
36 changes: 34 additions & 2 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,35 @@
fn main() {
println!("Hello, world!");
use std::env;

use futures::StreamExt;
use telegram_bot::*;
mod commands;

#[tokio::main]
async fn main() -> Result<(), Error> {
let token = env::var("TELEGRAM_BOT_TOKEN").expect("TELEGRAM_BOT_TOKEN not set");
let api = Api::new(token);

// Fetch new updates via long poll method
let mut stream = api.stream();
while let Some(update) = stream.next().await {
// If the received update contains a new message...
let update = update?;
if let UpdateKind::Message(message) = update.kind {
if let MessageKind::Text { ref data, .. } = message.kind {
match data.as_str() {
"/start" => commands::start(&api, &message).await?,
command if command.starts_with("/code") => {
commands::code(&api, &message, data).await?
}
_ => commands::invalid(&api, &message).await?,
}

// Print received text message to stdout.
println!("<{}>: {}", &message.from.first_name, data);

()
}
}
}
Ok(())
}

0 comments on commit fbd78fe

Please sign in to comment.