Skip to content

Commit

Permalink
retrieve guild stats from serenity's cache
Browse files Browse the repository at this point in the history
  • Loading branch information
nickelc committed May 25, 2019
1 parent 316cd5a commit 179b3ae
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 47 deletions.
4 changes: 2 additions & 2 deletions src/commands/basic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ impl Command for About {
})
}

fn execute(&self, ctx: &mut Context, msg: &Message, _: Args) -> CommandResult {
fn execute(&self, _: &mut Context, msg: &Message, _: Args) -> CommandResult {
serenity::http::raw::get_current_user().and_then(|u| {
let dbl = if crate::dbl::is_dbl_enabled() {
let profile = crate::dbl::get_profile();
Expand All @@ -39,7 +39,7 @@ impl Command for About {
a
})
.footer(|f| {
let (guilds, users) = guild_stats(ctx);
let (guilds, users) = guild_stats();
f.text(format!("Servers: {} | Users: {}", guilds, users))
})
.field(
Expand Down
57 changes: 12 additions & 45 deletions src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ use std::collections::HashMap;
use std::env;
use std::env::VarError;
use std::fmt;
use std::sync::Arc;
use std::time::{SystemTime, UNIX_EPOCH};

use chrono::prelude::*;
Expand All @@ -11,9 +10,10 @@ use modio::auth::Credentials;
use modio::Modio;
use serenity::model::channel::Message;
use serenity::model::gateway::{Game, Ready};
use serenity::model::guild::{Guild, GuildStatus, PartialGuild};
use serenity::model::guild::GuildStatus;
use serenity::model::id::GuildId;
use serenity::prelude::*;
use serenity::CACHE;
use tokio::runtime::Runtime;

use crate::db::{init_db, load_settings, load_subscriptions, DbPool, Settings, Subscriptions};
Expand All @@ -24,14 +24,6 @@ use crate::{DEFAULT_MODIO_HOST, MODIO_HOST};
pub type CliResult = std::result::Result<(), Error>;
pub type Result<T> = std::result::Result<T, Error>;

type GuildStats = HashMap<GuildId, usize>;

struct GuildStatsKey;

impl TypeMapKey for GuildStatsKey {
type Value = GuildStats;
}

impl TypeMapKey for Settings {
type Value = HashMap<GuildId, Settings>;
}
Expand All @@ -50,66 +42,41 @@ pub struct Handler;

impl EventHandler for Handler {
fn ready(&self, ctx: Context, ready: Ready) {
let (settings, subs, stats) = {
let (settings, subs) = {
let data = ctx.data.lock();
let pool = data
.get::<PoolKey>()
.expect("failed to get connection pool");

let stats = ready
.guilds
.iter()
.map(|g| (g.id(), 0))
.collect::<GuildStats>();
let guilds = ready.guilds.iter().map(GuildStatus::id).collect::<Vec<_>>();
info!("Guilds: {:?}", guilds);

let settings = load_settings(&pool, &guilds).unwrap_or_default();
let subs = load_subscriptions(&pool, &guilds).unwrap_or_default();
info!("Subscriptions: {}", subs);

(settings, subs, stats)
(settings, subs)
};
let mut data = ctx.data.lock();
data.insert::<Settings>(settings);
data.insert::<Subscriptions>(subs);
data.insert::<GuildStatsKey>(stats);

let game = Game::playing(&format!("@{} help", ready.user.name));
let game = Game::playing(&format!("~help| @{} help", ready.user.name));
ctx.set_game(game);
}

fn guild_create(&self, ctx: Context, guild: Guild, _: bool) {
let mut data = ctx.data.lock();
let stats = data
.get_mut::<GuildStatsKey>()
.expect("failed to get guild stats");
stats.insert(guild.id, guild.members.len());
}

fn guild_delete(&self, ctx: Context, guild: PartialGuild, _: Option<Arc<RwLock<Guild>>>) {
let mut data = ctx.data.lock();
let stats = data
.get_mut::<GuildStatsKey>()
.expect("failed to get guild stats");
stats.remove(&guild.id);
}
}

pub fn guild_stats(ctx: &mut Context) -> (usize, usize) {
let data = ctx.data.lock();
let stats = data
.get::<GuildStatsKey>()
.expect("failed to get guild stats");

pub fn guild_stats() -> (usize, usize) {
// ignore Discord Bot List server
let dbl = GuildId(264_445_053_596_991_498);

stats
CACHE
.read()
.guilds
.iter()
.filter(|&(&id, _)| dbl != id)
.fold((0, 0), |(count, sum), (_, members)| {
(count + 1, sum + members)
.fold((0, 0), |(count, sum), (_, guild)| {
let guild = guild.read();
(count + 1, sum + guild.members.len())
})
}

Expand Down

0 comments on commit 179b3ae

Please sign in to comment.