Skip to content
This repository has been archived by the owner on Jan 17, 2023. It is now read-only.

Commit

Permalink
Add include_only setting
Browse files Browse the repository at this point in the history
  • Loading branch information
oSumAtrIX committed Nov 5, 2021
1 parent 5ac5318 commit 1412627
Show file tree
Hide file tree
Showing 6 changed files with 113 additions and 87 deletions.
2 changes: 1 addition & 1 deletion Cargo.lock

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

4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ cargo-features = ["strip"]

[package]
name = "dinkleberg"
version = "0.1.3"
version = "0.2.3"
edition = "2021"
authors = ["oSumAtrIX <[email protected]>"]
build = "build.rs"
Expand All @@ -29,4 +29,4 @@ winres = "^0.1"
OriginalFilename = "dinkleberg.exe"
FileDescription = "Find out who is pretending to be offline"
ProductName = "Dinkleberg"
ProductVersion = "0.1.3"
ProductVersion = "0.2.3"
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,8 @@ For that, widgets must be enabled in the targets server settings under `Server S

Set `use_widget` in the `settings.json` to false to use the discord bot API endpoint instead.

Adding user ids to `include_only` list, separated by a comma, will only track those users. Leaving it empty as-is will track all users in the targeted guild. Filtering helps with rate limiting and false detection a lot and should be considered to be used.

## Usage/ Examples

```text
Expand Down
62 changes: 41 additions & 21 deletions src/handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ pub struct Handler {
guild_id: u64,
users: Mutex<Users>,
use_widget: bool,
include_only: Vec<u64>,
}

struct Users {
Expand All @@ -38,6 +39,7 @@ impl Handler {
count: 0,
}),
use_widget: settings.use_widget,
include_only: settings.include_only.clone(),
}
}

Expand All @@ -56,29 +58,42 @@ impl Handler {
return Ok((0, 0));
}
};
let presence_count= match self.use_widget {
let presence_count = match self.use_widget {
true => {
reqwest::blocking::get(&format!("https://canary.discord.com/api/guilds/{}/widget.json", guild_id))?.json::<Widget>()?.presence_count
},
reqwest::blocking::get(&format!(
"https://canary.discord.com/api/guilds/{}/widget.json",
guild_id
))?
.json::<Widget>()?
.presence_count
}
false => guild.approximate_presence_count.unwrap(),
};

Ok((
presence_count,
guild.approximate_member_count.unwrap(),
))
Ok((presence_count, guild.approximate_member_count.unwrap()))
}

