guzzles data
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
use anyhow::Result;
use chrono::{DateTime, Datelike, TimeZone, Utc};
use emoji::named::*;
use poise::serenity_prelude::*;
use serenity::futures::StreamExt;
use std::fs::read_to_string;
use std::io::Write;
use std::ops::{Deref, Sub};
type Context<'a> = poise::Context<'a, (), anyhow::Error>;

#[derive(poise::ChoiceParameter, Default, Copy, Clone, Debug)]
enum Period {
    #[name = "all time"]
    #[default]
    AllTime,
    #[name = "year"]
    LastYear,
    #[name = "month"]
    LastMonth,
    #[name = "week"]
    LastWeek,
}

struct Days(usize);

impl Deref for Days {
    type Target = usize;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl Sub<usize> for Days {
    type Output = Days;

    fn sub(self, rhs: usize) -> Self::Output {
        Self(self.0 - rhs)
    }
}

impl Days {
    fn t(self) -> DateTime<Utc> {
        Utc.timestamp_millis_opt(((*self as i64 * (60 * 60 * 24) as i64) + 1420070400) * 1000)
            .single()
            .unwrap()
    }

    fn now() -> Self {
        Self::from(Utc::now().timestamp() as usize)
    }
}

impl From<usize> for Days {
    fn from(value: usize) -> Self {
        Self((value - 1420070400) / (60 * 60 * 24))
    }
}

impl Period {
    fn from(self) -> Days {
        match self {
            Self::AllTime => Days(0),
            Self::LastYear => Days::now() - 365,
            Self::LastMonth => Days::now() - 30,
            Self::LastWeek => Days::now() - 7,
        }
    }

    fn tic(self, t: Days) -> bool {
        match self {
            Self::LastYear | Self::AllTime => t.t().day() == 1,
            Self::LastMonth => t.t().day() % 7 == 0,
            Self::LastWeek => true,
        }
    }
}

#[poise::command(slash_command)]
/// graph of users over time
pub async fn users(
    c: Context<'_>,
    #[description = "time period to graph (defaults to all time)"] period: Option<Period>,
) -> Result<()> {
    c.defer().await?;
    let p = period.unwrap_or_default();
    let g = {
        let Some(g) = c.guild() else {
            _ = c.reply(format!("{CANCEL} need guild"));
            return Ok(());
        };
        g.id
    };
    let mut s = std::pin::pin!(g.members_iter(c));
    let mut data: Vec<u16> = vec![0; 365 * 12];
    let mut min = 365 * 12;
    let mut max = 0;
    while let Some(x) = s.next().await {
        let x = x?.joined_at.unwrap();
        let d = *Days::from(x.timestamp() as usize);
        min = min.min(d);
        max = max.max(d);
        data[d] += 1;
    }
    let min = min.max(*p.from());
    let mut f = std::fs::File::create("1.dat").unwrap();
    let mut sum = 0;
    for (i, &d) in data[min..max].iter().enumerate() {
        sum += d;
        writeln!(
            &mut f,
            r"{},{sum}",
            if p.tic(Days(i + min)) {
                Days(i + min).t().format("%m/%d/%y").to_string()
            } else {
                "".to_string()
            }
        )
        .unwrap();
    }
    assert!(std::process::Command::new("gnuplot")
        .arg("x.plot")
        .spawn()
        .unwrap()
        .wait()
        .unwrap()
        .success());
    assert!(std::process::Command::new("inkscape")
        .arg("--export-filename=data.png")
        .arg("data.svg")
        .spawn()
        .unwrap()
        .wait()
        .unwrap()
        .success());
    poise::send_reply(
        c,
        poise::CreateReply::default().attachment(CreateAttachment::path("data.png").await.unwrap()),
    )
    .await?;
    Ok(())
}

#[tokio::main]
async fn main() {
    let tok =
        std::env::var("TOKEN").unwrap_or_else(|_| read_to_string("token").expect("wher token"));
    let f = poise::Framework::builder()
        .options(poise::FrameworkOptions {
            commands: vec![users()],
            ..Default::default()
        })
        .setup(|ctx, _ready, f| {
            Box::pin(async move {
                poise::builtins::register_globally(ctx, &f.options().commands).await?;
                println!("registered");
                Ok(())
            })
        })
        .build();
    ClientBuilder::new(
        tok,
        GatewayIntents::non_privileged() | GatewayIntents::MESSAGE_CONTENT,
    )
    .framework(f)
    .await
    .unwrap()
    .start()
    .await
    .unwrap();
}