summaryrefslogtreecommitdiff
path: root/src/main.rs
blob: a3c02225240f9e4cd5400ba0d4ba58ab148106f8 (plain)
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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
#![feature(once_cell)]

mod config;

use serenity::framework::StandardFramework;
use serenity::model::id::ChannelId;
use serenity::Client;
use std::lazy::SyncLazy;
use std::sync::{Arc, Mutex};

fn configure(conf: &mut serenity::framework::standard::Configuration) {
    conf.prefix(config::GLOBAL_COMMAND_PREFIX)
        .with_whitespace((true, true, true))
        .case_insensitivity(true);
}

struct Handler;

#[derive(Debug, Clone)]
pub enum BotError {
    MissingGuild,
}

impl std::fmt::Display for BotError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            Self::MissingGuild => write!(f, "this command is only usable in a guild"),
        }
    }
}

impl std::error::Error for BotError {}

#[derive(Debug, Clone, Default)]
pub struct ChannelCache {
    pub meta: Option<ChannelId>,
    pub lobby: Option<ChannelId>,
}

static CHANNEL_CACHE: SyncLazy<Arc<Mutex<ChannelCache>>> =
    SyncLazy::new(|| Arc::new(Mutex::new(Default::default())));

mod commands {
    use super::{ChannelCache, CHANNEL_CACHE};
    use crate::config;
    use serenity::client::Context;
    use serenity::framework::standard::{macros::*, CommandError, CommandResult};
    use serenity::model::{
        channel::{Channel, ChannelType, GuildChannel, Message},
        guild::Guild,
        id::ChannelId,
    };

    #[group]
    #[description("Commands for this bot")]
    #[commands(help, create)]
    struct Group;

    #[derive(Debug, Clone)]
    struct ChannelDescriptor<'n, 'd> {
        name: &'n str,
        description: &'d str,
        kind: ChannelType,
        parent: Option<ChannelId>,
    }

    async fn get_guild(ctx: &Context, msg: &Message) -> Result<Guild, CommandError> {
        msg.guild(&ctx.cache)
            .await
            .ok_or_else(|| Box::new(super::BotError::MissingGuild).into())
    }

    async fn create_channel_no_cache<'n, 'd>(
        ctx: &Context,
        guild: &Guild,
        desc: ChannelDescriptor<'n, 'd>,
    ) -> Result<GuildChannel, CommandError> {
        Ok(guild
            .create_channel(ctx, |c| {
                let c = c.name(desc.name).topic(desc.description).kind(desc.kind);
                if let Some(parent) = desc.parent {
                    c.category(parent)
                } else {
                    c
                }
            })
            .await?)
    }

    async fn get_guild_channel_by_optional_id(
        ctx: &Context,
        id: Option<ChannelId>,
    ) -> Option<GuildChannel> {
        match id {
            Some(id) => ctx.cache.guild_channel(id).await,
            None => None,
        }
    }

    async fn get_channel_by_optional_id(
        ctx: &Context,
        kind: ChannelType,
        id: Option<ChannelId>,
    ) -> Option<Channel> {
        match (kind, id) {
            (ChannelType::Category, Some(id)) => ctx
                .cache
                .categories()
                .await
                .get(&id)
                .cloned()
                .map(Channel::Category),
            (_, opt_id) => get_guild_channel_by_optional_id(ctx, opt_id)
                .await
                .map(Channel::Guild),
        }
    }

    async fn create_channel<'n, 'd>(
        ctx: &Context,
        guild: &Guild,
        desc: ChannelDescriptor<'n, 'd>,
    ) -> Result<Channel, CommandError> {
        let optional_channel = match desc.kind {
            ChannelType::Category => {
                println!("{:?}", ctx.cache.categories().await);
                ctx.cache.categories().await.values().find_map(|channel| {
                    if channel.name() == desc.name {
                        Some(Channel::Category(channel.clone()))
                    } else {
                        None
                    }
                })
            }
            _ => get_guild_channel_by_optional_id(
                ctx,
                guild.channel_id_from_name(&ctx.cache, desc.name).await,
            )
            .await
            .map(Channel::Guild),
        };
        match optional_channel {
            Some(channel) => Ok(channel),
            None => {
                let channel = create_channel_no_cache(ctx, guild, desc)
                    .await
                    .map(Channel::Guild);
                channel
            }
        }
    }

    async fn get_channel_or_create<'n, 'd, F: Fn(&mut ChannelCache) -> &mut Option<ChannelId>>(
        ctx: &Context,
        guild: &Guild,
        desc: ChannelDescriptor<'n, 'd>,
        f: F,
    ) -> Result<Channel, CommandError> {
        let lock = || CHANNEL_CACHE.lock().unwrap();
        Ok({
            let optional_id = *f(&mut *lock());
            match get_channel_by_optional_id(ctx, desc.kind, optional_id).await {
                Some(channel) => channel,
                None => {
                    let channel = create_channel(ctx, &guild, desc).await?;
                    *f(&mut *lock()) = Some(channel.id());
                    channel
                }
            }
        })
    }

    async fn get_meta_channel_or_create(
        ctx: &Context,
        guild: &Guild,
    ) -> Result<Channel, CommandError> {
        let desc = ChannelDescriptor {
            name: config::META_CHANNEL_NAME,
            description: config::META_CHANNEL_DESCRIPTION,
            kind: ChannelType::Category,
            parent: None,
        };
        get_channel_or_create(ctx, guild, desc, |cache| &mut cache.meta).await
    }

    async fn get_lobby_channel_or_create(
        ctx: &Context,
        guild: &Guild,
        meta_channel_id: ChannelId,
    ) -> Result<Channel, CommandError> {
        let desc = ChannelDescriptor {
            name: config::LOBBY_CHANNEL_NAME,
            description: config::LOBBY_CHANNEL_DESCRIPTION,
            kind: ChannelType::Voice,
            parent: Some(meta_channel_id),
        };
        get_channel_or_create(ctx, guild, desc, |cache| &mut cache.lobby).await
    }

    #[command]
    #[aliases("hepl", "?", "h")]
    async fn help(ctx: &Context, msg: &Message) -> CommandResult {
        msg.reply(ctx, crate::config::HELP_TEXT).await?;
        Ok(())
    }

    #[command]
    #[aliases("craete", "+", "c", "init")]
    async fn create(ctx: &Context, msg: &Message) -> CommandResult {
        let guild = get_guild(ctx, msg).await?;
        let meta_channel = get_meta_channel_or_create(ctx, &guild).await?;

        let lobby_channel = get_lobby_channel_or_create(ctx, &guild, meta_channel.id()).await?;

        Ok(())
    }

    #[command]
    #[aliases("strat", "s", "r", "run", "rnu")]
    async fn start(ctx: &Context, msg: &Message) -> CommandResult {
        let guild = get_guild(ctx, msg).await?;

        Ok(())
    }
}

impl serenity::client::EventHandler for Handler {}

#[tokio::main]
async fn main() {
    println!("crate framework");

    let framework = StandardFramework::new()
        .configure(|c| {
            configure(c);
            c
        })
        .group(&commands::GROUP_GROUP);

    let token = std::env::var(config::TOKEN_ENV).expect("missing token");
    println!("crate a new client with token: \"{}\"", token);
    let mut client = Client::new(token)
        .framework(framework)
        .event_handler(Handler)
        .await
        .expect("Error creating client");

    println!("starting the client");
    client.start().await.expect("client error");
}