Skip to content
This repository has been archived by the owner on Jan 4, 2022. It is now read-only.

Commit

Permalink
add channel and guild permission calculations
Browse files Browse the repository at this point in the history
show if a user is currently banned in a server in userinfo
start of the logpump
  • Loading branch information
AEnterprise committed May 8, 2020
1 parent 937338f commit 5315a56
Show file tree
Hide file tree
Showing 14 changed files with 140 additions and 9 deletions.
1 change: 0 additions & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ chrono = "0.4"
deadpool-postgres={version = "0.5", features=["config"]}
dashmap = "3.11"
flexi_logger = { version = "0.15", default_features = false, features = ["colors", "specfile", "ziplogs"] }
futures = "0.3"
git-version = "0.3"
lazy_static = "1.4"
log = "0.4"
Expand Down
3 changes: 2 additions & 1 deletion config-DEFAULT.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,5 @@ postgres="postgres://database?user=user&password=password&host=localhost"
#No = "<:gearNo:459697272314265600>"
#Warn = "<:gearWarning:473506219919802388>"
#Info = "<:gearAE:585879894232137739>"
#Bug = "<:gearBug:585878363361640460>"
#Bug = "<:gearBug:585878363361640460>"
#Bad = "<:gearJail:585878405539561512>"
2 changes: 2 additions & 0 deletions src/commands/basic/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@ pub use about::about;
pub use coinflip::coinflip;
pub use echo::echo;
pub use ping::ping;
pub use quote::quote;

mod about;
mod coinflip;
mod echo;
mod ping;
mod quote;
9 changes: 9 additions & 0 deletions src/commands/basic/quote.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
use crate::core::Context;
use crate::parser::Parser;
use crate::CommandResult;
use std::sync::Arc;
use twilight::model::channel::Message;

pub async fn quote(ctx: Arc<Context>, msg: Message, parser: Parser) -> CommandResult {
Ok(())
}
14 changes: 14 additions & 0 deletions src/commands/moderation/userinfo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ use std::sync::Arc;
use std::time::Duration;
use twilight::builders::embed::EmbedBuilder;
use twilight::model::channel::Message;
use twilight::model::guild::Permissions;
use twilight::model::id::ChannelId;
use twilight::model::user::UserFlags;

Expand Down Expand Up @@ -183,6 +184,19 @@ pub async fn userinfo(ctx: Arc<Context>, msg: Message, mut parser: Parser) -> Co
}
}

let guild_id = msg.guild_id.unwrap();
if ctx
.bot_has_guild_permissions(guild_id, Permissions::BAN_MEMBERS)
.await
{
if ctx.http.ban(guild_id, user.id).await?.is_some() {
content += &*format!(
"{} **This user is currently banned from this server**",
Emoji::Bad.for_chat()
)
}
}

builder = builder.description(content);

ctx.http
Expand Down
2 changes: 1 addition & 1 deletion src/core/context/cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,11 @@ use aes_gcm::{
aead::{Aead, NewAead},
Aes256Gcm,
};
use futures::channel::oneshot;
use log::{debug, info, trace};
use postgres_types::Type;
use rand::{thread_rng, RngCore};
use std::sync::Arc;
use tokio::sync::oneshot;
use twilight::http::error::Error::Response;
use twilight::http::error::ResponseError::{Client, Server};
use twilight::http::error::{Error as HttpError, ResponseError};
Expand Down
14 changes: 14 additions & 0 deletions src/core/context/logpump.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
use crate::core::Context;
use crate::utils::LogType;
use chrono::Utc;

impl Context {
pub fn log(&self, guild_id: u64, log: LogType) {
match self.log_pumps.get(&guild_id) {
Some(pump) => {
pump.value().send((Utc::now(), log));
}
None => {}
};
}
}
12 changes: 8 additions & 4 deletions src/core/context/mod.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
use crate::core::context::stats::BotStats;
use crate::core::GuildConfig;
use crate::utils::LogType;
use crate::EncryptionKey;
use aes_gcm::aead::generic_array::GenericArray;
use chrono::{DateTime, Utc};
use dashmap::DashMap;
use deadpool_postgres::Pool;
use futures::channel::oneshot::Sender;
use git_version::git_version;
use std::sync::RwLock;
use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender};
use tokio::sync::oneshot::Sender;
use twilight::cache::InMemoryCache;
use twilight::gateway::Cluster;
use twilight::http::Client as HttpClient;
Expand All @@ -29,6 +32,7 @@ pub struct Context {
pub pool: Pool,
__static_master_key: Option<Vec<u8>>,
pub chunk_requests: DashMap<String, Sender<MemberChunk>>,
log_pumps: DashMap<u64, UnboundedSender<(DateTime<Utc>, LogType)>>,
}

