Skip to content

Commit

Permalink
Made things compile and stuff
Browse files Browse the repository at this point in the history
  • Loading branch information
Vonk authored and kazie committed Oct 5, 2024
1 parent 4bee39a commit b642d39
Show file tree
Hide file tree
Showing 6 changed files with 56 additions and 64 deletions.
7 changes: 7 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,5 @@ rocket = { version = "0.5.1", features = ["json"] }
chrono = "0.4.31"
clokwerk = "0.4.0"
rand = { version = "0.8.5", features = ["small_rng"] }
async-trait = "0.1.83"
async-trait = "0.1.83"
anyhow = "1.0.89"
37 changes: 14 additions & 23 deletions src/client.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
use rocket::futures::FutureExt;
use std::collections::HashMap;
use std::error::Error;

use reqwest::Client;
use serde::de::StdError;
use reqwest::{Client};
use serde::Deserialize;
use anyhow::Result;

#[derive(Deserialize, Debug)]
pub struct Channel {
Expand Down Expand Up @@ -33,12 +31,12 @@ pub struct SlackClient {
#[async_trait::async_trait]
pub trait SlackClientTrait {
async fn get_channel_id_by_name(&self, channel_name: &str) -> Option<String>;
async fn get_channels(&self) -> Result<Vec<Channel>, Box<dyn Error>>;
async fn post_message(&self, channel_id: &str, message: &str) -> Result<(), Box<dyn Error>>;
async fn get_channels(&self) -> Result<Vec<Channel>>;
async fn post_message(&self, channel_id: &str, message: &str) -> Result<()>;
}

impl SlackClient {
pub fn new() -> Result<SlackClient, Box<dyn Error>> {
pub fn new() -> Result<SlackClient> {
let token = std::env::var("JOEL_BOT_SLACK_TOKEN")?;
Ok(SlackClient {
client: Client::new(),
Expand All @@ -62,7 +60,7 @@ impl SlackClientTrait for SlackClient {
}
}

async fn get_channels(&self) -> Result<Vec<Channel>, Box<dyn Error>> {
async fn get_channels(&self) -> Result<Vec<Channel>> {
let mut params = HashMap::new();
params.insert("token", self.token.clone());
params.insert("types", String::from("private_channel,public_channel"));
Expand All @@ -88,29 +86,22 @@ impl SlackClientTrait for SlackClient {
Ok(channels)
}

async fn post_message(&self, channel_id: &str, message: &str) -> Result<(), Box<dyn Error>> {
async fn post_message(&self, channel_id: &str, message: &str) -> Result<()> {
let mut params = HashMap::new();
params.insert("token", self.token.clone());
params.insert("channel", channel_id.to_string());
params.insert("text", message.to_string());

let result = self
.client
// let result = self
self.client
.post("https://slack.com/api/chat.postMessage")
.form(&params)
.send()
.await;

match result {
Ok(resp) => {
if resp.status().is_success() {
Ok(())
} else {
Err(Box::new(resp.error_for_status().unwrap_err()) as Box<dyn StdError>)
}
}
Err(e) => Err(Box::new(e) as Box<dyn StdError>),
}
.await?
.error_for_status()?;

Ok(())

}
}

5 changes: 2 additions & 3 deletions src/events.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
use crate::client::{SlackClient, SlackClientTrait};
use crate::last_day::{get_last_workday, is_last_workday};
use crate::config::Configuration;
use crate::last_day::get_last_workday;
use chrono::Utc;
use serde::Deserialize;
use std::sync::atomic::{AtomicPtr, Ordering};
use crate::config::Configuration;

use rocket::{config, Config};

#[derive(Deserialize)]
#[serde(tag = "type")]
Expand Down
6 changes: 3 additions & 3 deletions src/last_day.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use std::error::Error;

use chrono::{Datelike, NaiveDate};
use reqwest::Client;
use serde::Deserialize;
use anyhow::Result;

#[derive(Deserialize)]
struct SholidayFaboulResponse {
Expand All @@ -24,11 +24,11 @@ struct SholidayFaboulDay {
}


pub async fn is_last_workday(date: &NaiveDate) -> Result<bool, Box<dyn Error>> {
pub async fn is_last_workday(date: &NaiveDate) -> Result<bool> {
Ok(get_last_workday(date).await? == *date)
}

pub async fn get_last_workday(date: &NaiveDate) -> Result<NaiveDate, Box<dyn Error>> {
pub async fn get_last_workday(date: &NaiveDate) -> Result<NaiveDate> {
let client = Client::new();
let url = format!(
"https://sholiday.faboul.se/dagar/v2.1/{}/{}",
Expand Down
62 changes: 28 additions & 34 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,31 +1,25 @@
#[macro_use]
extern crate rocket;
use crate::last_day::{is_last_workday, get_last_workday};
use crate::last_day::{get_last_workday, is_last_workday};
use rand::SeedableRng;

use std::time::Duration;

use chrono::{Datelike, NaiveTime, Utc};
use clokwerk::Interval::Weekday;
use clokwerk::{AsyncScheduler, Job, Scheduler};
use clokwerk::{AsyncScheduler, Job};

use crate::config::*;
use rand::rngs::SmallRng;
use rand::{thread_rng, Rng};
use rand::Rng;
use reqwest::Client;
use rocket::form::Form;
use rocket::futures::future::BoxFuture;
use rocket::futures::FutureExt;
use rocket::response::status::Accepted;
use rocket::serde::json::Json;
use rocket::State;
use slack::client::*;
use slack::events;
use slack::events::{SlackRequest, SlackState};
use std::collections::HashMap;
use std::error::Error;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use tokio::time::sleep;

Expand All @@ -42,29 +36,7 @@ async fn main() {
scheduler
.every(Weekday)
.at_time(NaiveTime::from_hms_opt(9, 0, 0).unwrap())
.run(move || {
let config = config.clone();
let client = client.clone();
Box::pin(async move {
let today = Utc::now().date_naive();
match is_last_workday(&today).await {
Ok(true) => {
let context = today.month().to_string();
let message = config.get_message(&context);
match client.get_channel_id_by_name("allmant").await {
Some(channel_id) => {
if let Err(error) = client.post_message(&channel_id, &message).await {
println!("couldn't post message: {}", error)
}
}
None => println!("no channel with name 'allmant' found!"),
}
}
Ok(false) => println!("Not last work day"),
_ => {}
}
}) as Pin<Box<dyn Future<Output = ()> + Send>>
});
.run(move || last_workday_message(config.clone(), client.clone()));

tokio::spawn(async move {
loop {
Expand All @@ -85,6 +57,28 @@ async fn main() {
.expect("Server failed to start");
}

async fn last_workday_message(config: Arc<Configuration>, client: Arc<SlackClient>) {
let today = Utc::now().date_naive();
match is_last_workday(&today).await {
Ok(true) => {
let context = today.month().to_string();
let message = config.get_message(&context);
match client.get_channel_id_by_name("allmant").await {
Some(channel_id) => {
if let Err(error) = client.post_message(&channel_id, &message).await {
println!("couldn't post message: {}", error)
}
}
None => println!("no channel with name 'allmant' found!"),
}
}
Ok(false) => println!("Not last work day"),
Err(_) => {
// TODO Maybe handle error or nah?
}
};
}

#[post("/slack-request", format = "application/json", data = "<request>")]
async fn slack_request(state: &State<SlackState>, request: Json<SlackRequest>) -> String {
let slack_request_data = request.into_inner();
Expand All @@ -96,7 +90,7 @@ async fn slack_request(state: &State<SlackState>, request: Json<SlackRequest>) -
struct SlackSlashMessage {
// token: String, <-- We should save and validate this
// command: String, <-- can be used to check what command was used.
text: Option<String>,
// text: Option<String>,
response_url: String,
}

Expand All @@ -108,7 +102,7 @@ struct SlackSlashMessage {
async fn time_report(request: Form<SlackSlashMessage>) -> Accepted<String> {
let response_url = request.response_url.clone();

let calculations = vec![
let calculations = [
"vänta",
"beräknar",
"processerar",
Expand Down

0 comments on commit b642d39

Please sign in to comment.