aob-lemmy-bot/src/main.rs

157 lines
4.7 KiB
Rust
Raw Normal View History

2023-07-29 00:32:58 +00:00
use chrono::{Utc, DateTime, NaiveTime, FixedOffset, TimeZone, NaiveDate, NaiveDateTime};
2023-06-22 20:08:10 +00:00
use config::{Config, PrevPost, Secrets, CommunitiesVector};
use lemmy_api_common::{
person::{Login, LoginResponse},
post::{CreatePost, GetPosts, GetPostsResponse},
2023-06-22 20:08:10 +00:00
sensitive::Sensitive,
};
use lemmy_db_schema::{
ListingType, SortType,
};
use once_cell::sync::Lazy;
use reqwest::{blocking::Client, StatusCode};
2023-07-29 00:32:58 +00:00
use std::{thread::{sleep, self}, time::{self, Duration}, io, vec, str::FromStr};
mod config;
pub static CLIENT: Lazy<Client> = Lazy::new(|| {
let client = Client::builder()
.timeout(time::Duration::from_secs(30))
.connect_timeout(time::Duration::from_secs(30))
.build()
.expect("build client");
client
});
struct Bot {
secrets: Secrets,
config: Config,
post_history: Vec<PrevPost>,
2023-06-19 17:21:28 +00:00
community_ids: CommunitiesVector,
auth: Sensitive<String>,
2023-06-22 20:08:10 +00:00
start_time: DateTime<Utc>,
}
impl Bot {
pub(crate) fn new() -> Bot {
Bot {
2023-06-22 20:08:10 +00:00
secrets: Secrets::init(),
config: Config::init(),
post_history: PrevPost::load(),
2023-06-19 17:21:28 +00:00
community_ids: CommunitiesVector::new(),
auth: Sensitive::new("".to_string()),
2023-06-22 20:08:10 +00:00
start_time: Utc::now(),
}
}
pub(crate) fn login(&mut self) {
let login_params = Login {
username_or_email: self.secrets.lemmy.get_username(),
password: self.secrets.lemmy.get_password(),
2023-07-09 08:18:51 +00:00
totp_2fa_token: None,
};
let res = CLIENT
2023-06-19 20:10:28 +00:00
.post(self.config.instance.clone() + "/api/v3/user/login")
.json(&login_params)
.send()
.unwrap();
if res.status() == StatusCode::OK {
let data: &LoginResponse = &res.json().unwrap();
let jwt = data.jwt.clone().expect("JWT Token could not be acquired");
self.auth = jwt;
} else {
println!("Error Code: {:?}", res.status());
panic!("JWT Token could not be acquired");
}
}
pub(crate) fn post(&mut self, post_data: CreatePost) {
let res = CLIENT
2023-06-19 20:10:28 +00:00
.post(self.config.instance.clone() + "/api/v3/post")
.json(&post_data)
.send()
.unwrap();
}
2023-06-22 20:08:10 +00:00
pub(crate) fn run_once(&mut self, mut prev_time: NaiveTime) {
self.start_time = Utc::now();
if self.start_time.time() - prev_time > chrono::Duration::seconds(6) { // Prod should use hours, add command line switch later and read duration from config
prev_time = self.start_time.time();
self.config.load();
self.community_ids.load(&self.auth, &self.config.instance);
}
// Start the polling process
// Get all feed URLs (use cache)
let post_queue: Vec<CreatePost> = self.config.check_feeds(&mut self.post_history, &self.community_ids, &self.auth);
post_queue.iter().for_each(|post| {
println!("Posting: {}", post.name);
self.post(post.clone());
});
}
2023-06-22 20:08:10 +00:00
pub(crate) fn idle(&self) {
2023-07-29 00:36:40 +00:00
while Utc::now().time() - self.start_time.time() < chrono::Duration::seconds(30) {
2023-06-22 20:08:10 +00:00
sleep(time::Duration::from_secs(10));
}
2023-07-29 00:36:40 +00:00
let _ = reqwest::blocking::get("https://status.neshweb.net/api/push/7s1CjPPzrV?status=up&msg=OK&ping=");
}
2023-07-29 00:32:58 +00:00
pub(crate) fn print_info(&self) {
print!("\x1B[2J\x1B[1;1H");
println!("##[Ascendance of a Bookworm Bot]##");
println!("Instance: {}", &self.config.instance);
println!("Ran Last: {}", &self.start_time.format("%d/%m/%Y %H:%M:%S"));
println!("{:#<1$}", "", 30);
self.post_history.iter().for_each(|post| {
print!("{} ", post.title);
print!("{:<1$}: ", "", 60 - post.title.len());
println!("{}", post.last_post_url);
})
}
}
2023-06-19 20:10:28 +00:00
fn list_posts(auth: &Sensitive<String>, base: String) -> GetPostsResponse {
let params = GetPosts {
type_: Some(ListingType::Local),
sort: Some(SortType::New),
auth: Some(auth.clone()),
..Default::default()
};
let res = CLIENT
2023-06-19 20:10:28 +00:00
.get(base + "/api/v3/post/list")
.query(&params)
.send()
.unwrap()
.text()
.unwrap();
return serde_json::from_str(&res).unwrap();
}
2023-07-29 00:32:58 +00:00
fn run_bot() {
2023-06-22 20:08:10 +00:00
// Get all needed auth tokens at the start
let mut old = Utc::now().time();
let mut this = Bot::new();
this.login();
this.community_ids.load(&this.auth, &this.config.instance);
// Enter a loop (not for debugging)
loop {
2023-07-29 00:36:40 +00:00
this.idle();
2023-06-22 20:08:10 +00:00
this.run_once(old);
2023-07-29 00:32:58 +00:00
this.print_info();
2023-07-14 22:09:34 +00:00
this.idle();
2023-06-21 19:29:14 +00:00
}
}
fn main() -> Result<(), io::Error> {
2023-07-29 00:32:58 +00:00
run_bot();
2023-06-21 19:29:14 +00:00
Ok(())
}