impl Context {
Expand All @@ -52,13 +56,11 @@ impl Context {
pool,
__static_master_key: key,
chunk_requests: DashMap::new(),
log_pumps: DashMap::new(),
}
}

/// Returns if a message was sent by us.
///
/// Returns None if we couldn't currently get a lock on the cache, but
/// rarely, if ever should this happen.
pub fn is_own(&self, other: &Message) -> bool {
self.bot_user.id == other.author.id
}
Expand All @@ -75,4 +77,6 @@ impl Context {

mod cache;
mod database;
mod logpump;
mod permissions;
mod stats;
85 changes: 85 additions & 0 deletions src/core/context/permissions.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
use crate::core::Context;
use log::debug;
use std::sync::Arc;
use twilight::model::channel::permission_overwrite::PermissionOverwriteType;
use twilight::model::channel::GuildChannel;
use twilight::model::guild::Permissions;
use twilight::model::id::{ChannelId, GuildId, UserId};

impl Context {
pub async fn bot_has_guild_permissions(
&self,
guild_id: GuildId,
permissions: Permissions,
) -> bool {
self.get_bot_guild_permissions(guild_id)
.await
.contains(permissions)
}

pub async fn get_bot_guild_permissions(&self, guild_id: GuildId) -> Permissions {
self.get_guild_permissions_for(guild_id, self.bot_user.id)
.await
}

pub async fn get_guild_permissions_for(
&self,
guild_id: GuildId,
user_id: UserId,
) -> Permissions {
let mut permissions = Permissions::empty();
if let Some(member) = self.cache.member(guild_id, user_id).await.unwrap() {
for role_id in &member.roles {
if let Some(role) = self.cache.role(role_id.clone()).await.unwrap() {
permissions |= role.permissions;
}
}
};
permissions
}

pub async fn get_channel_permissions_for(
&self,
guild_id: GuildId,
user_id: UserId,
channel_id: ChannelId,
) -> Permissions {
let mut permissions = self.get_guild_permissions_for(guild_id, user_id).await;
if let Some(channel) = self.cache.guild_channel(channel_id).await.unwrap() {
if let Some(member) = self.cache.member(guild_id, user_id).await.unwrap() {
let overrides = match &*channel {
GuildChannel::Category(category) => &category.permission_overwrites,
GuildChannel::Text(channel) => &channel.permission_overwrites,
GuildChannel::Voice(channel) => &channel.permission_overwrites,
};
let mut user_allowed = Permissions::empty();
let mut user_denied = Permissions::empty();
let mut role_allowed = Permissions::empty();
let mut role_denied = Permissions::empty();
for o in overrides {
match o.kind {
PermissionOverwriteType::Member(member_id) => {
if member_id == user_id {
user_allowed |= o.allow;
user_denied |= o.deny;
}
}
PermissionOverwriteType::Role(role_id) => {
if member.roles.contains(&role_id) {
role_allowed |= o.allow;
role_denied |= o.deny;
}
}
}
}

permissions &= !role_denied;
permissions |= role_allowed;

permissions &= !user_denied;
permissions |= user_allowed;
};
};
permissions
}
}
1 change: 0 additions & 1 deletion src/core/handlers/general.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ use twilight::model::gateway::{
use crate::core::Context;
use crate::utils::Error;
use crate::{gearbot_info, gearbot_warn};
use futures::SinkExt;

pub async fn handle_event(shard_id: u64, event: &Event, ctx: Arc<Context>) -> Result<(), Error> {
match &event {
Expand Down
1 change: 1 addition & 0 deletions src/utils/emoji.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ define_emoji!(
Warn => "⚠️",
Robot => "🤖",
Bug => "🐛",
Bad => "😶",

StaffBadge => "",
PartnerBadge => "",
Expand Down
1 change: 1 addition & 0 deletions src/utils/log_types.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pub enum LogType {}
3 changes: 3 additions & 0 deletions src/utils/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ mod errors;
pub use emoji::*;
pub use errors::*;

mod log_types;
pub use log_types::*;

const MARKDOWN_REPALCEMENTS: &[&str; 7] = &["\\", "*", "_", "~", "|", "{", ">"];

fn replace_markdown(msg: &mut String) {
Expand Down

0 comments on commit 5315a56

Please sign in to comment.