use serenity::all::{ChannelId, Context, Guild, GuildId, PartialGuild, UserId, VoiceState}; use std::collections::HashMap; /// Request a guild by id, get it from cache pub fn request_guild(ctx: &Context, guild_id: &GuildId) -> Guild { match guild_id.to_guild_cached(&ctx.cache) { Some(guild) => guild.clone(), None => { panic!("Cannot get guild with id {:?}!", guild_id); } } } /// Request a guild by id, get it from Discord, not from cache, this is a partial guild #[allow(dead_code)] pub async fn request_partial_guild(ctx: &Context, guild_id: &GuildId) -> PartialGuild { match ctx.http.get_guild(*guild_id).await { Ok(guild) => guild, Err(error) => { panic!("error whilest getting guild from Discord {}", error); } } } /// Get the voice channel id of a user pub async fn get_vc_id(ctx: &Context, guild_id: &GuildId, user_id: &UserId) -> Option { let guild = request_guild(ctx, guild_id); guild .voice_states .get(user_id) .and_then(|voice_state| voice_state.channel_id) } /// Check if the bot is connected to a voice channel pub async fn is_self_connected_to_vc(ctx: &Context, guild_id: &GuildId) -> bool { get_self_vc_id(ctx, guild_id).await.is_some() } /// Check if a user is connected to a voice channel pub async fn is_user_connected_to_vc(ctx: &Context, guild_id: &GuildId, user_id: &UserId) -> bool { get_vc_id(ctx, guild_id, user_id).await.is_some() } /// Get the voice channel id of the bot pub async fn get_self_vc_id(ctx: &Context, guild_id: &GuildId) -> Option { let user_id = ctx.cache.current_user().id; get_vc_id(ctx, guild_id, &user_id).await } /// Get all voice states of a guild pub async fn get_voice_states(ctx: &Context, guild_id: &GuildId) -> HashMap { let guild = request_guild(ctx, guild_id); guild.voice_states.clone() } /// Get the amount of members in a voice channel pub async fn get_amount_of_members_in_vc( ctx: &Context, guild_id: &GuildId, channel_id: &ChannelId, ) -> usize { let voice_states = get_voice_states(ctx, guild_id).await; let amount = voice_states .iter() .filter(|(_, voice_state)| voice_state.channel_id == Some(*channel_id)) .count(); amount }