Rustendo/src/util/user_util.rs

101 lines
2.9 KiB
Rust

use serenity::all::{ChannelId, Context, Guild, GuildId, PartialGuild, UserId};
use serenity::Error;
/// Get a guild by id
pub fn get_guild_cached(ctx: &Context, guild_id: &GuildId) -> Option<Guild> {
let guild = match ctx.cache.guild(guild_id) {
Some(guild) => guild,
None => {
println!("Cannot get guild with id {:?}!", guild_id);
return None;
}
};
println!("Got guild: {:?}", guild.name);
Some(guild.clone())
}
pub async fn request_guild(ctx: &Context, guild_id: &GuildId) -> Result<Guild, Error> {
let guild = match ctx.http.get_guild(*guild_id).await {
Ok(guild) => guild,
Err(error) => {
return Err(error);
}
};
Ok(guild.id.to_guild_cached(ctx).unwrap().clone())
}
/// 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 current channel id of the bot
pub fn get_vc_id_cached(ctx: &Context, guild_id: &GuildId, user_id: &UserId) -> Option<ChannelId> {
let guild = match get_guild_cached(ctx, guild_id) {
Some(guild) => guild,
None => {
println!("Cannot get guild while getting channel id!");
return None;
}
};
let channel_id = guild
.voice_states
.get(user_id)
.and_then(|voice_state| voice_state.channel_id)?;
println!("Got vc with id: {:?}", channel_id);
Some(channel_id)
}
pub async fn get_vc_id(
ctx: &Context,
guild_id: &GuildId,
user_id: &UserId,
) -> Result<ChannelId, Error> {
let guild = request_guild(ctx, guild_id).await?;
let channel_id = guild
.voice_states
.get(user_id)
.and_then(|voice_state| voice_state.channel_id)
.expect("Cannot get channel id");
Ok(channel_id)
}
/// Check if the bot is connected to a voice channel
pub fn is_self_connected_to_vc_cached(ctx: &Context, guild_id: &GuildId) -> bool {
let channel_id = get_self_vc_id_cached(ctx, guild_id);
channel_id.is_some()
}
pub async fn is_self_connected_to_vc(ctx: &Context, guild_id: &GuildId) -> bool {
let channel_id = get_self_vc_id(ctx, guild_id);
channel_id.await.is_ok()
}
/// Get the current channel id of the bot
pub fn get_self_vc_id_cached(ctx: &Context, guild_id: &GuildId) -> Option<ChannelId> {
let channel_id = get_vc_id_cached(ctx, guild_id, &ctx.cache.current_user().id)?;
Some(channel_id)
}
pub async fn get_self_vc_id(ctx: &Context, guild_id: &GuildId) -> Result<ChannelId, Error> {
let user_id = ctx.cache.current_user().id;
get_vc_id(ctx, guild_id, &user_id).await
}