// skip the user if they are not in the include_only list
fn skip_cycle(&self, id: &u64) -> bool {
if self.include_only.is_empty() || self.include_only.contains(id) {
return false;
}
true
}
// update user count and online count when a user joins or leaves the server to keep the count accurate
async fn refresh_users_count(&self, _ctx: Context, _guild_id: GuildId, user: User) {
if self.skip_cycle(&user.id.0) {
return;
}

let approximate_users = match self.get_approximate_user_counts(&_ctx, _guild_id).await {
Ok(users) => users,
Err(e) => {
println!("{}", format!("Could not refresh users count: {}", e).red());
return;
}
};

let approximate_online = approximate_users.0;
let approximate_count = approximate_users.1;
let mut tracked_users = self.users.lock().await;
Expand Down Expand Up @@ -128,21 +143,25 @@ impl EventHandler for Handler {
return;
}

if self.skip_cycle(&_new_data.presence.user_id.0) {
return;
}

let mut tracked_users = self.users.lock().await;

let (users_online, _) = match self
.get_approximate_user_counts(&_ctx, presence_guild)
.await
{
Ok(users) => users,
Err(e) => {
println!("{}", format!("Could not get user count: {}", e).red());
return;
}
};
.get_approximate_user_counts(&_ctx, presence_guild)
.await
{
Ok(users) => users,
Err(e) => {
println!("{}", format!("Could not get user count: {}", e).red());
return;
}
};

if let Some(user) = _new_data.presence.user {
if users_online != tracked_users.online{
if users_online != tracked_users.online {
tracked_users.online += 1;
}

Expand All @@ -158,8 +177,6 @@ impl EventHandler for Handler {
}

if _new_data.presence.status == OnlineStatus::Offline {


let user = _new_data
.presence
.user_id
Expand Down Expand Up @@ -196,7 +213,10 @@ impl EventHandler for Handler {
{
Ok(users) => users,
Err(e) => {
println!("{}", format!("Could not initialize users count: {}", e).red());
println!(
"{}",
format!("Could not initialize users count: {}", e).red()
);
return;
}
};
Expand Down
114 changes: 57 additions & 57 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,69 +10,69 @@ use std::env;

#[tokio::main]
async fn main() {
if cfg!(target_os = "windows") {
// clear console
std::process::Command::new("cmd")
.arg("/c")
.arg("cls")
.status()
.unwrap();
if cfg!(target_os = "windows") {
// clear console
std::process::Command::new("cmd")
.arg("/c")
.arg("cls")
.status()
.unwrap();

// legacy support
#[cfg(windows)]
if let Err(_) = control::set_virtual_terminal(true) {
println!("Failed to set virtual terminal")
};
} else {
// clear console
std::process::Command::new("clear").status().unwrap();
}
// legacy support
#[cfg(windows)]
if control::set_virtual_terminal(true).is_err() {
println!("Failed to set virtual terminal")
};
} else {
// clear console
std::process::Command::new("clear").status().unwrap();
}

// print logo
println!("\n{}\n", "'########::'####:'##::: ##:'##:::'##:'##:::::::'########:'########::'########:'########:::'######:::\n ##.... ##:. ##:: ###:: ##: ##::'##:: ##::::::: ##.....:: ##.... ##: ##.....:: ##.... ##:'##... ##::\n ##:::: ##:: ##:: ####: ##: ##:'##::: ##::::::: ##::::::: ##:::: ##: ##::::::: ##:::: ##: ##:::..:::\n ##:::: ##:: ##:: ## ## ##: #####:::: ##::::::: ######::: ########:: ######::: ########:: ##::'####:\n ##:::: ##:: ##:: ##. ####: ##. ##::: ##::::::: ##...:::: ##.... ##: ##...:::: ##.. ##::: ##::: ##::\n ##:::: ##:: ##:: ##:. ###: ##:. ##:: ##::::::: ##::::::: ##:::: ##: ##::::::: ##::. ##:: ##::: ##::\n ########::'####: ##::. ##: ##::. ##: ########: ########: ########:: ########: ##:::. ##:. ######:::\n........:::....::..::::..::..::::..::........::........::........:::........::..:::::..:::......::::".green());
// print logo
println!("\n{}\n", "'########::'####:'##::: ##:'##:::'##:'##:::::::'########:'########::'########:'########:::'######:::\n ##.... ##:. ##:: ###:: ##: ##::'##:: ##::::::: ##.....:: ##.... ##: ##.....:: ##.... ##:'##... ##::\n ##:::: ##:: ##:: ####: ##: ##:'##::: ##::::::: ##::::::: ##:::: ##: ##::::::: ##:::: ##: ##:::..:::\n ##:::: ##:: ##:: ## ## ##: #####:::: ##::::::: ######::: ########:: ######::: ########:: ##::'####:\n ##:::: ##:: ##:: ##. ####: ##. ##::: ##::::::: ##...:::: ##.... ##: ##...:::: ##.. ##::: ##::: ##::\n ##:::: ##:: ##:: ##:. ###: ##:. ##:: ##::::::: ##::::::: ##:::: ##: ##::::::: ##::. ##:: ##::: ##::\n ########::'####: ##::. ##: ##::. ##: ########: ########: ########:: ########: ##:::. ##:. ######:::\n........:::....::..::::..::..::::..::........::........::........:::........::..:::::..:::......::::".green());

// get discord token
let token = match env::var("DISCORD_TOKEN") {
Ok(token) => token,
Err(_) => {
println!(
"{}",
"Please set the environment variable DISCORD_TOKEN to continue".red()
);
return;
}
};
// get discord token
let token = match env::var("DISCORD_TOKEN") {
Ok(token) => token,
Err(_) => {
println!(
"{}",
"Please set the environment variable DISCORD_TOKEN to continue".red()
);
return;
}
};

// print usage
let args: Vec<String> = std::env::args().collect();
if args.len() < 2 {
println!("{}", format!("Usage: {} <guid_id>", args[0]).red());
return;
}
// print usage
let args: Vec<String> = std::env::args().collect();
if args.len() < 2 {
println!("{}", format!("Usage: {} <guid_id>", args[0]).red());
return;
}

// parse guild
let guild_id = match (&args[1]).parse::<u64>() {
Ok(n) => n,
Err(_) => panic!("{}", "Could not parse guid id".red()),
};
// parse guild
let guild_id = match (&args[1]).parse::<u64>() {
Ok(n) => n,
Err(_) => panic!("{}", "Could not parse guid id".red()),
};

let settings = match Settings::load() {
Ok(settings) => settings,
Err(_) => {
println!("{}", "Could not load settings".red());
return;
}
};
let settings = match Settings::load() {
Ok(settings) => settings,
Err(_) => {
println!("{}", "Could not load settings".red());
return;
}
};

// create client with custom handler implementing trait `EventHandler`
let mut client = Client::builder(token)
.event_handler(Handler::new(guild_id, &settings))
.intents(GatewayIntents::GUILD_PRESENCES | GatewayIntents::GUILD_MEMBERS)
.await
.unwrap_or_else(|_| panic!("{}", "Error creating client".red().to_string()));
// create client with custom handler implementing trait `EventHandler`
let mut client = Client::builder(token)
.event_handler(Handler::new(guild_id, &settings))
.intents(GatewayIntents::GUILD_PRESENCES | GatewayIntents::GUILD_MEMBERS)
.await
.unwrap_or_else(|_| panic!("{}", "Error creating client".red().to_string()));

// start client or panic
if let Err(why) = client.start().await {
panic!("{}", format!("Client error: {:?}", why).red());
}
// start client or panic
if let Err(why) = client.start().await {
panic!("{}", format!("Client error: {:?}", why).red());
}
}
16 changes: 10 additions & 6 deletions src/settings.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,21 @@
use std::{fs::File, io::{Error, Read, Write}};
use std::{
fs::File,
io::{Error, Read, Write},
};

use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize)]
pub struct Settings {
pub use_widget : bool
pub use_widget: bool,
pub include_only: Vec<u64>,
}

impl Settings {
pub fn new() -> Settings {
Settings {
use_widget : true
use_widget: true,
include_only: vec![],
}
}

Expand All @@ -22,7 +27,7 @@ impl Settings {
}

pub fn load() -> Result<Settings, Error> {
let mut file = match File::open("settings.json"){
let mut file = match File::open("settings.json") {
Ok(file) => file,
Err(_) => {
let settings = Settings::new();
Expand All @@ -35,5 +40,4 @@ impl Settings {
file.read_to_string(&mut buf)?;
Ok(serde_json::from_str(&buf)?)
}

}
}

0 comments on commit 1412627

Please sign in to comment.