protected override void OnResume() { base.OnResume(); if (scanFragment == null) { scanFragment = new CustomScannerFragment { BottomText = learningTask.Description }; SupportFragmentManager.BeginTransaction() .Replace(Resource.Id.fragment_container, scanFragment) .Commit(); } bool needsPermission = PermissionsHandler.NeedsPermissionRequest(this); if (needsPermission) { PermissionsHandler.RequestPermissionsAsync(this); } else { scanFragment.StartScanning(OnScanResult, GetOptions()); } }
protected override void OnResume() { base.OnResume(); if (PermissionsHandler.NeedsPermissionRequest(this)) { PermissionsHandler.RequestPermissionsAsync(this); } _scanner.StartScanning(result => { if (!result.Text.Contains(":")) { return; } RunOnUiThread(() => { try { Toast.MakeText(this, "Request Scanned. Please wait.", ToastLength.Long).Show(); } catch (Exception e) { var f = e; } }); QrCodeScanCommand.Execute(result.Text); }, MobileBarcodeScanningOptions.Default); }
internal override void Init(CommandGroupBuilder cgb) { cgb.CreateCommand(Module.Prefix + "chnlfilterinv") .Alias(Module.Prefix + "cfi") .Description("Aktiviert, oder deaktiviert automatische Löschung von Einladungen in diesem Channel." + "Falls kein Channel gewählt, derzeitige Channel. Benutze ALL um alle derzeitig existierenden Channel zu wählen." + $" | `{Prefix}cfi enable #general-chat`") .Parameter("bool") .Parameter("channel", ParameterType.Optional) .Do(async e => { try { var state = PermissionHelper.ValidateBool(e.GetArg("bool")); var chanStr = e.GetArg("channel"); if (chanStr?.ToLowerInvariant().Trim() != "all") { var chan = string.IsNullOrWhiteSpace(chanStr) ? e.Channel : PermissionHelper.ValidateChannel(e.Server, chanStr); await PermissionsHandler.SetChannelFilterInvitesPermission(chan, state).ConfigureAwait(false); await e.Channel.SendMessage($"Invite Filter wurde **{(state ? "aktiviert" : "deaktiviert")}** für Channel **{chan.Name}**.") .ConfigureAwait(false); return; } //all channels foreach (var curChannel in e.Server.TextChannels) { await PermissionsHandler.SetChannelFilterInvitesPermission(curChannel, state).ConfigureAwait(false); } await e.Channel.SendMessage($"Invite Filter wurde **{(state ? "aktiviert" : "deaktiviert")}** für **ALL** Channel.") .ConfigureAwait(false); } catch (Exception ex) { await e.Channel.SendMessage($"💢 Fehler: {ex.Message}").ConfigureAwait(false); } }); cgb.CreateCommand(Module.Prefix + "srvrfilterinv") .Alias(Module.Prefix + "sfi") .Description($"Aktiviert, oder deaktiviert automatische Löschung von Einladungenauf diesem Server. | `{Prefix}sfi disable`") .Parameter("bool") .Do(async e => { try { var state = PermissionHelper.ValidateBool(e.GetArg("bool")); await PermissionsHandler.SetServerFilterInvitesPermission(e.Server, state).ConfigureAwait(false); await e.Channel.SendMessage($"Invite Filter wurde **{(state ? "aktiviert" : "deaktiviert")}** für diesen Server.") .ConfigureAwait(false); } catch (Exception ex) { await e.Channel.SendMessage($"💢 Fehler: {ex.Message}").ConfigureAwait(false); } }); }
public override void OnRequestPermissionsResult( int requestCode, string[] permissions, [GeneratedEnum] Permission[] grantResults) { PermissionsHandler.OnRequestPermissionsResult(requestCode, permissions, grantResults); Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults); base.OnRequestPermissionsResult(requestCode, permissions, grantResults); }
private void handler(AdminQueryEvent ev, string perm, bool hierarchy = false) { ServerRoles serverRoles = ((UnityEngine.GameObject)ev.Admin.GetGameObject()).GetComponent <ServerRoles>(); PermissionsHandler permissionsHandler = ServerStatic.GetPermissionsHandler(); if ((permissionsHandler.StaffAccess && serverRoles.Staff) || (permissionsHandler.ManagersAccess && serverRoles.RaEverywhere) || (permissionsHandler.BanningTeamAccess && serverRoles.RaEverywhere)) { return; } Server server = PluginManager.Manager.Server; if (hierarchy && plugin.GetConfigBool("AP_HIERARCHY_ENABLE")) { bool isHigher = true; string[] queryArgs = ev.Query.Split(' '); if (queryArgs.Length > 1) { List <Player> playerList = server.GetPlayers(""); string[] players = queryArgs[1].Split('.'); playerList = playerList.FindAll(p => { if (Array.IndexOf(players, p.PlayerId.ToString()) > -1) { return(true); } return(false); }); if (playerList.Count > 0) { foreach (Player player in playerList) { if (!checkHierarchy(ev.Admin, player)) { isHigher = false; } } } } if (!isHigher) { ev.Successful = false; ev.Handled = true; ev.Output = "Player is higher rank than you!"; } } if (!hasPerm(ev.Admin, ev.Admin.GetUserGroup().Name, perm)) { ev.Successful = false; ev.Handled = true; ev.Output = "You Don't Have Permission to do that! You require the permission " + perm + "!"; } }
public RawPrintingHTTPServer() { config = ServerConfig.load(); _url += ":" + config.port; _permissions = new PermissionsHandler(this); _home = new HomeHandler(this); _printers = new PrintersHandler(); }
public RawPrintingHTTPServer() { config = ServerConfig.load(); _permissions = new PermissionsHandler(this); _home = new HomeHandler(this); _printers = new PrintersHandler(this); _settings = new SettingsHandler(this); }
public async void SurfaceCreated(ISurfaceHolder holder) { await PermissionsHandler.RequestPermissionsAsync(); cameraAnalyzer.SetupCamera(); surfaceCreated = true; }
public static bool Prefix(PermissionsHandler __instance, ref UserGroup __result, string playerId) { if (Player.Get(playerId) != null && Player.Get(playerId).ReferenceHub.serverRoles.Group != null && __instance._groups.ContainsValue(Player.Get(playerId).ReferenceHub.serverRoles.Group)) { __result = Player.Get(playerId).ReferenceHub.serverRoles.Group; return(false); } return(true); }
public LoadedPlugin(Assembly asm, Type pluginType) { CanUseCommands = false; Enabled = false; PluginAssembly = asm; PluginInstance = (IPlugin)Activator.CreateInstance(pluginType); Details = PluginInstance.PluginDetails; PluginID = string.Format("[{0}]-[{1}]", Details.Name, pluginType.GUID.ToString("n")); Permissions = new PermissionsHandler(this){ OnException = OnException }; }
public PluginPermissionForms(PermissionsHandler _permissions) { if (_permissions == null) { this.DialogResult = DialogResult.Abort; return; } Permissions = _permissions; InitializeComponent(); this.Text = string.Format("Permissions for \"{0}\"", Permissions.Parent.Details.Name); }
public LoadedPlugin(Assembly asm, Type pluginType) { CanUseCommands = false; Enabled = false; PluginAssembly = asm; PluginInstance = (IPlugin)Activator.CreateInstance(pluginType); Details = PluginInstance.PluginDetails; PluginID = string.Format("[{0}]-[{1}]", Details.Name, pluginType.GUID.ToString("n")); Permissions = new PermissionsHandler(this) { OnException = OnException }; }
public static bool CheckPermissions(CommandSender sender, string queryZero, PlayerPermissions perm) { if (ServerStatic.IsDedicated && sender.FullPermissions) { return(true); } if (PermissionsHandler.IsPermitted(sender.Permissions, perm)) { return(true); } sender.RaReply(queryZero.ToUpper() + "#You don't have permissions to execute this command.\nMissing permission: " + perm, false, true, ""); return(false); }
bool ILabModGameConsoleQuery.Event(QueryProcessor processor, string query, bool encrypted) { ServerConsole.AddLog(query); if (PermissionsHandler.IsPermitted(processor.GetComponent <ServerRoles>().Permissions, PlayerPermissions.RoundEvents)) { if (query.Equals("dodgeball")) { dodgeball = !dodgeball; processor.GCT.SendToClient(processor.connectionToClient, "dodgeball=" + dodgeball.ToString(), "green"); return(false); } } return(true); }
internal override void Init(CommandGroupBuilder cgb) { cgb.CreateCommand(Module.Prefix + "cfi") .Alias(Module.Prefix + "channelfilterinvites") .Description("Enables or disables automatic deleting of invites on the channel." + "If no channel supplied, it will default to current one. Use ALL to apply to all existing channels at once." + "\n**Usage**: ;cfi enable #general-chat") .Parameter("bool") .Parameter("channel", ParameterType.Optional) .Do(async e => { try { var state = PermissionHelper.ValidateBool(e.GetArg("bool")); var chanStr = e.GetArg("channel"); if (chanStr?.ToLowerInvariant().Trim() != "all") { var chan = string.IsNullOrWhiteSpace(chanStr) ? e.Channel : PermissionHelper.ValidateChannel(e.Server, chanStr); PermissionsHandler.SetChannelFilterInvitesPermission(chan, state); await e.Channel.SendMessage($"Invite Filter has been **{(state ? "enabled" : "disabled")}** for **{chan.Name}** channel."); return; } //all channels foreach (var curChannel in e.Server.TextChannels) { PermissionsHandler.SetChannelFilterInvitesPermission(curChannel, state); } await e.Channel.SendMessage($"Invite Filter has been **{(state ? "enabled" : "disabled")}** for **ALL** channels."); } catch (Exception ex) { await e.Channel.SendMessage($"💢 Error: {ex.Message}"); } }); cgb.CreateCommand(Module.Prefix + "sfi") .Alias(Module.Prefix + "serverfilterinvites") .Description("Enables or disables automatic deleting of invites on the server.\n**Usage**: ;sfi disable") .Parameter("bool") .Do(async e => { try { var state = PermissionHelper.ValidateBool(e.GetArg("bool")); PermissionsHandler.SetServerFilterInvitesPermission(e.Server, state); await e.Channel.SendMessage($"Invite Filter has been **{(state ? "enabled" : "disabled")}** for this server."); } catch (Exception ex) { await e.Channel.SendMessage($"💢 Error: {ex.Message}"); } }); }
public void SetupCamera() { if (camera != null) { return; } PermissionsHandler.CheckCameraPermissions(context); OpenCamera(); if (camera == null) { return; } ApplyCameraSettings(); try { camera.SetPreviewDisplay(holder); var previewParameters = camera.GetParameters(); var previewSize = previewParameters.PreviewSize; var bitsPerPixel = ImageFormat.GetBitsPerPixel(previewParameters.PreviewFormat); int bufferSize = (previewSize.Width * previewSize.Height * bitsPerPixel) / 8; const int NUM_PREVIEW_BUFFERS = 5; for (uint i = 0; i < NUM_PREVIEW_BUFFERS; ++i) { using (var buffer = new FastJavaByteArray(bufferSize)) camera.AddCallbackBuffer(buffer); } camera.StartPreview(); camera.SetNonMarshalingPreviewCallback(cameraEventListener); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.ToString()); return; } finally { } }
public async override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Permission[] grantResults) { if (requestCode == Constants.SelectFilePermissionRequestCode) { if (grantResults.Any(r => r != Permission.Granted)) { _messagingService.Send("selectFileCameraPermissionDenied"); } await _deviceActionService.SelectFileAsync(); } else { Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults); PermissionsHandler.OnRequestPermissionsResult(requestCode, permissions, grantResults); } base.OnRequestPermissionsResult(requestCode, permissions, grantResults); }
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Android.Content.PM.Permission[] grantResults) { PermissionsImplementation.Current.OnRequestPermissionsResult(requestCode, permissions, grantResults); PermissionsHandler.OnRequestPermissionsResult(requestCode, permissions, grantResults); }
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Permission[] grantResults) { PermissionsHandler.OnRequestPermissionsResult(requestCode, permissions, grantResults); }
//AzurePush //bool IsPlayServiceAvailable() //{ // int resultCode = GoogleApiAvailability.Instance.IsGooglePlayServicesAvailable(this); // if (resultCode != ConnectionResult.Success) // { // if (GoogleApiAvailability.Instance.IsUserResolvableError(resultCode)) // Log.Debug(AzurePushSettings.DebugTag, GoogleApiAvailability.Instance.GetErrorString(resultCode)); // else // { // Log.Debug(AzurePushSettings.DebugTag, "This device is not supported"); // } // return false; // } // return true; //} //void CreateNotificationChannel() //{ // // Notification channels are new as of "Oreo". // // There is no need to create a notification channel on older versions of Android. // if (Build.VERSION.SdkInt >= BuildVersionCodes.O) // { // var channelName = AzurePushSettings.NotificationChannelName; // var channelDescription = String.Empty; // var channel = new NotificationChannel(channelName, channelName, NotificationImportance.Default) // { // Description = channelDescription // }; // var notificationManager = (NotificationManager)GetSystemService(NotificationService); // notificationManager.CreateNotificationChannel(channel); // } //} //END public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Permission[] grantResults) { PermissionsImplementation.Current.OnRequestPermissionsResult(requestCode, permissions, grantResults); PermissionsHandler.OnRequestPermissionsResult(requestCode, permissions, grantResults); base.OnRequestPermissionsResult(requestCode, permissions, grantResults); }
private void GiveHandler(AdminQueryEvent ev) { ServerRoles serverRoles = ((UnityEngine.GameObject)ev.Admin.GetGameObject()).GetComponent <ServerRoles>(); PermissionsHandler permissionsHandler = ServerStatic.GetPermissionsHandler(); if ((permissionsHandler.StaffAccess && serverRoles.Staff) || (permissionsHandler.ManagersAccess && serverRoles.RaEverywhere) || (permissionsHandler.BanningTeamAccess && serverRoles.RaEverywhere)) { return; } Server server = PluginManager.Manager.Server; if (plugin.GetConfigBool("AP_HIERARCHY_ENABLE")) { bool isHigher = true; string[] queryArgs = ev.Query.Split(' '); if (queryArgs.Length > 1) { List <Player> playerList = server.GetPlayers(""); string[] players = queryArgs[1].Split('.'); playerList = playerList.FindAll(p => { if (Array.IndexOf(players, p.PlayerId.ToString()) > -1) { return(true); } return(false); }); if (playerList.Count > 0) { foreach (Player player in playerList) { if (!checkHierarchy(ev.Admin, player)) { isHigher = false; } } } } if (!isHigher) { ev.Successful = false; ev.Handled = true; ev.Output = "Player is higher rank than you!"; } } string perm = ""; string[] args = ev.Query.Split(' '); if (args.Length != 3) { return; } int itemCode; if (!Int32.TryParse(args[args.Length - 1], out itemCode)) { return; } switch (itemCode) { case (int)ItemType.JANITOR_KEYCARD: case (int)ItemType.SCIENTIST_KEYCARD: case (int)ItemType.MAJOR_SCIENTIST_KEYCARD: case (int)ItemType.ZONE_MANAGER_KEYCARD: case (int)ItemType.GUARD_KEYCARD: case (int)ItemType.SENIOR_GUARD_KEYCARD: case (int)ItemType.CONTAINMENT_ENGINEER_KEYCARD: case (int)ItemType.MTF_LIEUTENANT_KEYCARD: case (int)ItemType.MTF_COMMANDER_KEYCARD: case (int)ItemType.FACILITY_MANAGER_KEYCARD: case (int)ItemType.CHAOS_INSURGENCY_DEVICE: case (int)ItemType.O5_LEVEL_KEYCARD: perm = "AP_RM_PLAYER_GIVE_KEYCARD"; break; case (int)ItemType.RADIO: case (int)ItemType.COM15: case (int)ItemType.MEDKIT: case (int)ItemType.FLASHLIGHT: case (int)ItemType.WEAPON_MANAGER_TABLET: case (int)ItemType.DISARMER: perm = "AP_RM_PLAYER_GIVE_TOOL"; break; case (int)ItemType.MICROHID: case (int)ItemType.E11_STANDARD_RIFLE: case (int)ItemType.P90: case (int)ItemType.MP4: case (int)ItemType.USP: case (int)ItemType.LOGICER: perm = "AP_RM_PLAYER_GIVE_WEAPON"; break; case (int)ItemType.FRAG_GRENADE: case (int)ItemType.FLASHBANG: perm = "AP_RM_PLAYER_GIVE_GRENADE"; break; case (int)ItemType.DROPPED_7: case (int)ItemType.DROPPED_9: case (int)ItemType.DROPPED_5: perm = "AP_RM_PLAYER_GIVE_AMMO"; break; case (int)ItemType.COIN: case (int)ItemType.CUP: perm = "AP_RM_PLAYER_GIVE_OTHER"; break; } if (!hasPerm(ev.Admin, ev.Admin.GetUserGroup().Name, perm)) { ev.Successful = false; ev.Handled = true; ev.Output = "You Don't Have Permission to do that! You require the permission " + perm + "!"; } }
public override void Install(ModuleManager manager) { manager.CreateCommands("", cgb => { cgb.AddCheck(PermissionChecker.Instance); commands.ForEach(cmd => cmd.Init(cgb)); cgb.CreateCommand(Prefix + "permrole") .Alias(Prefix + "pr") .Description("Sets a role which can change permissions. Or supply no parameters to find out the current one. Default one is 'Wiz Bot'.") .Parameter("role", ParameterType.Unparsed) .Do(async e => { if (string.IsNullOrWhiteSpace(e.GetArg("role"))) { await e.Channel.SendMessage($"Current permissions role is `{PermissionsHandler.GetServerPermissionsRoleName(e.Server)}`").ConfigureAwait(false); return; } var arg = e.GetArg("role"); Discord.Role role = null; try { role = PermissionHelper.ValidateRole(e.Server, arg); } catch (Exception ex) { Console.WriteLine(ex.Message); await e.Channel.SendMessage($"Role `{arg}` probably doesn't exist. Create the role with that name first.").ConfigureAwait(false); return; } PermissionsHandler.SetPermissionsRole(e.Server, role.Name); await e.Channel.SendMessage($"Role `{role.Name}` is now required in order to change permissions.").ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "rpc") .Alias(Prefix + "rolepermissionscopy") .Description($"Copies BOT PERMISSIONS (not discord permissions) from one role to another.\n**Usage**:`{Prefix}rpc Some Role ~ Some other role`") .Parameter("from_to", ParameterType.Unparsed) .Do(async e => { var arg = e.GetArg("from_to")?.Trim(); if (string.IsNullOrWhiteSpace(arg) || !arg.Contains('~')) { return; } var args = arg.Split('~').Select(a => a.Trim()).ToArray(); if (args.Length > 2) { await e.Channel.SendMessage("💢Invalid number of '~'s in the argument."); return; } try { var fromRole = PermissionHelper.ValidateRole(e.Server, args[0]); var toRole = PermissionHelper.ValidateRole(e.Server, args[1]); PermissionsHandler.CopyRolePermissions(fromRole, toRole); await e.Channel.SendMessage($"Copied permission settings from **{fromRole.Name}** to **{toRole.Name}**."); } catch (Exception ex) { await e.Channel.SendMessage($"💢{ex.Message}"); } }); cgb.CreateCommand(Prefix + "cpc") .Alias(Prefix + "channelpermissionscopy") .Description($"Copies BOT PERMISSIONS (not discord permissions) from one channel to another.\n**Usage**:`{Prefix}cpc Some Channel ~ Some other channel`") .Parameter("from_to", ParameterType.Unparsed) .Do(async e => { var arg = e.GetArg("from_to")?.Trim(); if (string.IsNullOrWhiteSpace(arg) || !arg.Contains('~')) { return; } var args = arg.Split('~').Select(a => a.Trim()).ToArray(); if (args.Length > 2) { await e.Channel.SendMessage("💢Invalid number of '~'s in the argument."); return; } try { var fromChannel = PermissionHelper.ValidateChannel(e.Server, args[0]); var toChannel = PermissionHelper.ValidateChannel(e.Server, args[1]); PermissionsHandler.CopyChannelPermissions(fromChannel, toChannel); await e.Channel.SendMessage($"Copied permission settings from **{fromChannel.Name}** to **{toChannel.Name}**."); } catch (Exception ex) { await e.Channel.SendMessage($"💢{ex.Message}"); } }); cgb.CreateCommand(Prefix + "upc") .Alias(Prefix + "userpermissionscopy") .Description($"Copies BOT PERMISSIONS (not discord permissions) from one role to another.\n**Usage**:`{Prefix}upc @SomeUser ~ @SomeOtherUser`") .Parameter("from_to", ParameterType.Unparsed) .Do(async e => { var arg = e.GetArg("from_to")?.Trim(); if (string.IsNullOrWhiteSpace(arg) || !arg.Contains('~')) { return; } var args = arg.Split('~').Select(a => a.Trim()).ToArray(); if (args.Length > 2) { await e.Channel.SendMessage("💢Invalid number of '~'s in the argument."); return; } try { var fromUser = PermissionHelper.ValidateUser(e.Server, args[0]); var toUser = PermissionHelper.ValidateUser(e.Server, args[1]); PermissionsHandler.CopyUserPermissions(fromUser, toUser); await e.Channel.SendMessage($"Copied permission settings from **{fromUser.ToString()}**to * *{toUser.ToString()}**."); } catch (Exception ex) { await e.Channel.SendMessage($"💢{ex.Message}"); } }); cgb.CreateCommand(Prefix + "verbose") .Alias(Prefix + "v") .Description("Sets whether to show when a command/module is blocked.\n**Usage**: ;verbose true") .Parameter("arg", ParameterType.Required) .Do(async e => { var arg = e.GetArg("arg"); var val = PermissionHelper.ValidateBool(arg); PermissionsHandler.SetVerbosity(e.Server, val); await e.Channel.SendMessage($"Verbosity set to {val}.").ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "serverperms") .Alias(Prefix + "sp") .Description("Shows banned permissions for this server.") .Do(async e => { var perms = PermissionsHandler.GetServerPermissions(e.Server); if (string.IsNullOrWhiteSpace(perms?.ToString())) { await e.Channel.SendMessage("No permissions set for this server.").ConfigureAwait(false); } await e.Channel.SendMessage(perms.ToString()).ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "roleperms") .Alias(Prefix + "rp") .Description("Shows banned permissions for a certain role. No argument means for everyone.\n**Usage**: ;rp AwesomeRole") .Parameter("role", ParameterType.Unparsed) .Do(async e => { var arg = e.GetArg("role"); var role = e.Server.EveryoneRole; if (!string.IsNullOrWhiteSpace(arg)) { try { role = PermissionHelper.ValidateRole(e.Server, arg); } catch (Exception ex) { await e.Channel.SendMessage("💢 Error: " + ex.Message).ConfigureAwait(false); return; } } var perms = PermissionsHandler.GetRolePermissionsById(e.Server, role.Id); if (string.IsNullOrWhiteSpace(perms?.ToString())) { await e.Channel.SendMessage($"No permissions set for **{role.Name}** role.").ConfigureAwait(false); } await e.Channel.SendMessage(perms.ToString()).ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "channelperms") .Alias(Prefix + "cp") .Description("Shows banned permissions for a certain channel. No argument means for this channel.\n**Usage**: ;cp #dev") .Parameter("channel", ParameterType.Unparsed) .Do(async e => { var arg = e.GetArg("channel"); var channel = e.Channel; if (!string.IsNullOrWhiteSpace(arg)) { try { channel = PermissionHelper.ValidateChannel(e.Server, arg); } catch (Exception ex) { await e.Channel.SendMessage("💢 Error: " + ex.Message).ConfigureAwait(false); return; } } var perms = PermissionsHandler.GetChannelPermissionsById(e.Server, channel.Id); if (string.IsNullOrWhiteSpace(perms?.ToString())) { await e.Channel.SendMessage($"No permissions set for **{channel.Name}** channel.").ConfigureAwait(false); } await e.Channel.SendMessage(perms.ToString()).ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "userperms") .Alias(Prefix + "up") .Description("Shows banned permissions for a certain user. No argument means for yourself.\n**Usage**: ;up Wizkiller96") .Parameter("user", ParameterType.Unparsed) .Do(async e => { var user = e.User; if (!string.IsNullOrWhiteSpace(e.GetArg("user"))) { try { user = PermissionHelper.ValidateUser(e.Server, e.GetArg("user")); } catch (Exception ex) { await e.Channel.SendMessage("💢 Error: " + ex.Message).ConfigureAwait(false); return; } } var perms = PermissionsHandler.GetUserPermissionsById(e.Server, user.Id); if (string.IsNullOrWhiteSpace(perms?.ToString())) { await e.Channel.SendMessage($"No permissions set for user **{user.Name}**.").ConfigureAwait(false); } await e.Channel.SendMessage(perms.ToString()).ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "sm").Alias(Prefix + "servermodule") .Parameter("module", ParameterType.Required) .Parameter("bool", ParameterType.Required) .Description("Sets a module's permission at the server level.\n**Usage**: ;sm [module_name] enable") .Do(async e => { try { var module = PermissionHelper.ValidateModule(e.GetArg("module")); var state = PermissionHelper.ValidateBool(e.GetArg("bool")); PermissionsHandler.SetServerModulePermission(e.Server, module, state); await e.Channel.SendMessage($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** on this server.").ConfigureAwait(false); } catch (ArgumentException exArg) { await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false); } catch (Exception ex) { await e.Channel.SendMessage("Something went terribly wrong - " + ex.Message).ConfigureAwait(false); } }); cgb.CreateCommand(Prefix + "sc").Alias(Prefix + "servercommand") .Parameter("command", ParameterType.Required) .Parameter("bool", ParameterType.Required) .Description("Sets a command's permission at the server level.\n**Usage**: ;sc [command_name] disable") .Do(async e => { try { var command = PermissionHelper.ValidateCommand(e.GetArg("command")); var state = PermissionHelper.ValidateBool(e.GetArg("bool")); PermissionsHandler.SetServerCommandPermission(e.Server, command, state); await e.Channel.SendMessage($"Command **{command}** has been **{(state ? "enabled" : "disabled")}** on this server.").ConfigureAwait(false); } catch (ArgumentException exArg) { await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false); } catch (Exception ex) { await e.Channel.SendMessage("Something went terribly wrong - " + ex.Message).ConfigureAwait(false); } }); cgb.CreateCommand(Prefix + "rm").Alias(Prefix + "rolemodule") .Parameter("module", ParameterType.Required) .Parameter("bool", ParameterType.Required) .Parameter("role", ParameterType.Unparsed) .Description("Sets a module's permission at the role level.\n**Usage**: ;rm [module_name] enable [role_name]") .Do(async e => { try { var module = PermissionHelper.ValidateModule(e.GetArg("module")); var state = PermissionHelper.ValidateBool(e.GetArg("bool")); if (e.GetArg("role")?.ToLower() == "all") { foreach (var role in e.Server.Roles) { PermissionsHandler.SetRoleModulePermission(role, module, state); } await e.Channel.SendMessage($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** for **ALL** roles.").ConfigureAwait(false); } else { var role = PermissionHelper.ValidateRole(e.Server, e.GetArg("role")); PermissionsHandler.SetRoleModulePermission(role, module, state); await e.Channel.SendMessage($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** for **{role.Name}** role.").ConfigureAwait(false); } } catch (ArgumentException exArg) { await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false); } catch (Exception ex) { await e.Channel.SendMessage("Something went terribly wrong - " + ex.Message).ConfigureAwait(false); } }); cgb.CreateCommand(Prefix + "rc").Alias(Prefix + "rolecommand") .Parameter("command", ParameterType.Required) .Parameter("bool", ParameterType.Required) .Parameter("role", ParameterType.Unparsed) .Description("Sets a command's permission at the role level.\n**Usage**: ;rc [command_name] disable [role_name]") .Do(async e => { try { var command = PermissionHelper.ValidateCommand(e.GetArg("command")); var state = PermissionHelper.ValidateBool(e.GetArg("bool")); if (e.GetArg("role")?.ToLower() == "all") { foreach (var role in e.Server.Roles) { PermissionsHandler.SetRoleCommandPermission(role, command, state); } await e.Channel.SendMessage($"Command **{command}** has been **{(state ? "enabled" : "disabled")}** for **ALL** roles.").ConfigureAwait(false); } else { var role = PermissionHelper.ValidateRole(e.Server, e.GetArg("role")); PermissionsHandler.SetRoleCommandPermission(role, command, state); await e.Channel.SendMessage($"Command **{command}** has been **{(state ? "enabled" : "disabled")}** for **{role.Name}** role.").ConfigureAwait(false); } } catch (ArgumentException exArg) { await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false); } catch (Exception ex) { await e.Channel.SendMessage("Something went terribly wrong - " + ex.Message).ConfigureAwait(false); } }); cgb.CreateCommand(Prefix + "cm").Alias(Prefix + "channelmodule") .Parameter("module", ParameterType.Required) .Parameter("bool", ParameterType.Required) .Parameter("channel", ParameterType.Unparsed) .Description("Sets a module's permission at the channel level.\n**Usage**: ;cm [module_name] enable [channel_name]") .Do(async e => { try { var module = PermissionHelper.ValidateModule(e.GetArg("module")); var state = PermissionHelper.ValidateBool(e.GetArg("bool")); var channelArg = e.GetArg("channel"); if (channelArg?.ToLower() == "all") { foreach (var channel in e.Server.TextChannels) { PermissionsHandler.SetChannelModulePermission(channel, module, state); } await e.Channel.SendMessage($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** on **ALL** channels.").ConfigureAwait(false); } else if (string.IsNullOrWhiteSpace(channelArg)) { PermissionsHandler.SetChannelModulePermission(e.Channel, module, state); await e.Channel.SendMessage($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** for **{e.Channel.Name}** channel.").ConfigureAwait(false); } else { var channel = PermissionHelper.ValidateChannel(e.Server, channelArg); PermissionsHandler.SetChannelModulePermission(channel, module, state); await e.Channel.SendMessage($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** for **{channel.Name}** channel.").ConfigureAwait(false); } } catch (ArgumentException exArg) { await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false); } catch (Exception ex) { await e.Channel.SendMessage("Something went terribly wrong - " + ex.Message).ConfigureAwait(false); } }); cgb.CreateCommand(Prefix + "cc").Alias(Prefix + "channelcommand") .Parameter("command", ParameterType.Required) .Parameter("bool", ParameterType.Required) .Parameter("channel", ParameterType.Unparsed) .Description("Sets a command's permission at the channel level.\n**Usage**: ;cc [command_name] enable [channel_name]") .Do(async e => { try { var command = PermissionHelper.ValidateCommand(e.GetArg("command")); var state = PermissionHelper.ValidateBool(e.GetArg("bool")); if (e.GetArg("channel")?.ToLower() == "all") { foreach (var channel in e.Server.TextChannels) { PermissionsHandler.SetChannelCommandPermission(channel, command, state); } await e.Channel.SendMessage($"Command **{command}** has been **{(state ? "enabled" : "disabled")}** on **ALL** channels.").ConfigureAwait(false); } else { var channel = PermissionHelper.ValidateChannel(e.Server, e.GetArg("channel")); PermissionsHandler.SetChannelCommandPermission(channel, command, state); await e.Channel.SendMessage($"Command **{command}** has been **{(state ? "enabled" : "disabled")}** for **{channel.Name}** channel.").ConfigureAwait(false); } } catch (ArgumentException exArg) { await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false); } catch (Exception ex) { await e.Channel.SendMessage("Something went terribly wrong - " + ex.Message).ConfigureAwait(false); } }); cgb.CreateCommand(Prefix + "um").Alias(Prefix + "usermodule") .Parameter("module", ParameterType.Required) .Parameter("bool", ParameterType.Required) .Parameter("user", ParameterType.Unparsed) .Description("Sets a module's permission at the user level.\n**Usage**: ;um [module_name] enable [user_name]") .Do(async e => { try { var module = PermissionHelper.ValidateModule(e.GetArg("module")); var state = PermissionHelper.ValidateBool(e.GetArg("bool")); var user = PermissionHelper.ValidateUser(e.Server, e.GetArg("user")); PermissionsHandler.SetUserModulePermission(user, module, state); await e.Channel.SendMessage($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** for user **{user.Name}**.").ConfigureAwait(false); } catch (ArgumentException exArg) { await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false); } catch (Exception ex) { await e.Channel.SendMessage("Something went terribly wrong - " + ex.Message).ConfigureAwait(false); } }); cgb.CreateCommand(Prefix + "uc").Alias(Prefix + "usercommand") .Parameter("command", ParameterType.Required) .Parameter("bool", ParameterType.Required) .Parameter("user", ParameterType.Unparsed) .Description("Sets a command's permission at the user level.\n**Usage**: ;uc [command_name] enable [user_name]") .Do(async e => { try { var command = PermissionHelper.ValidateCommand(e.GetArg("command")); var state = PermissionHelper.ValidateBool(e.GetArg("bool")); var user = PermissionHelper.ValidateUser(e.Server, e.GetArg("user")); PermissionsHandler.SetUserCommandPermission(user, command, state); await e.Channel.SendMessage($"Command **{command}** has been **{(state ? "enabled" : "disabled")}** for user **{user.Name}**.").ConfigureAwait(false); } catch (ArgumentException exArg) { await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false); } catch (Exception ex) { await e.Channel.SendMessage("Something went terribly wrong - " + ex.Message).ConfigureAwait(false); } }); cgb.CreateCommand(Prefix + "asm").Alias(Prefix + "allservermodules") .Parameter("bool", ParameterType.Required) .Description("Sets permissions for all modules at the server level.\n**Usage**: ;asm [enable/disable]") .Do(async e => { try { var state = PermissionHelper.ValidateBool(e.GetArg("bool")); foreach (var module in WizBot.Client.GetService <ModuleService>().Modules) { PermissionsHandler.SetServerModulePermission(e.Server, module.Name, state); } await e.Channel.SendMessage($"All modules have been **{(state ? "enabled" : "disabled")}** on this server.").ConfigureAwait(false); } catch (ArgumentException exArg) { await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false); } catch (Exception ex) { await e.Channel.SendMessage("Something went terribly wrong - " + ex.Message).ConfigureAwait(false); } }); cgb.CreateCommand(Prefix + "asc").Alias(Prefix + "allservercommands") .Parameter("module", ParameterType.Required) .Parameter("bool", ParameterType.Required) .Description("Sets permissions for all commands from a certain module at the server level.\n**Usage**: ;asc [module_name] [enable/disable]") .Do(async e => { try { var state = PermissionHelper.ValidateBool(e.GetArg("bool")); var module = PermissionHelper.ValidateModule(e.GetArg("module")); foreach (var command in WizBot.Client.GetService <CommandService>().AllCommands.Where(c => c.Category == module)) { PermissionsHandler.SetServerCommandPermission(e.Server, command.Text, state); } await e.Channel.SendMessage($"All commands from the **{module}** module have been **{(state ? "enabled" : "disabled")}** on this server.").ConfigureAwait(false); } catch (ArgumentException exArg) { await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false); } catch (Exception ex) { await e.Channel.SendMessage("Something went terribly wrong - " + ex.Message).ConfigureAwait(false); } }); cgb.CreateCommand(Prefix + "acm").Alias(Prefix + "allchannelmodules") .Parameter("bool", ParameterType.Required) .Parameter("channel", ParameterType.Unparsed) .Description("Sets permissions for all modules at the channel level.\n**Usage**: ;acm [enable/disable] [channel_name]") .Do(async e => { try { var state = PermissionHelper.ValidateBool(e.GetArg("bool")); var chArg = e.GetArg("channel"); var channel = string.IsNullOrWhiteSpace(chArg) ? e.Channel :PermissionHelper.ValidateChannel(e.Server, chArg); foreach (var module in WizBot.Client.GetService <ModuleService>().Modules) { PermissionsHandler.SetChannelModulePermission(channel, module.Name, state); } await e.Channel.SendMessage($"All modules have been **{(state ? "enabled" : "disabled")}** for **{channel.Name}** channel.").ConfigureAwait(false); } catch (ArgumentException exArg) { await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false); } catch (Exception ex) { await e.Channel.SendMessage("Something went terribly wrong - " + ex.Message).ConfigureAwait(false); } }); cgb.CreateCommand(Prefix + "acc").Alias(Prefix + "allchannelcommands") .Parameter("module", ParameterType.Required) .Parameter("bool", ParameterType.Required) .Parameter("channel", ParameterType.Unparsed) .Description("Sets permissions for all commands from a certain module at the channel level.\n**Usage**: ;acc [module_name] [enable/disable] [channel_name]") .Do(async e => { try { var state = PermissionHelper.ValidateBool(e.GetArg("bool")); var module = PermissionHelper.ValidateModule(e.GetArg("module")); var channel = PermissionHelper.ValidateChannel(e.Server, e.GetArg("channel")); foreach (var command in WizBot.Client.GetService <CommandService>().AllCommands.Where(c => c.Category == module)) { PermissionsHandler.SetChannelCommandPermission(channel, command.Text, state); } await e.Channel.SendMessage($"All commands from the **{module}** module have been **{(state ? "enabled" : "disabled")}** for **{channel.Name}** channel.").ConfigureAwait(false); } catch (ArgumentException exArg) { await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false); } catch (Exception ex) { await e.Channel.SendMessage("Something went terribly wrong - " + ex.Message).ConfigureAwait(false); } }); cgb.CreateCommand(Prefix + "arm").Alias(Prefix + "allrolemodules") .Parameter("bool", ParameterType.Required) .Parameter("role", ParameterType.Unparsed) .Description("Sets permissions for all modules at the role level.\n**Usage**: ;arm [enable/disable] [role_name]") .Do(async e => { try { var state = PermissionHelper.ValidateBool(e.GetArg("bool")); var role = PermissionHelper.ValidateRole(e.Server, e.GetArg("role")); foreach (var module in WizBot.Client.GetService <ModuleService>().Modules) { PermissionsHandler.SetRoleModulePermission(role, module.Name, state); } await e.Channel.SendMessage($"All modules have been **{(state ? "enabled" : "disabled")}** for **{role.Name}** role.").ConfigureAwait(false); } catch (ArgumentException exArg) { await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false); } catch (Exception ex) { await e.Channel.SendMessage("Something went terribly wrong - " + ex.Message).ConfigureAwait(false); } }); cgb.CreateCommand(Prefix + "arc").Alias(Prefix + "allrolecommands") .Parameter("module", ParameterType.Required) .Parameter("bool", ParameterType.Required) .Parameter("channel", ParameterType.Unparsed) .Description("Sets permissions for all commands from a certain module at the role level.\n**Usage**: ;arc [module_name] [enable/disable] [role_name]") .Do(async e => { try { var state = PermissionHelper.ValidateBool(e.GetArg("bool")); var module = PermissionHelper.ValidateModule(e.GetArg("module")); var role = PermissionHelper.ValidateRole(e.Server, e.GetArg("channel")); foreach (var command in WizBot.Client.GetService <CommandService>().AllCommands.Where(c => c.Category == module)) { PermissionsHandler.SetRoleCommandPermission(role, command.Text, state); } await e.Channel.SendMessage($"All commands from the **{module}** module have been **{(state ? "enabled" : "disabled")}** for **{role.Name}** role.").ConfigureAwait(false); } catch (ArgumentException exArg) { await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false); } catch (Exception ex) { await e.Channel.SendMessage("Something went terribly wrong - " + ex.Message).ConfigureAwait(false); } }); cgb.CreateCommand(Prefix + "ubl") .Description("Blacklists a mentioned user.\n**Usage**: ;ubl [user_mention]") .Parameter("user", ParameterType.Unparsed) .AddCheck(SimpleCheckers.OwnerOnly()) .Do(async e => { await Task.Run(async() => { if (!e.Message.MentionedUsers.Any()) { return; } var usr = e.Message.MentionedUsers.First(); WizBot.Config.UserBlacklist.Add(usr.Id); ConfigHandler.SaveConfig(); await e.Channel.SendMessage($"`Sucessfully blacklisted user {usr.Name}`").ConfigureAwait(false); }).ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "uubl") .Description($"Unblacklists a mentioned user.\n**Usage**: {Prefix}uubl [user_mention]") .Parameter("user", ParameterType.Unparsed) .AddCheck(SimpleCheckers.OwnerOnly()) .Do(async e => { await Task.Run(async() => { if (!e.Message.MentionedUsers.Any()) { return; } var usr = e.Message.MentionedUsers.First(); if (WizBot.Config.UserBlacklist.Contains(usr.Id)) { WizBot.Config.UserBlacklist.Remove(usr.Id); ConfigHandler.SaveConfig(); await e.Channel.SendMessage($"`Sucessfully unblacklisted user {usr.Name}`").ConfigureAwait(false); } else { await e.Channel.SendMessage($"`{usr.Name} was not in blacklist`").ConfigureAwait(false); } }).ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "cbl") .Description("Blacklists a mentioned channel (#general for example).\n**Usage**: ;cbl [channel_mention]") .Parameter("channel", ParameterType.Unparsed) .Do(async e => { await Task.Run(async() => { if (!e.Message.MentionedChannels.Any()) { return; } var ch = e.Message.MentionedChannels.First(); WizBot.Config.UserBlacklist.Add(ch.Id); ConfigHandler.SaveConfig(); await e.Channel.SendMessage($"`Sucessfully blacklisted channel {ch.Name}`").ConfigureAwait(false); }).ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "cubl") .Description("Unblacklists a mentioned channel (#general for example).\n**Usage**: ;cubl [channel_mention]") .Parameter("channel", ParameterType.Unparsed) .Do(async e => { await Task.Run(async() => { if (!e.Message.MentionedChannels.Any()) { return; } var ch = e.Message.MentionedChannels.First(); WizBot.Config.UserBlacklist.Remove(ch.Id); ConfigHandler.SaveConfig(); await e.Channel.SendMessage($"`Sucessfully blacklisted channel {ch.Name}`").ConfigureAwait(false); }).ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "sbl") .Description("Blacklists a server by a name or id (#general for example). **BOT OWNER ONLY**\n**Usage**: ;sbl [servername/serverid]") .Parameter("server", ParameterType.Unparsed) .AddCheck(SimpleCheckers.OwnerOnly()) .Do(async e => { await Task.Run(async() => { var arg = e.GetArg("server")?.Trim(); if (string.IsNullOrWhiteSpace(arg)) { return; } var server = WizBot.Client.Servers.FirstOrDefault(s => s.Id.ToString() == arg) ?? WizBot.Client.FindServers(arg.Trim()).FirstOrDefault(); if (server == null) { await e.Channel.SendMessage("Cannot find that server").ConfigureAwait(false); return; } var serverId = server.Id; WizBot.Config.ServerBlacklist.Add(serverId); ConfigHandler.SaveConfig(); //cleanup trivias and typeracing Modules.Games.Commands.Trivia.TriviaGame trivia; TriviaCommands.RunningTrivias.TryRemove(serverId, out trivia); TypingGame typeracer; SpeedTyping.RunningContests.TryRemove(serverId, out typeracer); await e.Channel.SendMessage($"`Sucessfully blacklisted server {server.Name}`").ConfigureAwait(false); }).ConfigureAwait(false); }); }); }
public override void Install(ModuleManager manager) { manager.CreateCommands("", cgb => { cgb.AddCheck(PermissionChecker.Instance); commands.ForEach(cmd => cmd.Init(cgb)); cgb.CreateCommand(Prefix + "permrole") .Alias(Prefix + "pr") .Description($"Sets a role which can change permissions. Or supply no parameters to find out the current one. Default one is 'Nadeko'. | `{Prefix}pr role`") .Parameter("role", ParameterType.Unparsed) .Do(async e => { if (string.IsNullOrWhiteSpace(e.GetArg("role"))) { await e.Channel.SendMessage($"Current permissions role is `{PermissionsHandler.GetServerPermissionsRoleName(e.Server)}`").ConfigureAwait(false); return; } var arg = e.GetArg("role"); Discord.Role role = null; try { role = PermissionHelper.ValidateRole(e.Server, arg); } catch (Exception ex) { Console.WriteLine(ex.Message); await e.Channel.SendMessage($"Role `{arg}` probably doesn't exist. Create the role with that name first.").ConfigureAwait(false); return; } await PermissionsHandler.SetPermissionsRole(e.Server, role.Name).ConfigureAwait(false); await e.Channel.SendMessage($"Role `{role.Name}` is now required in order to change permissions.").ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "rolepermscopy") .Alias(Prefix + "rpc") .Description($"Copies BOT PERMISSIONS (not discord permissions) from one role to another. |`{Prefix}rpc Some Role ~ Some other role`") .Parameter("from_to", ParameterType.Unparsed) .Do(async e => { var arg = e.GetArg("from_to")?.Trim(); if (string.IsNullOrWhiteSpace(arg) || !arg.Contains('~')) { return; } var args = arg.Split('~').Select(a => a.Trim()).ToArray(); if (args.Length > 2) { await e.Channel.SendMessage("💢Invalid number of '~'s in the argument.").ConfigureAwait(false); return; } try { var fromRole = PermissionHelper.ValidateRole(e.Server, args[0]); var toRole = PermissionHelper.ValidateRole(e.Server, args[1]); await PermissionsHandler.CopyRolePermissions(fromRole, toRole).ConfigureAwait(false); await e.Channel.SendMessage($"Copied permission settings from **{fromRole.Name}** to **{toRole.Name}**.").ConfigureAwait(false); } catch (Exception ex) { await e.Channel.SendMessage($"💢{ex.Message}").ConfigureAwait(false); } }); cgb.CreateCommand(Prefix + "chnlpermscopy") .Alias(Prefix + "cpc") .Description($"Copies BOT PERMISSIONS (not discord permissions) from one channel to another. |`{Prefix}cpc Some Channel ~ Some other channel`") .Parameter("from_to", ParameterType.Unparsed) .Do(async e => { var arg = e.GetArg("from_to")?.Trim(); if (string.IsNullOrWhiteSpace(arg) || !arg.Contains('~')) { return; } var args = arg.Split('~').Select(a => a.Trim()).ToArray(); if (args.Length > 2) { await e.Channel.SendMessage("💢Invalid number of '~'s in the argument."); return; } try { var fromChannel = PermissionHelper.ValidateChannel(e.Server, args[0]); var toChannel = PermissionHelper.ValidateChannel(e.Server, args[1]); await PermissionsHandler.CopyChannelPermissions(fromChannel, toChannel).ConfigureAwait(false); await e.Channel.SendMessage($"Copied permission settings from **{fromChannel.Name}** to **{toChannel.Name}**.").ConfigureAwait(false); } catch (Exception ex) { await e.Channel.SendMessage($"💢{ex.Message}"); } }); cgb.CreateCommand(Prefix + "usrpermscopy") .Alias(Prefix + "upc") .Description($"Copies BOT PERMISSIONS (not discord permissions) from one role to another. |`{Prefix}upc @SomeUser ~ @SomeOtherUser`") .Parameter("from_to", ParameterType.Unparsed) .Do(async e => { var arg = e.GetArg("from_to")?.Trim(); if (string.IsNullOrWhiteSpace(arg) || !arg.Contains('~')) { return; } var args = arg.Split('~').Select(a => a.Trim()).ToArray(); if (args.Length > 2) { await e.Channel.SendMessage("💢Invalid number of '~'s in the argument.").ConfigureAwait(false); return; } try { var fromUser = PermissionHelper.ValidateUser(e.Server, args[0]); var toUser = PermissionHelper.ValidateUser(e.Server, args[1]); await PermissionsHandler.CopyUserPermissions(fromUser, toUser).ConfigureAwait(false); await e.Channel.SendMessage($"Copied permission settings from **{fromUser.ToString()}**to * *{toUser.ToString()}**.").ConfigureAwait(false); } catch (Exception ex) { await e.Channel.SendMessage($"💢{ex.Message}"); } }); cgb.CreateCommand(Prefix + "verbose") .Alias(Prefix + "v") .Description($"Sets whether to show when a command/module is blocked. | `{Prefix}verbose true`") .Parameter("arg", ParameterType.Required) .Do(async e => { var arg = e.GetArg("arg"); var val = PermissionHelper.ValidateBool(arg); await PermissionsHandler.SetVerbosity(e.Server, val).ConfigureAwait(false); await e.Channel.SendMessage($"Verbosity set to {val}.").ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "srvrperms") .Alias(Prefix + "sp") .Description($"Shows banned permissions for this server. | `{Prefix}sp`") .Do(async e => { var perms = PermissionsHandler.GetServerPermissions(e.Server); if (string.IsNullOrWhiteSpace(perms?.ToString())) { await e.Channel.SendMessage("No permissions set for this server.").ConfigureAwait(false); } await e.Channel.SendMessage(perms.ToString()).ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "roleperms") .Alias(Prefix + "rp") .Description($"Shows banned permissions for a certain role. No argument means for everyone. | `{Prefix}rp AwesomeRole`") .Parameter("role", ParameterType.Unparsed) .Do(async e => { var arg = e.GetArg("role"); var role = e.Server.EveryoneRole; if (!string.IsNullOrWhiteSpace(arg)) { try { role = PermissionHelper.ValidateRole(e.Server, arg); } catch (Exception ex) { await e.Channel.SendMessage("💢 Error: " + ex.Message).ConfigureAwait(false); return; } } var perms = PermissionsHandler.GetRolePermissionsById(e.Server, role.Id); if (string.IsNullOrWhiteSpace(perms?.ToString())) { await e.Channel.SendMessage($"No permissions set for **{role.Name}** role.").ConfigureAwait(false); } await e.Channel.SendMessage(perms.ToString()).ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "chnlperms") .Alias(Prefix + "cp") .Description($"Shows banned permissions for a certain channel. No argument means for this channel. | `{Prefix}cp #dev`") .Parameter("channel", ParameterType.Unparsed) .Do(async e => { var arg = e.GetArg("channel"); var channel = e.Channel; if (!string.IsNullOrWhiteSpace(arg)) { try { channel = PermissionHelper.ValidateChannel(e.Server, arg); } catch (Exception ex) { await e.Channel.SendMessage("💢 Error: " + ex.Message).ConfigureAwait(false); return; } } var perms = PermissionsHandler.GetChannelPermissionsById(e.Server, channel.Id); if (string.IsNullOrWhiteSpace(perms?.ToString())) { await e.Channel.SendMessage($"No permissions set for **{channel.Name}** channel.").ConfigureAwait(false); } await e.Channel.SendMessage(perms.ToString()).ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "userperms") .Alias(Prefix + "up") .Description($"Shows banned permissions for a certain user. No argument means for yourself. | `{Prefix}up Kwoth`") .Parameter("user", ParameterType.Unparsed) .Do(async e => { var user = e.User; if (!string.IsNullOrWhiteSpace(e.GetArg("user"))) { try { user = PermissionHelper.ValidateUser(e.Server, e.GetArg("user")); } catch (Exception ex) { await e.Channel.SendMessage("💢 Error: " + ex.Message).ConfigureAwait(false); return; } } var perms = PermissionsHandler.GetUserPermissionsById(e.Server, user.Id); if (string.IsNullOrWhiteSpace(perms?.ToString())) { await e.Channel.SendMessage($"No permissions set for user **{user.Name}**.").ConfigureAwait(false); } await e.Channel.SendMessage(perms.ToString()).ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "srvrmdl") .Alias(Prefix + "sm") .Parameter("module", ParameterType.Required) .Parameter("bool", ParameterType.Required) .Description($"Sets a module's permission at the server level. | `{Prefix}sm \"module name\" enable`") .Do(async e => { try { var module = PermissionHelper.ValidateModule(e.GetArg("module")); var state = PermissionHelper.ValidateBool(e.GetArg("bool")); await PermissionsHandler.SetServerModulePermission(e.Server, module, state).ConfigureAwait(false); await e.Channel.SendMessage($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** on this server.").ConfigureAwait(false); } catch (ArgumentException exArg) { await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false); } catch (Exception ex) { await e.Channel.SendMessage("Something went terribly wrong - " + ex.Message).ConfigureAwait(false); } }); cgb.CreateCommand(Prefix + "srvrcmd").Alias(Prefix + "sc") .Parameter("command", ParameterType.Required) .Parameter("bool", ParameterType.Required) .Description($"Sets a command's permission at the server level. | `{Prefix}sc \"command name\" disable`") .Do(async e => { try { var command = PermissionHelper.ValidateCommand(e.GetArg("command")); var state = PermissionHelper.ValidateBool(e.GetArg("bool")); await PermissionsHandler.SetServerCommandPermission(e.Server, command, state).ConfigureAwait(false); await e.Channel.SendMessage($"Command **{command}** has been **{(state ? "enabled" : "disabled")}** on this server.").ConfigureAwait(false); } catch (ArgumentException exArg) { await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false); } catch (Exception ex) { await e.Channel.SendMessage("Something went terribly wrong - " + ex.Message).ConfigureAwait(false); } }); cgb.CreateCommand(Prefix + "rolemdl").Alias(Prefix + "rm") .Parameter("module", ParameterType.Required) .Parameter("bool", ParameterType.Required) .Parameter("role", ParameterType.Unparsed) .Description($"Sets a module's permission at the role level. | `{Prefix}rm \"module name\" enable MyRole`") .Do(async e => { try { var module = PermissionHelper.ValidateModule(e.GetArg("module")); var state = PermissionHelper.ValidateBool(e.GetArg("bool")); if (e.GetArg("role")?.ToLower() == "all") { foreach (var role in e.Server.Roles) { await PermissionsHandler.SetRoleModulePermission(role, module, state).ConfigureAwait(false); } await e.Channel.SendMessage($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** for **ALL** roles.").ConfigureAwait(false); } else { var role = PermissionHelper.ValidateRole(e.Server, e.GetArg("role")); await PermissionsHandler.SetRoleModulePermission(role, module, state).ConfigureAwait(false); await e.Channel.SendMessage($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** for **{role.Name}** role.").ConfigureAwait(false); } } catch (ArgumentException exArg) { await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false); } catch (Exception ex) { await e.Channel.SendMessage("Something went terribly wrong - " + ex.Message).ConfigureAwait(false); } }); cgb.CreateCommand(Prefix + "rolecmd").Alias(Prefix + "rc") .Parameter("command", ParameterType.Required) .Parameter("bool", ParameterType.Required) .Parameter("role", ParameterType.Unparsed) .Description($"Sets a command's permission at the role level. | `{Prefix}rc \"command name\" disable MyRole`") .Do(async e => { try { var command = PermissionHelper.ValidateCommand(e.GetArg("command")); var state = PermissionHelper.ValidateBool(e.GetArg("bool")); if (e.GetArg("role")?.ToLower() == "all") { foreach (var role in e.Server.Roles) { await PermissionsHandler.SetRoleCommandPermission(role, command, state).ConfigureAwait(false); } await e.Channel.SendMessage($"Command **{command}** has been **{(state ? "enabled" : "disabled")}** for **ALL** roles.").ConfigureAwait(false); } else { var role = PermissionHelper.ValidateRole(e.Server, e.GetArg("role")); await PermissionsHandler.SetRoleCommandPermission(role, command, state).ConfigureAwait(false); await e.Channel.SendMessage($"Command **{command}** has been **{(state ? "enabled" : "disabled")}** for **{role.Name}** role.").ConfigureAwait(false); } } catch (ArgumentException exArg) { await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false); } catch (Exception ex) { await e.Channel.SendMessage("Something went terribly wrong - " + ex.Message).ConfigureAwait(false); } }); cgb.CreateCommand(Prefix + "chnlmdl").Alias(Prefix + "cm") .Parameter("module", ParameterType.Required) .Parameter("bool", ParameterType.Required) .Parameter("channel", ParameterType.Unparsed) .Description($"Sets a module's permission at the channel level. | `{Prefix}cm \"module name\" enable SomeChannel`") .Do(async e => { try { var module = PermissionHelper.ValidateModule(e.GetArg("module")); var state = PermissionHelper.ValidateBool(e.GetArg("bool")); var channelArg = e.GetArg("channel"); if (channelArg?.ToLower() == "all") { foreach (var channel in e.Server.TextChannels) { await PermissionsHandler.SetChannelModulePermission(channel, module, state).ConfigureAwait(false); } await e.Channel.SendMessage($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** on **ALL** channels.").ConfigureAwait(false); } else if (string.IsNullOrWhiteSpace(channelArg)) { await PermissionsHandler.SetChannelModulePermission(e.Channel, module, state).ConfigureAwait(false); await e.Channel.SendMessage($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** for **{e.Channel.Name}** channel.").ConfigureAwait(false); } else { var channel = PermissionHelper.ValidateChannel(e.Server, channelArg); await PermissionsHandler.SetChannelModulePermission(channel, module, state).ConfigureAwait(false); await e.Channel.SendMessage($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** for **{channel.Name}** channel.").ConfigureAwait(false); } } catch (ArgumentException exArg) { await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false); } catch (Exception ex) { await e.Channel.SendMessage("Something went terribly wrong - " + ex.Message).ConfigureAwait(false); } }); cgb.CreateCommand(Prefix + "chnlcmd").Alias(Prefix + "cc") .Parameter("command", ParameterType.Required) .Parameter("bool", ParameterType.Required) .Parameter("channel", ParameterType.Unparsed) .Description($"Sets a command's permission at the channel level. | `{Prefix}cc \"command name\" enable SomeChannel`") .Do(async e => { try { var command = PermissionHelper.ValidateCommand(e.GetArg("command")); var state = PermissionHelper.ValidateBool(e.GetArg("bool")); if (e.GetArg("channel")?.ToLower() == "all") { foreach (var channel in e.Server.TextChannels) { await PermissionsHandler.SetChannelCommandPermission(channel, command, state).ConfigureAwait(false); } await e.Channel.SendMessage($"Command **{command}** has been **{(state ? "enabled" : "disabled")}** on **ALL** channels.").ConfigureAwait(false); } else { var channel = PermissionHelper.ValidateChannel(e.Server, e.GetArg("channel")); await PermissionsHandler.SetChannelCommandPermission(channel, command, state).ConfigureAwait(false); await e.Channel.SendMessage($"Command **{command}** has been **{(state ? "enabled" : "disabled")}** for **{channel.Name}** channel.").ConfigureAwait(false); } } catch (ArgumentException exArg) { await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false); } catch (Exception ex) { await e.Channel.SendMessage("Something went terribly wrong - " + ex.Message).ConfigureAwait(false); } }); cgb.CreateCommand(Prefix + "usrmdl").Alias(Prefix + "um") .Parameter("module", ParameterType.Required) .Parameter("bool", ParameterType.Required) .Parameter("user", ParameterType.Unparsed) .Description($"Sets a module's permission at the user level. | `{Prefix}um \"module name\" enable SomeUsername`") .Do(async e => { try { var module = PermissionHelper.ValidateModule(e.GetArg("module")); var state = PermissionHelper.ValidateBool(e.GetArg("bool")); var user = PermissionHelper.ValidateUser(e.Server, e.GetArg("user")); await PermissionsHandler.SetUserModulePermission(user, module, state).ConfigureAwait(false); await e.Channel.SendMessage($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** for user **{user.Name}**.").ConfigureAwait(false); } catch (ArgumentException exArg) { await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false); } catch (Exception ex) { await e.Channel.SendMessage("Something went terribly wrong - " + ex.Message).ConfigureAwait(false); } }); cgb.CreateCommand(Prefix + "usrcmd").Alias(Prefix + "uc") .Parameter("command", ParameterType.Required) .Parameter("bool", ParameterType.Required) .Parameter("user", ParameterType.Unparsed) .Description($"Sets a command's permission at the user level. | `{Prefix}uc \"command name\" enable SomeUsername`") .Do(async e => { try { var command = PermissionHelper.ValidateCommand(e.GetArg("command")); var state = PermissionHelper.ValidateBool(e.GetArg("bool")); var user = PermissionHelper.ValidateUser(e.Server, e.GetArg("user")); await PermissionsHandler.SetUserCommandPermission(user, command, state).ConfigureAwait(false); await e.Channel.SendMessage($"Command **{command}** has been **{(state ? "enabled" : "disabled")}** for user **{user.Name}**.").ConfigureAwait(false); } catch (ArgumentException exArg) { await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false); } catch (Exception ex) { await e.Channel.SendMessage("Something went terribly wrong - " + ex.Message).ConfigureAwait(false); } }); cgb.CreateCommand(Prefix + "allsrvrmdls").Alias(Prefix + "asm") .Parameter("bool", ParameterType.Required) .Description($"Sets permissions for all modules at the server level. | `{Prefix}asm [enable/disable]`") .Do(async e => { try { var state = PermissionHelper.ValidateBool(e.GetArg("bool")); foreach (var module in NadekoBot.Client.GetService <ModuleService>().Modules) { await PermissionsHandler.SetServerModulePermission(e.Server, module.Name, state).ConfigureAwait(false); } await e.Channel.SendMessage($"All modules have been **{(state ? "enabled" : "disabled")}** on this server.").ConfigureAwait(false); } catch (ArgumentException exArg) { await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false); } catch (Exception ex) { await e.Channel.SendMessage("Something went terribly wrong - " + ex.Message).ConfigureAwait(false); } }); cgb.CreateCommand(Prefix + "allsrvrcmds").Alias(Prefix + "asc") .Parameter("module", ParameterType.Required) .Parameter("bool", ParameterType.Required) .Description($"Sets permissions for all commands from a certain module at the server level. | `{Prefix}asc \"module name\" [enable/disable]`") .Do(async e => { try { var state = PermissionHelper.ValidateBool(e.GetArg("bool")); var module = PermissionHelper.ValidateModule(e.GetArg("module")); foreach (var command in NadekoBot.Client.GetService <CommandService>().AllCommands.Where(c => c.Category == module)) { await PermissionsHandler.SetServerCommandPermission(e.Server, command.Text, state).ConfigureAwait(false); } await e.Channel.SendMessage($"All commands from the **{module}** module have been **{(state ? "enabled" : "disabled")}** on this server.").ConfigureAwait(false); } catch (ArgumentException exArg) { await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false); } catch (Exception ex) { await e.Channel.SendMessage("Something went terribly wrong - " + ex.Message).ConfigureAwait(false); } }); cgb.CreateCommand(Prefix + "allchnlmdls").Alias(Prefix + "acm") .Parameter("bool", ParameterType.Required) .Parameter("channel", ParameterType.Unparsed) .Description($"Sets permissions for all modules at the channel level. | `{Prefix}acm [enable/disable] SomeChannel`") .Do(async e => { try { var state = PermissionHelper.ValidateBool(e.GetArg("bool")); var chArg = e.GetArg("channel"); var channel = string.IsNullOrWhiteSpace(chArg) ? e.Channel : PermissionHelper.ValidateChannel(e.Server, chArg); foreach (var module in NadekoBot.Client.GetService <ModuleService>().Modules) { await PermissionsHandler.SetChannelModulePermission(channel, module.Name, state).ConfigureAwait(false); } await e.Channel.SendMessage($"All modules have been **{(state ? "enabled" : "disabled")}** for **{channel.Name}** channel.").ConfigureAwait(false); } catch (ArgumentException exArg) { await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false); } catch (Exception ex) { await e.Channel.SendMessage("Something went terribly wrong - " + ex.Message).ConfigureAwait(false); } }); cgb.CreateCommand(Prefix + "allchnlcmds").Alias(Prefix + "acc") .Parameter("module", ParameterType.Required) .Parameter("bool", ParameterType.Required) .Parameter("channel", ParameterType.Unparsed) .Description($"Sets permissions for all commands from a certain module at the channel level. | `{Prefix}acc \"module name\" [enable/disable] SomeChannel`") .Do(async e => { try { var state = PermissionHelper.ValidateBool(e.GetArg("bool")); var module = PermissionHelper.ValidateModule(e.GetArg("module")); var channel = PermissionHelper.ValidateChannel(e.Server, e.GetArg("channel")); foreach (var command in NadekoBot.Client.GetService <CommandService>().AllCommands.Where(c => c.Category == module)) { await PermissionsHandler.SetChannelCommandPermission(channel, command.Text, state).ConfigureAwait(false); } await e.Channel.SendMessage($"All commands from the **{module}** module have been **{(state ? "enabled" : "disabled")}** for **{channel.Name}** channel.").ConfigureAwait(false); } catch (ArgumentException exArg) { await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false); } catch (Exception ex) { await e.Channel.SendMessage("Something went terribly wrong - " + ex.Message).ConfigureAwait(false); } }); cgb.CreateCommand(Prefix + "allrolemdls").Alias(Prefix + "arm") .Parameter("bool", ParameterType.Required) .Parameter("role", ParameterType.Unparsed) .Description($"Sets permissions for all modules at the role level. | `{Prefix}arm [enable/disable] MyRole`") .Do(async e => { try { var state = PermissionHelper.ValidateBool(e.GetArg("bool")); var role = PermissionHelper.ValidateRole(e.Server, e.GetArg("role")); foreach (var module in NadekoBot.Client.GetService <ModuleService>().Modules) { await PermissionsHandler.SetRoleModulePermission(role, module.Name, state).ConfigureAwait(false); } await e.Channel.SendMessage($"All modules have been **{(state ? "enabled" : "disabled")}** for **{role.Name}** role.").ConfigureAwait(false); } catch (ArgumentException exArg) { await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false); } catch (Exception ex) { await e.Channel.SendMessage("Something went terribly wrong - " + ex.Message).ConfigureAwait(false); } }); cgb.CreateCommand(Prefix + "allrolecmds").Alias(Prefix + "arc") .Parameter("module", ParameterType.Required) .Parameter("bool", ParameterType.Required) .Parameter("role", ParameterType.Unparsed) .Description($"Sets permissions for all commands from a certain module at the role level. | `{Prefix}arc \"module name\" [enable/disable] MyRole`") .Do(async e => { try { var state = PermissionHelper.ValidateBool(e.GetArg("bool")); var module = PermissionHelper.ValidateModule(e.GetArg("module")); if (e.GetArg("role")?.ToLower() == "all") { foreach (var role in e.Server.Roles) { foreach (var command in NadekoBot.Client.GetService <CommandService>().AllCommands.Where(c => c.Category == module)) { await PermissionsHandler.SetRoleCommandPermission(role, command.Text, state).ConfigureAwait(false); } } await e.Channel.SendMessage($"All commands from the **{module}** module have been **{(state ? "enabled" : "disabled")}** for **all roles** role.").ConfigureAwait(false); } else { var role = PermissionHelper.ValidateRole(e.Server, e.GetArg("role")); foreach (var command in NadekoBot.Client.GetService <CommandService>().AllCommands.Where(c => c.Category == module)) { await PermissionsHandler.SetRoleCommandPermission(role, command.Text, state).ConfigureAwait(false); } await e.Channel.SendMessage($"All commands from the **{module}** module have been **{(state ? "enabled" : "disabled")}** for **{role.Name}** role.").ConfigureAwait(false); } } catch (ArgumentException exArg) { await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false); } catch (Exception ex) { await e.Channel.SendMessage("Something went terribly wrong - " + ex.Message).ConfigureAwait(false); } }); cgb.CreateCommand(Prefix + "ubl") .Description($"Blacklists a mentioned user. **Bot Owner Only!**| `{Prefix}ubl [user_mention]`") .Parameter("user", ParameterType.Unparsed) .AddCheck(SimpleCheckers.OwnerOnly()) .Do(async e => { await Task.Run(async() => { if (!e.Message.MentionedUsers.Any()) { return; } var usr = e.Message.MentionedUsers.First(); NadekoBot.Config.UserBlacklist.Add(usr.Id); await ConfigHandler.SaveConfig().ConfigureAwait(false); await e.Channel.SendMessage($"`Sucessfully blacklisted user {usr.Name}`").ConfigureAwait(false); }).ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "uubl") .Description($"Unblacklists a mentioned user. **Bot Owner Only!** | `{Prefix}uubl [user_mention]`") .Parameter("user", ParameterType.Unparsed) .AddCheck(SimpleCheckers.OwnerOnly()) .Do(async e => { await Task.Run(async() => { if (!e.Message.MentionedUsers.Any()) { return; } var usr = e.Message.MentionedUsers.First(); if (NadekoBot.Config.UserBlacklist.Contains(usr.Id)) { NadekoBot.Config.UserBlacklist.Remove(usr.Id); await ConfigHandler.SaveConfig().ConfigureAwait(false); await e.Channel.SendMessage($"`Sucessfully unblacklisted user {usr.Name}`").ConfigureAwait(false); } else { await e.Channel.SendMessage($"`{usr.Name} was not in blacklist`").ConfigureAwait(false); } }).ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "cbl") .Description($"Blacklists a mentioned channel (#general for example). | `{Prefix}cbl #some_channel`") .Parameter("channel", ParameterType.Unparsed) .Do(async e => { await Task.Run(async() => { if (!e.Message.MentionedChannels.Any()) { return; } var ch = e.Message.MentionedChannels.First(); NadekoBot.Config.ChannelBlacklist.Add(ch.Id); await ConfigHandler.SaveConfig().ConfigureAwait(false); await e.Channel.SendMessage($"`Sucessfully blacklisted channel {ch.Name}`").ConfigureAwait(false); }).ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "cubl") .Description($"Unblacklists a mentioned channel (#general for example). | `{Prefix}cubl #some_channel`") .Parameter("channel", ParameterType.Unparsed) .Do(async e => { await Task.Run(async() => { if (!e.Message.MentionedChannels.Any()) { return; } var ch = e.Message.MentionedChannels.First(); if (NadekoBot.Config.ChannelBlacklist.Contains(ch.Id)) { NadekoBot.Config.ChannelBlacklist.Remove(ch.Id); await ConfigHandler.SaveConfig().ConfigureAwait(false); await e.Channel.SendMessage($"`Sucessfully unblacklisted channel {ch.Name}`").ConfigureAwait(false); } else { await e.Channel.SendMessage($"`{ch.Name} was not in blacklist`").ConfigureAwait(false); } }).ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "sbl") .Description($"Blacklists a server by a name or id (#general for example). **BOT OWNER ONLY** | `{Prefix}sbl [servername/serverid]`") .Parameter("server", ParameterType.Unparsed) .AddCheck(SimpleCheckers.OwnerOnly()) .Do(async e => { await Task.Run(async() => { var arg = e.GetArg("server")?.Trim(); if (string.IsNullOrWhiteSpace(arg)) { return; } var server = NadekoBot.Client.Servers.FirstOrDefault(s => s.Id.ToString() == arg) ?? NadekoBot.Client.FindServers(arg.Trim()).FirstOrDefault(); if (server == null) { await e.Channel.SendMessage("Cannot find that server").ConfigureAwait(false); return; } var serverId = server.Id; NadekoBot.Config.ServerBlacklist.Add(serverId); await ConfigHandler.SaveConfig().ConfigureAwait(false); //cleanup trivias and typeracing await e.Channel.SendMessage($"`Sucessfully blacklisted server {server.Name}`").ConfigureAwait(false); }).ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "cmdcooldown") .Alias(Prefix + "cmdcd") .Description($"Sets a cooldown per user for a command. Set 0 to clear. **Needs Manager Messages Permissions**| `{Prefix}cmdcd \"some cmd\" 5`") .Parameter("command", ParameterType.Required) .Parameter("secs", ParameterType.Required) .AddCheck(SimpleCheckers.ManageMessages()) .Do(async e => { try { var command = PermissionHelper.ValidateCommand(e.GetArg("command")); var secsStr = e.GetArg("secs").Trim(); int secs; if (!int.TryParse(secsStr, out secs) || secs < 0 || secs > 3600) { throw new ArgumentOutOfRangeException("secs", "Invalid second parameter. (Must be a number between 0 and 3600)"); } await PermissionsHandler.SetCommandCooldown(e.Server, command, secs).ConfigureAwait(false); if (secs == 0) { await e.Channel.SendMessage($"Command **{command}** has no coooldown now.").ConfigureAwait(false); } else { await e.Channel.SendMessage($"Command **{command}** now has a **{secs} {(secs==1 ? "second" : "seconds")}** cooldown.").ConfigureAwait(false); } } catch (ArgumentException exArg) { await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false); } catch (Exception ex) { await e.Channel.SendMessage("Something went terribly wrong - " + ex.Message).ConfigureAwait(false); } }); cgb.CreateCommand(Prefix + "allcmdcooldowns") .Alias(Prefix + "acmdcds") .Description($"Shows a list of all commands and their respective cooldowns. | `{Prefix}acmdcds`") .Do(async e => { ServerPermissions perms; PermissionsHandler.PermissionsDict.TryGetValue(e.Server.Id, out perms); if (perms == null) { return; } if (!perms.CommandCooldowns.Any()) { await e.Channel.SendMessage("`No command cooldowns set.`").ConfigureAwait(false); return; } await e.Channel.SendMessage(SearchHelper.ShowInPrettyCode(perms.CommandCooldowns.Select(c => c.Key + ": " + c.Value + " secs"), s => $"{s,-30}", 2)).ConfigureAwait(false); }); }); }
private static bool Prefix(PlayerStats __instance, out bool __result, PlayerStats.HitInfo info, GameObject go, bool noTeamDamage = false, bool IsValidDamage = true) { try { __result = false; var player = go?.GetPlayer(); var killer = __instance?.GetPlayer(); if (player == null) { return(false); } if (info.GetDamageType() == DamageTypes.Grenade) { killer = SynapseController.Server.GetPlayer(info.PlayerId); } else if (info.GetDamageType() == DamageTypes.Pocket) { killer = Server.Get.Players.FirstOrDefault(x => x.Scp106Controller.PocketPlayers.Contains(player)); if (SynapseExtensions.CanNotHurtByScp(player)) { return(false); } } bool flag = false; bool flag2 = false; bool flag3 = go == null; ReferenceHub referenceHub = flag3 ? null : ReferenceHub.GetHub(go); if (info.Amount < 0f) { if (flag3) { info.Amount = Mathf.Abs(999999f); } else { info.Amount = ((referenceHub.playerStats != null) ? Mathf.Abs(referenceHub.playerStats.Health + referenceHub.playerStats.syncArtificialHealth + 10f) : Mathf.Abs(999999f)); } } if (__instance._burned.Enabled) { info.Amount *= __instance._burned.DamageMult; } if (info.Amount > 2.14748365E+09f) { info.Amount = 2.14748365E+09f; } if (info.GetDamageType().isWeapon&& referenceHub.characterClassManager.IsAnyScp() && info.GetDamageType() != DamageTypes.MicroHid) { info.Amount *= __instance.weaponManager.weapons[(int)__instance.weaponManager.curWeapon].scpDamageMultiplier; } if (flag3) { __result = false; return(false); } PlayerStats playerStats = referenceHub.playerStats; CharacterClassManager characterClassManager = referenceHub.characterClassManager; if (playerStats == null || characterClassManager == null) { __result = false; return(false); } if (characterClassManager.GodMode) { __result = false; return(false); } if (__instance.ccm.CurRole.team == Team.SCP && __instance.ccm.Classes.SafeGet(characterClassManager.CurClass).team == Team.SCP && __instance.ccm != characterClassManager) { __result = false; return(false); } if (characterClassManager.SpawnProtected && !__instance._allowSPDmg) { __result = false; return(false); } bool flag4 = !noTeamDamage && info.IsPlayer && referenceHub != info.RHub && referenceHub.characterClassManager.Fraction == info.RHub.characterClassManager.Fraction; if (flag4) { info.Amount *= PlayerStats.FriendlyFireFactor; } float health = playerStats.Health; if (__instance.lastHitInfo.Attacker == "ARTIFICIALDEGEN") { playerStats.unsyncedArtificialHealth -= info.Amount; if (playerStats.unsyncedArtificialHealth < 0f) { playerStats.unsyncedArtificialHealth = 0f; } } else { var allow = true; try { Server.Get.Events.Player.InvokePlayerDamageEvent(player, killer, ref info, out allow); } catch (Exception e) { SynapseController.Server.Logger.Error($"Synapse-Event: PlayerDamage Event failed!!\n{e}\nStackTrace:\n{e.StackTrace}"); } if (!allow) { __result = false; return(false); } if (playerStats.unsyncedArtificialHealth > 0f) { float num = info.Amount * playerStats.artificialNormalRatio; float num2 = info.Amount - num; playerStats.unsyncedArtificialHealth -= num; if (playerStats.unsyncedArtificialHealth < 0f) { num2 += Mathf.Abs(playerStats.unsyncedArtificialHealth); playerStats.unsyncedArtificialHealth = 0f; } playerStats.Health -= num2; if (playerStats.Health > 0f && playerStats.Health - num <= 0f && characterClassManager.CurRole.team != Team.SCP) { __instance.TargetAchieve(characterClassManager.connectionToClient, "didntevenfeelthat"); } } else { playerStats.Health -= info.Amount; } if (playerStats.Health < 0f) { playerStats.Health = 0f; } playerStats.lastHitInfo = info; } PlayableScpsController component = go.GetComponent <PlayableScpsController>(); if (component != null && (object)component.CurrentScp is PlayableScps.Interfaces.IDamagable damagable) { damagable.OnDamage(info); } if (playerStats.Health < 1f && characterClassManager.CurClass != RoleType.Spectator) { if (component != null && (object)component.CurrentScp is PlayableScps.Interfaces.IImmortalScp immortalScp && !immortalScp.OnDeath(info, __instance.gameObject)) { __result = false; return(false); } foreach (Scp079PlayerScript scp079PlayerScript in Scp079PlayerScript.instances) { Scp079Interactable.ZoneAndRoom otherRoom = go.GetComponent <Scp079PlayerScript>().GetOtherRoom(); bool flag5 = false; foreach (Scp079Interaction scp079Interaction in scp079PlayerScript.ReturnRecentHistory(12f, __instance._filters)) { foreach (Scp079Interactable.ZoneAndRoom zoneAndRoom in scp079Interaction.interactable.currentZonesAndRooms) { if (zoneAndRoom.currentZone == otherRoom.currentZone && zoneAndRoom.currentRoom == otherRoom.currentRoom) { flag5 = true; } } } if (flag5) { scp079PlayerScript.RpcGainExp(ExpGainType.KillAssist, characterClassManager.CurClass); } } if (RoundSummary.RoundInProgress() && RoundSummary.roundTime < 60 && IsValidDamage) { __instance.TargetAchieve(characterClassManager.connectionToClient, "wowreally"); } if (__instance.isLocalPlayer && info.PlayerId != referenceHub.queryProcessor.PlayerId) { RoundSummary.Kills++; } flag = true; if (characterClassManager.CurClass == RoleType.Scp096) { ReferenceHub hub = ReferenceHub.GetHub(go); if (hub != null && hub.scpsController.CurrentScp is PlayableScps.Scp096 && (hub.scpsController.CurrentScp as PlayableScps.Scp096).PlayerState == PlayableScps.Scp096PlayerState.Enraging) { __instance.TargetAchieve(characterClassManager.connectionToClient, "unvoluntaryragequit"); } } else if (info.GetDamageType() == DamageTypes.Pocket) { __instance.TargetAchieve(characterClassManager.connectionToClient, "newb"); } else if (info.GetDamageType() == DamageTypes.Scp173) { __instance.TargetAchieve(characterClassManager.connectionToClient, "firsttime"); } else if (info.GetDamageType() == DamageTypes.Grenade && info.PlayerId == referenceHub.queryProcessor.PlayerId) { __instance.TargetAchieve(characterClassManager.connectionToClient, "iwanttobearocket"); } else if (info.GetDamageType().isWeapon) { Inventory inventory = referenceHub.inventory; if (characterClassManager.CurClass == RoleType.Scientist) { Item itemByID = inventory.GetItemByID(inventory.curItem); if (itemByID != null && itemByID.itemCategory == ItemCategory.Keycard && __instance.GetComponent <CharacterClassManager>().CurClass == RoleType.ClassD) { __instance.TargetAchieve(__instance.connectionToClient, "betrayal"); } } if (Time.realtimeSinceStartup - __instance._killStreakTime > 30f || __instance._killStreak == 0) { __instance._killStreak = 0; __instance._killStreakTime = Time.realtimeSinceStartup; } if (__instance.GetComponent <WeaponManager>().GetShootPermission(characterClassManager, true)) { __instance._killStreak++; } if (__instance._killStreak >= 5) { __instance.TargetAchieve(__instance.connectionToClient, "pewpew"); } if ((__instance.ccm.CurRole.team == Team.MTF || __instance.ccm.Classes.SafeGet(__instance.ccm.CurClass).team == Team.RSC) && characterClassManager.CurClass == RoleType.ClassD) { __instance.TargetStats(__instance.connectionToClient, "dboys_killed", "justresources", 50); } } else if (__instance.ccm.CurRole.team == Team.SCP && go.GetComponent <MicroHID>().CurrentHidState != MicroHID.MicroHidState.Idle) { __instance.TargetAchieve(__instance.connectionToClient, "illpassthanks"); } if (player.RealTeam == Team.RSC && player.RealTeam == Team.SCP) { __instance.TargetAchieve(__instance.connectionToClient, "timetodoitmyself"); } bool flag6 = info.IsPlayer && referenceHub == info.RHub; flag2 = flag4; if (flag6) { ServerLogs.AddLog(ServerLogs.Modules.ClassChange, string.Concat(new string[] { referenceHub.LoggedNameFromRefHub(), " playing as ", referenceHub.characterClassManager.CurRole.fullName, " committed a suicide using ", info.GetDamageName(), "." }), ServerLogs.ServerLogType.Suicide, false); } else { ServerLogs.AddLog(ServerLogs.Modules.ClassChange, string.Concat(new string[] { referenceHub.LoggedNameFromRefHub(), " playing as ", referenceHub.characterClassManager.CurRole.fullName, " has been killed by ", info.Attacker, " using ", info.GetDamageName(), info.IsPlayer ? (" playing as " + info.RHub.characterClassManager.CurRole.fullName + ".") : "." }), flag2 ? ServerLogs.ServerLogType.Teamkill : ServerLogs.ServerLogType.KillLog, false); } if (info.GetDamageType().isScp || info.GetDamageType() == DamageTypes.Pocket) { RoundSummary.kills_by_scp++; } else if (info.GetDamageType() == DamageTypes.Grenade) { RoundSummary.kills_by_frag++; } try { Server.Get.Events.Player.InvokePlayerDeathEvent(player, killer, info); } catch (Exception e) { SynapseController.Server.Logger.Error($"Synapse-Event: PlayerDeath Event failed!!\n{e}\nStackTrace:\n{e.StackTrace}"); } if (!__instance._pocketCleanup || info.GetDamageType() != DamageTypes.Pocket) { referenceHub.inventory.ServerDropAll(); PlayerMovementSync playerMovementSync = referenceHub.playerMovementSync; if (characterClassManager.Classes.CheckBounds(characterClassManager.CurClass) && info.GetDamageType() != DamageTypes.RagdollLess) { __instance.GetComponent <RagdollManager>().SpawnRagdoll(go.transform.position, go.transform.rotation, (playerMovementSync == null) ? Vector3.zero : playerMovementSync.PlayerVelocity, (int)characterClassManager.CurClass, info, characterClassManager.CurRole.team > Team.SCP, go.GetComponent <Dissonance.Integrations.MirrorIgnorance.MirrorIgnorancePlayer>().PlayerId, referenceHub.nicknameSync.DisplayName, referenceHub.queryProcessor.PlayerId); } } else { referenceHub.inventory.Clear(); } characterClassManager.NetworkDeathPosition = go.transform.position; if (characterClassManager.CurRole.team == Team.SCP) { if (characterClassManager.CurClass == RoleType.Scp0492) { NineTailedFoxAnnouncer.CheckForZombies(go); } else { GameObject x = null; foreach (GameObject gameObject in PlayerManager.players) { if (gameObject.GetComponent <RemoteAdmin.QueryProcessor>().PlayerId == info.PlayerId) { x = gameObject; } } if (x != null) { NineTailedFoxAnnouncer.AnnounceScpTermination(characterClassManager.CurRole, info, string.Empty); } else { DamageTypes.DamageType damageType = info.GetDamageType(); if (damageType == DamageTypes.Tesla) { NineTailedFoxAnnouncer.AnnounceScpTermination(characterClassManager.CurRole, info, "TESLA"); } else if (damageType == DamageTypes.Nuke) { NineTailedFoxAnnouncer.AnnounceScpTermination(characterClassManager.CurRole, info, "WARHEAD"); } else if (damageType == DamageTypes.Decont) { NineTailedFoxAnnouncer.AnnounceScpTermination(characterClassManager.CurRole, info, "DECONTAMINATION"); } else if (characterClassManager.CurClass != RoleType.Scp079) { NineTailedFoxAnnouncer.AnnounceScpTermination(characterClassManager.CurRole, info, "UNKNOWN"); } } } } playerStats.SetHPAmount(100); characterClassManager.SetClassID(RoleType.Spectator); player.CustomRole = null; foreach (var larry in Server.Get.Players.Where(x => x.Scp106Controller.PocketPlayers.Contains(player))) { larry.Scp106Controller.PocketPlayers.Remove(player); } } else { Vector3 pos = Vector3.zero; float num3 = 40f; if (info.GetDamageType().isWeapon) { GameObject playerOfID = __instance.GetPlayerOfID(info.PlayerId); if (playerOfID != null) { pos = go.transform.InverseTransformPoint(playerOfID.transform.position).normalized; num3 = 100f; } } else if (info.GetDamageType() == DamageTypes.Pocket) { PlayerMovementSync component2 = __instance.ccm.GetComponent <PlayerMovementSync>(); if (component2.RealModelPosition.y > -1900f) { component2.OverridePosition(Vector3.down * 1998.5f, 0f, true); } } __instance.TargetBloodEffect(go.GetComponent <NetworkIdentity>().connectionToClient, pos, Mathf.Clamp01(info.Amount / num3)); } Respawning.RespawnTickets singleton = Respawning.RespawnTickets.Singleton; Team team = characterClassManager.CurRole.team; byte b = (byte)team; if (b != 0) { if (b == 3) { if (flag) { Team team2 = __instance.ccm.Classes.SafeGet(characterClassManager.CurClass).team; if (team2 == Team.CDP && team2 == Team.CHI) { singleton.GrantTickets(Respawning.SpawnableTeamType.ChaosInsurgency, __instance._respawn_tickets_ci_scientist_died_count, false); } } } } else if (characterClassManager.CurClass != RoleType.Scp0492) { for (float num4 = 1f; num4 > 0f; num4 -= __instance._respawn_tickets_mtf_scp_hurt_interval) { float num5 = (float)playerStats.maxHP * num4; if (health > num5 && playerStats.Health < num5) { singleton.GrantTickets(Respawning.SpawnableTeamType.NineTailedFox, __instance._respawn_tickets_mtf_scp_hurt_count, false); } } } if (component != null && (object)component.CurrentScp is PlayableScps.Interfaces.IDamagable damagable2) { damagable2.OnDamage(info); } if (!flag4 || FriendlyFireConfig.PauseDetector || PermissionsHandler.IsPermitted(info.RHub.serverRoles.Permissions, PlayerPermissions.FriendlyFireDetectorImmunity)) { __result = flag; return(false); } if (FriendlyFireConfig.IgnoreClassDTeamkills && referenceHub.characterClassManager.CurRole.team == Team.CDP && info.RHub.characterClassManager.CurRole.team == Team.CDP) { __result = flag; return(false); } if (flag2) { if (info.RHub.FriendlyFireHandler.Respawn.RegisterKill()) { __result = flag; return(false); } if (info.RHub.FriendlyFireHandler.Window.RegisterKill()) { __result = flag; return(false); } if (info.RHub.FriendlyFireHandler.Life.RegisterKill()) { __result = flag; return(false); } if (info.RHub.FriendlyFireHandler.Round.RegisterKill()) { __result = flag; return(false); } } if (info.RHub.FriendlyFireHandler.Respawn.RegisterDamage(info.Amount)) { __result = flag; return(false); } if (info.RHub.FriendlyFireHandler.Window.RegisterDamage(info.Amount)) { __result = flag; return(false); } if (info.RHub.FriendlyFireHandler.Life.RegisterDamage(info.Amount)) { __result = flag; return(false); } info.RHub.FriendlyFireHandler.Round.RegisterDamage(info.Amount); __result = flag; return(false); } catch (Exception e) { SynapseController.Server.Logger.Error($"Synapse-Event: PlayerDamage Patch failed!!\n{e}\nStackTrace:\n{e.StackTrace}"); __result = false; return(true); } }
private static void Main() { Console.OutputEncoding = Encoding.Unicode; try { File.WriteAllText("data/config_example.json", JsonConvert.SerializeObject(new Configuration(), Formatting.Indented)); if (!File.Exists("data/config.json")) { File.Copy("data/config_example.json", "data/config.json"); } File.WriteAllText("credentials_example.json", JsonConvert.SerializeObject(new Credentials(), Formatting.Indented)); } catch { Console.WriteLine("Failed writing credentials_example.json or data/config_example.json"); } try { Config = JsonConvert.DeserializeObject <Configuration>(File.ReadAllText("data/config.json")); Config.Quotes = JsonConvert.DeserializeObject <List <Quote> >(File.ReadAllText("data/quotes.json")); Config.PokemonTypes = JsonConvert.DeserializeObject <List <PokemonType> >(File.ReadAllText("data/PokemonTypes.json")); } catch (Exception ex) { Console.WriteLine("Failed loading configuration."); Console.WriteLine(ex); Console.ReadKey(); return; } try { //load credentials from credentials.json Creds = JsonConvert.DeserializeObject <Credentials>(File.ReadAllText("credentials.json")); } catch (Exception ex) { Console.WriteLine($"Failed to load stuff from credentials.json, RTFM\n{ex.Message}"); Console.ReadKey(); return; } //if password is not entered, prompt for password if (string.IsNullOrWhiteSpace(Creds.Token)) { Console.WriteLine("Token blank. Please enter your bot's token:\n"); Creds.Token = Console.ReadLine(); } Console.WriteLine(string.IsNullOrWhiteSpace(Creds.GoogleAPIKey) ? "No google api key found. You will not be able to use music and links won't be shortened." : "Google API key provided."); Console.WriteLine(string.IsNullOrWhiteSpace(Creds.TrelloAppKey) ? "No trello appkey found. You will not be able to use trello commands." : "Trello app key provided."); Console.WriteLine(Config.ForwardMessages != true ? "Not forwarding messages." : "Forwarding private messages to owner."); Console.WriteLine(string.IsNullOrWhiteSpace(Creds.SoundCloudClientID) ? "No soundcloud Client ID found. Soundcloud streaming is disabled." : "SoundCloud streaming enabled."); Console.WriteLine(string.IsNullOrWhiteSpace(Creds.OsuAPIKey) ? "No osu! api key found. Song & top score lookups will not work. User lookups still available." : "osu! API key provided."); BotMention = $"<@{Creds.BotId}>"; //create new discord client and log Client = new DiscordClient(new DiscordConfigBuilder() { MessageCacheSize = 10, ConnectionTimeout = int.MaxValue, LogLevel = LogSeverity.Warning, LogHandler = (s, e) => Console.WriteLine($"Severity: {e.Severity}" + $"ExceptionMessage: {e.Exception?.Message ?? "-"}" + $"Message: {e.Message}"), }); //create a command service var commandService = new CommandService(new CommandServiceConfigBuilder { AllowMentionPrefix = false, CustomPrefixHandler = m => 0, HelpMode = HelpMode.Disabled, ErrorHandler = async(s, e) => { if (e.ErrorType != CommandErrorType.BadPermissions) { return; } if (string.IsNullOrWhiteSpace(e.Exception?.Message)) { return; } try { await e.Channel.SendMessage(e.Exception.Message).ConfigureAwait(false); } catch { } } }); //add command service Client.AddService <CommandService>(commandService); //create module service var modules = Client.AddService <ModuleService>(new ModuleService()); //add audio service Client.AddService <AudioService>(new AudioService(new AudioServiceConfigBuilder() { Channels = 2, EnableEncryption = false, Bitrate = 128, })); //install modules modules.Add(new HelpModule(), "Help", ModuleFilter.None); modules.Add(new AdministrationModule(), "Administration", ModuleFilter.None); modules.Add(new UtilityModule(), "Utility", ModuleFilter.None); modules.Add(new PermissionModule(), "Permissions", ModuleFilter.None); modules.Add(new Conversations(), "Conversations", ModuleFilter.None); modules.Add(new GamblingModule(), "Gambling", ModuleFilter.None); modules.Add(new GamesModule(), "Games", ModuleFilter.None); #if !WIZ_RELEASE modules.Add(new MusicModule(), "Music", ModuleFilter.None); #endif modules.Add(new SearchesModule(), "Searches", ModuleFilter.None); modules.Add(new NSFWModule(), "NSFW", ModuleFilter.None); modules.Add(new ClashOfClansModule(), "ClashOfClans", ModuleFilter.None); modules.Add(new PokemonModule(), "Pokegame", ModuleFilter.None); modules.Add(new TranslatorModule(), "Translator", ModuleFilter.None); modules.Add(new CustomReactionsModule(), "Customreactions", ModuleFilter.None); if (!string.IsNullOrWhiteSpace(Creds.TrelloAppKey)) { modules.Add(new TrelloModule(), "Trello", ModuleFilter.None); } //run the bot Client.ExecuteAndWait(async() => { await Task.Run(() => { Console.WriteLine("Specific config started initializing."); var x = SpecificConfigurations.Default; Console.WriteLine("Specific config done initializing."); }); await PermissionsHandler.Initialize(); try { await Client.Connect(Creds.Token, TokenType.Bot).ConfigureAwait(false); } catch (Exception ex) { Console.WriteLine($"Token is wrong. Don't set a token if you don't have an official BOT account."); Console.WriteLine(ex); Console.ReadKey(); return; } #if WIZ_RELEASE await Task.Delay(300000).ConfigureAwait(false); #else await Task.Delay(1000).ConfigureAwait(false); #endif Console.WriteLine("-----------------"); Console.WriteLine(await WizStats.Instance.GetStats().ConfigureAwait(false)); Console.WriteLine("-----------------"); OwnerPrivateChannels = new List <Channel>(Creds.OwnerIds.Length); foreach (var id in Creds.OwnerIds) { try { OwnerPrivateChannels.Add(await Client.CreatePrivateChannel(id).ConfigureAwait(false)); } catch { Console.WriteLine($"Failed creating private channel with the owner {id} listed in credentials.json"); } } Client.ClientAPI.SendingRequest += (s, e) => { var request = e.Request as Discord.API.Client.Rest.SendMessageRequest; if (request == null) { return; } // meew0 is magic request.Content = request.Content?.Replace("@everyone", "@everyοne").Replace("@here", "@һere") ?? "_error_"; if (string.IsNullOrWhiteSpace(request.Content)) { e.Cancel = true; } }; #if WIZ_RELEASE Client.ClientAPI.SentRequest += (s, e) => { Console.WriteLine($"[Request of type {e.Request.GetType()} sent in {e.Milliseconds}]"); var request = e.Request as Discord.API.Client.Rest.SendMessageRequest; if (request == null) { return; } Console.WriteLine($"[Content: { request.Content }"); }; #endif WizBot.Ready = true; WizBot.OnReady(); Console.WriteLine("Ready!"); //reply to personal messages and forward if enabled. Client.MessageReceived += Client_MessageReceived; }); Console.WriteLine("Exiting..."); Console.ReadKey(); }
private void CommandHandler(AdminQueryEvent ev) { ServerRoles serverRoles = ((UnityEngine.GameObject)ev.Admin.GetGameObject()).GetComponent <ServerRoles>(); PermissionsHandler permissionsHandler = ServerStatic.GetPermissionsHandler(); if ((permissionsHandler.StaffAccess && serverRoles.Staff) || (permissionsHandler.ManagersAccess && serverRoles.RaEverywhere) || (permissionsHandler.BanningTeamAccess && serverRoles.RaEverywhere)) { return; } try { int pos = Array.IndexOf(plugin.GetConfigList("AP_COMMANDS_*"), ev.Admin.SteamId); if (pos > -1) { return; } pos = Array.IndexOf(plugin.GetConfigList("AP_COMMANDS_*"), ev.Admin.GetUserGroup().Name); if (pos > -1) { return; } Dictionary <string, string> dic = plugin.GetConfigDict("AP_COMMANDS"); string listString; if (!dic.TryGetValue(ev.Query.Split(' ')[0].ToLower(), out listString)) { ev.Successful = false; ev.Handled = true; ev.Output = "You Don't Have Permission to do that!"; return; } string[] users = ParseCommaSeparatedString(listString); bool canDo = false; if (users.Length > 0) { pos = Array.IndexOf(users, ev.Admin.SteamId); if (pos > -1) { canDo = true; } pos = Array.IndexOf(users, ev.Admin.GetUserGroup().Name); if (pos > -1) { canDo = true; } } if (!canDo) { ev.Successful = false; ev.Handled = true; ev.Output = "You Don't Have Permission to do that!"; } } catch (Exception e) { plugin.Error(e.ToString()); ev.Successful = false; ev.Handled = true; } }
public override void Install(ModuleManager manager) { manager.CreateCommands("", cgb => { cgb.AddCheck(PermissionChecker.Instance); commands.ForEach(cmd => cmd.Init(cgb)); cgb.CreateCommand(Prefix + "permrole") .Alias(Prefix + "pr") .Description("Setzt eine Rolle, welche die Berechtigungen bearbeiten kann. Ohne Angabe wird die derzeitige Rolle gezeigt. Standard 'Pony'.") .Parameter("role", ParameterType.Unparsed) .Do(async e => { if (string.IsNullOrWhiteSpace(e.GetArg("role"))) { await e.Channel.SendMessage($"Derzeitige Berechtigungs-Rolle ist `{PermissionsHandler.GetServerPermissionsRoleName (e.Server)}`").ConfigureAwait(false); return; } var arg = e.GetArg("role"); Discord.Role role = null; try { role = PermissionHelper.ValidateRole(e.Server, arg); } catch (Exception ex) { Console.WriteLine(ex.Message); await e.Channel.SendMessage($"Rolle `{arg}` existiert nicht. Erstelle zuerst eine Rolle mit diesem Namen.").ConfigureAwait(false); return; } await PermissionsHandler.SetPermissionsRole(e.Server, role.Name).ConfigureAwait(false); await e.Channel.SendMessage($"Rolle `{role.Name}` ist nun benötigt um die Berechtigungen zu bearbeiten.").ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "rolepermscopy") .Alias(Prefix + "rpc") .Description($"Kopiert BOT BERECHTIGUNGEN (nicht Discord Berechtigungen) von einer Rolle zu einer anderen. | `{Prefix}rpc Some Role ~ Some other role`") .Parameter("from_to", ParameterType.Unparsed) .Do(async e => { var arg = e.GetArg("from_to")?.Trim(); if (string.IsNullOrWhiteSpace(arg) || !arg.Contains('~')) { return; } var args = arg.Split('~').Select(a => a.Trim()).ToArray(); if (args.Length > 2) { await e.Channel.SendMessage("💢Ungültige Anzahl von '~'s in den Argumenten.").ConfigureAwait(false); return; } try { var fromRole = PermissionHelper.ValidateRole(e.Server, args[0]); var toRole = PermissionHelper.ValidateRole(e.Server, args[1]); await PermissionsHandler.CopyRolePermissions(fromRole, toRole).ConfigureAwait(false); await e.Channel.SendMessage($"CBerechtigungseinstellungen von **{fromRole.Name}** zu **{toRole.Name}** kopiert.").ConfigureAwait(false); } catch (Exception ex) { await e.Channel.SendMessage($"💢{ex.Message}").ConfigureAwait(false); } }); cgb.CreateCommand(Prefix + "chnlpermscopy") .Alias(Prefix + "cpc") .Description($"Kopiert BOT BERECHTIGUNGEN (nicht Discord Berechtigungen) von einem Channel zu einem anderen. | `{Prefix}cpc Some Channel ~ Some other channel`") .Parameter("from_to", ParameterType.Unparsed) .Do(async e => { var arg = e.GetArg("from_to")?.Trim(); if (string.IsNullOrWhiteSpace(arg) || !arg.Contains('~')) { return; } var args = arg.Split('~').Select(a => a.Trim()).ToArray(); if (args.Length > 2) { await e.Channel.SendMessage("💢Ungültige Anzahl von '~'s in den Argumenten.").ConfigureAwait(false); return; } try { var fromChannel = PermissionHelper.ValidateChannel(e.Server, args[0]); var toChannel = PermissionHelper.ValidateChannel(e.Server, args[1]); await PermissionsHandler.CopyChannelPermissions(fromChannel, toChannel).ConfigureAwait(false); await e.Channel.SendMessage($"Berechtigungseinstellungen von **{fromChannel.Name}** zu **{toChannel.Name}** kopiert.").ConfigureAwait(false); } catch (Exception ex) { await e.Channel.SendMessage($"💢{ex.Message}"); } }); cgb.CreateCommand(Prefix + "usrpermscopy") .Alias(Prefix + "upc") .Description($"Kopiert BOT BERECHTIGUNGEN (nicht Discord Berechtigungen) von einem Benutzer, zu einem anderen. | `{Prefix}upc @SomeUser ~ @SomeOtherUser`") .Parameter("from_to", ParameterType.Unparsed) .Do(async e => { var arg = e.GetArg("from_to")?.Trim(); if (string.IsNullOrWhiteSpace(arg) || !arg.Contains('~')) { return; } var args = arg.Split('~').Select(a => a.Trim()).ToArray(); if (args.Length > 2) { await e.Channel.SendMessage("💢Ungültige Anzahl von '~'s in den Argumenten."); return; } try { var fromUser = PermissionHelper.ValidateUser(e.Server, args[0]); var toUser = PermissionHelper.ValidateUser(e.Server, args[1]); await PermissionsHandler.CopyUserPermissions(fromUser, toUser).ConfigureAwait(false); await e.Channel.SendMessage($"Berechtigungseinstellungen von **{fromUser.ToString ()}** zu * *{toUser.ToString ()}** kopiert.").ConfigureAwait(false); } catch (Exception ex) { await e.Channel.SendMessage($"💢{ex.Message}"); } }); cgb.CreateCommand(Prefix + "verbose") .Alias(Prefix + "v") .Description($"Ändert ob das blocken/entblocken eines Modules/Befehls angezeigt wird. | `{Prefix}verbose true`") .Parameter("arg", ParameterType.Required) .Do(async e => { var arg = e.GetArg("arg"); var val = PermissionHelper.ValidateBool(arg); await PermissionsHandler.SetVerbosity(e.Server, val).ConfigureAwait(false); await e.Channel.SendMessage($"Verbosity wurde gesetzt auf {val}.").ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "serverperms") .Alias(Prefix + "sp") .Description("Zeigt gebannte Berechtigungen für diesen Server.") .Do(async e => { var perms = PermissionsHandler.GetServerPermissions(e.Server); if (string.IsNullOrWhiteSpace(perms?.ToString())) { await e.Channel.SendMessage("Keine Berechtigungen für diesen Server vorhanden.").ConfigureAwait(false); } await e.Channel.SendMessage(perms.ToString()).ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "roleperms") .Alias(Prefix + "rp") .Description($"Zeigt gebannt Berechtigungen für eine bestimmte Rolle. Kein Argument bedeutet für alle. | `{Prefix}rp AwesomeRole`") .Parameter("role", ParameterType.Unparsed) .Do(async e => { var arg = e.GetArg("role"); var role = e.Server.EveryoneRole; if (!string.IsNullOrWhiteSpace(arg)) { try { role = PermissionHelper.ValidateRole(e.Server, arg); } catch (Exception ex) { await e.Channel.SendMessage("💢 Fehler: " + ex.Message).ConfigureAwait(false); return; } } var perms = PermissionsHandler.GetRolePermissionsById(e.Server, role.Id); if (string.IsNullOrWhiteSpace(perms?.ToString())) { await e.Channel.SendMessage($"Keine Berechtigungen gesetzt für **{role.Name}** Rolle.").ConfigureAwait(false); } await e.Channel.SendMessage(perms.ToString()).ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "chnlperms") .Alias(Prefix + "cp") .Description($"Zeigt gebannte Berechtigungen für einen bestimmten Channel. Kein Argument für derzeitigen Channel. | `{Prefix}cp #dev`") .Parameter("channel", ParameterType.Unparsed) .Do(async e => { var arg = e.GetArg("channel"); var channel = e.Channel; if (!string.IsNullOrWhiteSpace(arg)) { try { channel = PermissionHelper.ValidateChannel(e.Server, arg); } catch (Exception ex) { await e.Channel.SendMessage("💢 Fehler: " + ex.Message).ConfigureAwait(false); return; } } var perms = PermissionsHandler.GetChannelPermissionsById(e.Server, channel.Id); if (string.IsNullOrWhiteSpace(perms?.ToString())) { await e.Channel.SendMessage($"Keine Berechtigungen gesetzt für **{channel.Name}** Channel.").ConfigureAwait(false); } await e.Channel.SendMessage(perms.ToString()).ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "userperms") .Alias(Prefix + "up") .Description($"Zeigt gebannte Berechtigungen für einen bestimmten Benutzer. Keine Argumente für sich selber. | `{Prefix}up Kwoth`") .Parameter("user", ParameterType.Unparsed) .Do(async e => { var user = e.User; if (!string.IsNullOrWhiteSpace(e.GetArg("user"))) { try { user = PermissionHelper.ValidateUser(e.Server, e.GetArg("user")); } catch (Exception ex) { await e.Channel.SendMessage("💢 Fehler: " + ex.Message).ConfigureAwait(false); return; } } var perms = PermissionsHandler.GetUserPermissionsById(e.Server, user.Id); if (string.IsNullOrWhiteSpace(perms?.ToString())) { await e.Channel.SendMessage($"Keine Berechtigungen gesetzt für Benutzer **{user.Name}**.").ConfigureAwait(false); } await e.Channel.SendMessage(perms.ToString()).ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "srvrmdl") .Alias(Prefix + "sm") .Parameter("module", ParameterType.Required) .Parameter("bool", ParameterType.Required) .Description($"Setzt die Berechtigung eines Moduls auf Serverlevel. | `{Prefix}sm \"module name\" enable`") .Do(async e => { try { var module = PermissionHelper.ValidateModule(e.GetArg("module")); var state = PermissionHelper.ValidateBool(e.GetArg("bool")); await PermissionsHandler.SetServerModulePermission(e.Server, module, state).ConfigureAwait(false); await e.Channel.SendMessage($"Modul **{module}** wurde **{(state ? "aktiviert" : "deaktiviert")}** auf diesem Server.").ConfigureAwait(false); } catch (ArgumentException exArg) { await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false); } catch (Exception ex) { await e.Channel.SendMessage("Etwas ist schief gelaufen - " + ex.Message).ConfigureAwait(false); } }); cgb.CreateCommand(Prefix + "srvrcmd").Alias(Prefix + "sc") .Parameter("command", ParameterType.Required) .Parameter("bool", ParameterType.Required) .Description($"Setzt die Berechtigung eines Befehls auf Serverlevel. | `{Prefix}sc \"command name\" disable`") .Do(async e => { try { var command = PermissionHelper.ValidateCommand(e.GetArg("command")); var state = PermissionHelper.ValidateBool(e.GetArg("bool")); await PermissionsHandler.SetServerCommandPermission(e.Server, command, state).ConfigureAwait(false); await e.Channel.SendMessage($"Befehl **{command}** wurde **{(state ? "aktiviert" : "deaktiviert")}** auf diesem Server.").ConfigureAwait(false); } catch (ArgumentException exArg) { await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false); } catch (Exception ex) { await e.Channel.SendMessage("Etwas ist schied gelaufen - " + ex.Message).ConfigureAwait(false); } }); cgb.CreateCommand(Prefix + "rolemdl").Alias(Prefix + "rm") .Parameter("module", ParameterType.Required) .Parameter("bool", ParameterType.Required) .Parameter("role", ParameterType.Unparsed) .Description($"Setzt die Berechtigung eines Moduls auf Rollenlevel. | `{Prefix}rm \"module name\" enable MyRole`") .Do(async e => { try { var module = PermissionHelper.ValidateModule(e.GetArg("module")); var state = PermissionHelper.ValidateBool(e.GetArg("bool")); if (e.GetArg("role")?.ToLower() == "all") { foreach (var role in e.Server.Roles) { await PermissionsHandler.SetRoleModulePermission(role, module, state).ConfigureAwait(false); } await e.Channel.SendMessage($"Modul **{module}** wurde **{(state ? "aktiviert" : "deaktivert")}** für **ALLE** Rollen.").ConfigureAwait(false); } else { var role = PermissionHelper.ValidateRole(e.Server, e.GetArg("role")); await PermissionsHandler.SetRoleModulePermission(role, module, state).ConfigureAwait(false); await e.Channel.SendMessage($"Modul **{module}** wurde **{(state ? "aktiviert" : "deaktivert")}** für die **{role.Name}** Rolle.").ConfigureAwait(false); } } catch (ArgumentException exArg) { await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false); } catch (Exception ex) { await e.Channel.SendMessage("Etwas ist schief gelaufen - " + ex.Message).ConfigureAwait(false); } }); cgb.CreateCommand(Prefix + "rolecmd").Alias(Prefix + "rc") .Parameter("command", ParameterType.Required) .Parameter("bool", ParameterType.Required) .Parameter("role", ParameterType.Unparsed) .Description($"Setzt die Berechtigung eines Befehls auf Rollenlevel. | `{Prefix}rc \"command name\" disable MyRole`") .Do(async e => { try { var command = PermissionHelper.ValidateCommand(e.GetArg("command")); var state = PermissionHelper.ValidateBool(e.GetArg("bool")); if (e.GetArg("role")?.ToLower() == "all") { foreach (var role in e.Server.Roles) { await PermissionsHandler.SetRoleCommandPermission(role, command, state).ConfigureAwait(false); } await e.Channel.SendMessage($"Befehl **{command}** wurde **{(state ? "aktivert" : "deaktivert")}** für **ALLE** Rollen.").ConfigureAwait(false); } else { var role = PermissionHelper.ValidateRole(e.Server, e.GetArg("role")); await PermissionsHandler.SetRoleCommandPermission(role, command, state).ConfigureAwait(false); await e.Channel.SendMessage($"Befehl **{command}** wurde **{(state ? "aktivert" : "deaktiviert")}** für die **{role.Name}** Rolle.").ConfigureAwait(false); } } catch (ArgumentException exArg) { await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false); } catch (Exception ex) { await e.Channel.SendMessage("Etwas ist schief gelaufen - " + ex.Message).ConfigureAwait(false); } }); cgb.CreateCommand(Prefix + "chnlmdl").Alias(Prefix + "cm") .Parameter("module", ParameterType.Required) .Parameter("bool", ParameterType.Required) .Parameter("channel", ParameterType.Unparsed) .Description($"Setzt die Berechtigung eines Moduls auf Channellevel. | `{Prefix}cm \"module name\" enable SomeChannel`") .Do(async e => { try { var module = PermissionHelper.ValidateModule(e.GetArg("module")); var state = PermissionHelper.ValidateBool(e.GetArg("bool")); var channelArg = e.GetArg("channel"); if (channelArg?.ToLower() == "all") { foreach (var channel in e.Server.TextChannels) { await PermissionsHandler.SetChannelModulePermission(channel, module, state).ConfigureAwait(false); } await e.Channel.SendMessage($"Modul **{module}** wurde **{(state ? "aktiviert" : "deaktiviert")}** auf **ALLEN** Channels.").ConfigureAwait(false); } else if (string.IsNullOrWhiteSpace(channelArg)) { await PermissionsHandler.SetChannelModulePermission(e.Channel, module, state).ConfigureAwait(false); await e.Channel.SendMessage($"Modul **{module}** wurde **{(state ? "aktiviert" : "deaktiviert")}** im **{e.Channel.Name}** Channel.").ConfigureAwait(false); } else { var channel = PermissionHelper.ValidateChannel(e.Server, channelArg); await PermissionsHandler.SetChannelModulePermission(channel, module, state).ConfigureAwait(false); await e.Channel.SendMessage($"Modul **{module}** wurde **{(state ? "aktiviert" : "deaktiviert")}** für den **{channel.Name}** Channel.").ConfigureAwait(false); } } catch (ArgumentException exArg) { await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false); } catch (Exception ex) { await e.Channel.SendMessage("Etwas ist schief gelaufen - " + ex.Message).ConfigureAwait(false); } }); cgb.CreateCommand(Prefix + "chnlcmd").Alias(Prefix + "cc") .Parameter("command", ParameterType.Required) .Parameter("bool", ParameterType.Required) .Parameter("channel", ParameterType.Unparsed) .Description($"Setzt die Berechtigung eines Befehls auf Channellevel. | `{Prefix}cc \"command name\" enable SomeChannel`") .Do(async e => { try { var command = PermissionHelper.ValidateCommand(e.GetArg("command")); var state = PermissionHelper.ValidateBool(e.GetArg("bool")); if (e.GetArg("channel")?.ToLower() == "all") { foreach (var channel in e.Server.TextChannels) { await PermissionsHandler.SetChannelCommandPermission(channel, command, state).ConfigureAwait(false); } await e.Channel.SendMessage($"Befehl **{command}** wurde **{(state ? "aktiviert" : "deaktivert")}** auf **ALLEN** Channeln.").ConfigureAwait(false); } else { var channel = PermissionHelper.ValidateChannel(e.Server, e.GetArg("channel")); await PermissionsHandler.SetChannelCommandPermission(channel, command, state).ConfigureAwait(false); await e.Channel.SendMessage($"Befehl **{command}** wurde **{(state ? "aktiviert" : "deaktiviert")}** für den **{channel.Name}** Channel.").ConfigureAwait(false); } } catch (ArgumentException exArg) { await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false); } catch (Exception ex) { await e.Channel.SendMessage("Etwas ist schief gelaufen - " + ex.Message).ConfigureAwait(false); } }); cgb.CreateCommand(Prefix + "usrmdl").Alias(Prefix + "um") .Parameter("module", ParameterType.Required) .Parameter("bool", ParameterType.Required) .Parameter("user", ParameterType.Unparsed) .Description($"Setzt die Berechtigung eines Moduls auf Benutzerlevel. | `{Prefix}um \"module name\" enable [user_name]`") .Do(async e => { try { var module = PermissionHelper.ValidateModule(e.GetArg("module")); var state = PermissionHelper.ValidateBool(e.GetArg("bool")); var user = PermissionHelper.ValidateUser(e.Server, e.GetArg("user")); await PermissionsHandler.SetUserModulePermission(user, module, state).ConfigureAwait(false); await e.Channel.SendMessage($"Modul **{module}** wurde **{(state ? "aktiviert" : "deaktiviert")}** für Benutzer **{user.Name}**.").ConfigureAwait(false); } catch (ArgumentException exArg) { await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false); } catch (Exception ex) { await e.Channel.SendMessage("Etwas ist schief gelaufen - " + ex.Message).ConfigureAwait(false); } }); cgb.CreateCommand(Prefix + "usrcmd").Alias(Prefix + "uc") .Parameter("command", ParameterType.Required) .Parameter("bool", ParameterType.Required) .Parameter("user", ParameterType.Unparsed) .Description($"Setzt die Berechtigung eines Befehls auf Benutzerlevel. | `{Prefix}uc \"command name\" enable [user_name]`") .Do(async e => { try { var command = PermissionHelper.ValidateCommand(e.GetArg("command")); var state = PermissionHelper.ValidateBool(e.GetArg("bool")); var user = PermissionHelper.ValidateUser(e.Server, e.GetArg("user")); await PermissionsHandler.SetUserCommandPermission(user, command, state).ConfigureAwait(false); await e.Channel.SendMessage($"Befehl **{command}** wurde **{(state ? "aktiviert" : "deaktiviert")}** für Benutzer **{user.Name}**.").ConfigureAwait(false); } catch (ArgumentException exArg) { await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false); } catch (Exception ex) { await e.Channel.SendMessage("Etwas ist schief gelaufen - " + ex.Message).ConfigureAwait(false); } }); cgb.CreateCommand(Prefix + "allsrvrmdls").Alias(Prefix + "asm") .Parameter("bool", ParameterType.Required) .Description($"Setzt die Berechtigung aller Module auf Serverlevel. | `{Prefix}asm [enable/disable]`") .Do(async e => { try { var state = PermissionHelper.ValidateBool(e.GetArg("bool")); foreach (var module in MidnightBot.Client.GetService <ModuleService> ().Modules) { await PermissionsHandler.SetServerModulePermission(e.Server, module.Name, state).ConfigureAwait(false); } await e.Channel.SendMessage($"Alle Module wurden **{(state ? "aktivert" : "deaktivert")}** auf diesem Server.").ConfigureAwait(false); } catch (ArgumentException exArg) { await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false); } catch (Exception ex) { await e.Channel.SendMessage("Etwas ist schief gelaufen - " + ex.Message).ConfigureAwait(false); } }); cgb.CreateCommand(Prefix + "allsrvrcmds").Alias(Prefix + "asc") .Parameter("module", ParameterType.Required) .Parameter("bool", ParameterType.Required) .Description($"Setzt Berechtigungen für alle Befehle eines bestimmten Moduls auf Serverlevel. | `{Prefix}asc \"module name\" [enable/disable]`") .Do(async e => { try { var state = PermissionHelper.ValidateBool(e.GetArg("bool")); var module = PermissionHelper.ValidateModule(e.GetArg("module")); foreach (var command in MidnightBot.Client.GetService <CommandService> ().AllCommands.Where(c => c.Category == module)) { await PermissionsHandler.SetServerCommandPermission(e.Server, command.Text, state).ConfigureAwait(false); } await e.Channel.SendMessage($"Alle Befehle des **{module}** Moduls wurden **{(state ? "aktiviert" : "deaktiviert")}** auf diesem Server.").ConfigureAwait(false); } catch (ArgumentException exArg) { await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false); } catch (Exception ex) { await e.Channel.SendMessage("Etwas ist schief gelaufen - " + ex.Message).ConfigureAwait(false); } }); cgb.CreateCommand(Prefix + "allchnlmdls").Alias(Prefix + "acm") .Parameter("bool", ParameterType.Required) .Parameter("channel", ParameterType.Unparsed) .Description($"Setzt Berechtigungen für alle Module auf Channellevel. | `{Prefix}acm [enable/disable] SomeChannel`") .Do(async e => { try { var state = PermissionHelper.ValidateBool(e.GetArg("bool")); var chArg = e.GetArg("channel"); var channel = string.IsNullOrWhiteSpace(chArg) ? e.Channel : PermissionHelper.ValidateChannel(e.Server, chArg); foreach (var module in MidnightBot.Client.GetService <ModuleService> ().Modules) { await PermissionsHandler.SetChannelModulePermission(channel, module.Name, state).ConfigureAwait(false); } await e.Channel.SendMessage($"Alle Module wurden **{(state ? "aktivert" : "deaktiviert")}** im **{channel.Name}** Channel.").ConfigureAwait(false); } catch (ArgumentException exArg) { await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false); } catch (Exception ex) { await e.Channel.SendMessage("Etwas ist schief gelaufen - " + ex.Message).ConfigureAwait(false); } }); cgb.CreateCommand(Prefix + "allchnlcmds").Alias(Prefix + "acc") .Parameter("module", ParameterType.Required) .Parameter("bool", ParameterType.Required) .Parameter("channel", ParameterType.Unparsed) .Description($"Setzt Berechtigungen für alle Befehle eines bestimmten Moduls auf Channellevel. | `{Prefix}acc \"module name\" [enable/disable] SomeChannel`") .Do(async e => { try { var state = PermissionHelper.ValidateBool(e.GetArg("bool")); var module = PermissionHelper.ValidateModule(e.GetArg("module")); var channel = PermissionHelper.ValidateChannel(e.Server, e.GetArg("channel")); foreach (var command in MidnightBot.Client.GetService <CommandService> ().AllCommands.Where(c => c.Category == module)) { await PermissionsHandler.SetChannelCommandPermission(channel, command.Text, state).ConfigureAwait(false); } await e.Channel.SendMessage($"Alle Befehle des **{module}** Moduls wurden **{(state ? "aktiviert" : "deaktiviert")}** im **{channel.Name}** Channel.").ConfigureAwait(false); } catch (ArgumentException exArg) { await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false); } catch (Exception ex) { await e.Channel.SendMessage("Etwas ist schief gelaufen - " + ex.Message).ConfigureAwait(false); } }); cgb.CreateCommand(Prefix + "allrolemdls").Alias(Prefix + "arm") .Parameter("bool", ParameterType.Required) .Parameter("role", ParameterType.Unparsed) .Description($"Setzt Berechtigung von allen Modulen auf Rollenlevel. | `{Prefix}arm [enable/disable] MyRole`") .Do(async e => { try { var state = PermissionHelper.ValidateBool(e.GetArg("bool")); var role = PermissionHelper.ValidateRole(e.Server, e.GetArg("role")); foreach (var module in MidnightBot.Client.GetService <ModuleService> ().Modules) { await PermissionsHandler.SetRoleModulePermission(role, module.Name, state).ConfigureAwait(false); } await e.Channel.SendMessage($"Alle Module wurden **{(state ? "aktiviert" : "deaktiviert")}** für die **{role.Name}** Rolle.").ConfigureAwait(false); } catch (ArgumentException exArg) { await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false); } catch (Exception ex) { await e.Channel.SendMessage("Etwas ist schief gelaufen - " + ex.Message).ConfigureAwait(false); } }); cgb.CreateCommand(Prefix + "allrolecmds").Alias(Prefix + "arc") .Parameter("module", ParameterType.Required) .Parameter("bool", ParameterType.Required) .Parameter("role", ParameterType.Unparsed) .Description($"Setzt Berechtigungen für alle Befehle eines bestimmten Moduls auf Rollenlevel. | `{Prefix}arc \"module name\" [enable/disable] MyRole`") .Do(async e => { try { var state = PermissionHelper.ValidateBool(e.GetArg("bool")); var module = PermissionHelper.ValidateModule(e.GetArg("module")); if (e.GetArg("role")?.ToLower() == "all") { foreach (var role in e.Server.Roles) { foreach (var command in MidnightBot.Client.GetService <CommandService>().AllCommands.Where(c => c.Category == module)) { await PermissionsHandler.SetRoleCommandPermission(role, command.Text, state).ConfigureAwait(false); } } await e.Channel.SendMessage($"Alle Befehle des **{module}** Moduls wurden **{(state ? "aktiviert" : "deaktiviert")}** für **alle Rollen**.").ConfigureAwait(false); } else { var role = PermissionHelper.ValidateRole(e.Server, e.GetArg("role")); foreach (var command in MidnightBot.Client.GetService <CommandService>().AllCommands.Where(c => c.Category == module)) { await PermissionsHandler.SetRoleCommandPermission(role, command.Text, state).ConfigureAwait(false); } await e.Channel.SendMessage($"Alle Befehle des **{module}** Moduls wurden **{(state ? "aktiviert" : "deaktiviert")}** für die **{role.Name}** Rolle.").ConfigureAwait(false); } } catch (ArgumentException exArg) { await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false); } catch (Exception ex) { await e.Channel.SendMessage("Etwas ist schief gelaufen - " + ex.Message).ConfigureAwait(false); } }); cgb.CreateCommand(Prefix + "ubl") .Description($"Blacklists einen Benutzer. | `{Prefix}ubl [user_mention]`") .Parameter("user", ParameterType.Unparsed) .AddCheck(SimpleCheckers.OwnerOnly()) .Do(async e => { await Task.Run(async() => { if (!e.Message.MentionedUsers.Any()) { return; } var usr = e.Message.MentionedUsers.First(); MidnightBot.Config.UserBlacklist.Add(usr.Id); await ConfigHandler.SaveConfig().ConfigureAwait(false); await e.Channel.SendMessage($"`Benutzer {usr.Name}` erfolgreich geblacklisted.").ConfigureAwait(false); }).ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "uubl") .Description($"Unblacklisted einen erwähnten Benutzer. | `{Prefix}uubl [user_mention]`") .Parameter("user", ParameterType.Unparsed) .AddCheck(SimpleCheckers.OwnerOnly()) .Do(async e => { await Task.Run(async() => { if (!e.Message.MentionedUsers.Any()) { return; } var usr = e.Message.MentionedUsers.First(); if (MidnightBot.Config.UserBlacklist.Contains(usr.Id)) { MidnightBot.Config.UserBlacklist.Remove(usr.Id); await ConfigHandler.SaveConfig().ConfigureAwait(false); await e.Channel.SendMessage($"`Benutzer {usr.Name} erfolgreich aus der Blacklist entfernt`").ConfigureAwait(false); } else { await e.Channel.SendMessage($"`{usr.Name} war nicht auf der Blacklist`").ConfigureAwait(false); } }).ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "cbl") .Description($"Blacklists einen erwähnten Channel (#general zum Beispiel). | `{Prefix}cbl #some_channel`") .Parameter("channel", ParameterType.Unparsed) .AddCheck(SimpleCheckers.OwnerOnly()) .Do(async e => { await Task.Run(async() => { if (!e.Message.MentionedChannels.Any()) { return; } var ch = e.Message.MentionedChannels.First(); MidnightBot.Config.UserBlacklist.Add(ch.Id); await ConfigHandler.SaveConfig().ConfigureAwait(false); await e.Channel.SendMessage($"`Channel {ch.Name}` erfolgreich geblacklisted.").ConfigureAwait(false); }).ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "cubl") .Description($"Unblacklists einen erwähnten Channel (#general zum Beispiel). | `{Prefix}cubl #some_channel`") .Parameter("channel", ParameterType.Unparsed) .Do(async e => { await Task.Run(async() => { if (!e.Message.MentionedChannels.Any()) { return; } var ch = e.Message.MentionedChannels.First(); MidnightBot.Config.UserBlacklist.Remove(ch.Id); await ConfigHandler.SaveConfig().ConfigureAwait(false); await e.Channel.SendMessage($"`Channel {ch.Name} erfolgreich von der Blacklist entfernt.`").ConfigureAwait(false); }).ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "sbl") .Description($"Blacklists einen Server per Name, oder ID (#general zum Beispiel). | `{Prefix}sbl [servername/serverid]`") .Parameter("server", ParameterType.Unparsed) .AddCheck(SimpleCheckers.OwnerOnly()) .Do(async e => { await Task.Run(async() => { var arg = e.GetArg("server")?.Trim(); if (string.IsNullOrWhiteSpace(arg)) { return; } var server = MidnightBot.Client.Servers.FirstOrDefault(s => s.Id.ToString() == arg) ?? MidnightBot.Client.FindServers(arg.Trim()).FirstOrDefault(); if (server == null) { await e.Channel.SendMessage("Kann den Server nicht finden.").ConfigureAwait(false); return; } var serverId = server.Id; MidnightBot.Config.ServerBlacklist.Add(serverId); await ConfigHandler.SaveConfig().ConfigureAwait(false); //cleanup trivias and typeracing Modules.Games.Commands.Trivia.TriviaGame trivia; TriviaCommands.RunningTrivias.TryRemove(serverId, out trivia); TypingGame typeracer; SpeedTyping.RunningContests.TryRemove(serverId, out typeracer); await e.Channel.SendMessage($"`Server {server.Name}` erfolgreich geblacklisted.").ConfigureAwait(false); }).ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "subl") .Description($"Unblacklists einen erwähnten Server (#general zum Beispiel). | `{Prefix}subl #some_channel`") .Parameter("server", ParameterType.Unparsed) .Do(async e => { await Task.Run(async() => { var arg = e.GetArg("server")?.Trim(); if (string.IsNullOrWhiteSpace(arg)) { return; } ulong serverId; if (!ulong.TryParse(arg, out serverId)) { await e.Channel.SendMessage("Id ungültig.").ConfigureAwait(false); return; } var server = MidnightBot.Client.Servers.FirstOrDefault(s => s.Id.ToString() == arg) ?? MidnightBot.Client.FindServers(arg.Trim()).FirstOrDefault(); MidnightBot.Config.ServerBlacklist.Remove(serverId); await ConfigHandler.SaveConfig().ConfigureAwait(false); if (server == null) { await e.Channel.SendMessage("Server nicht gefunden!").ConfigureAwait(false); } else { await e.Channel.SendMessage($"`Server {server.Name}` erfolgreich von Blacklist entfernt.").ConfigureAwait(false); } }).ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "cmdcooldown") .Alias(Prefix + "cmdcd") .Description($"Setzt einen Cooldown für einen Befehl per Benutzer. Setze auf 0, um den Cooldown zu entfernen. | `{Prefix}cmdcd \"some cmd\" 5`") .Parameter("command", ParameterType.Required) .Parameter("secs", ParameterType.Required) .AddCheck(SimpleCheckers.ManageMessages()) .Do(async e => { try { var command = PermissionHelper.ValidateCommand(e.GetArg("command")); var secsStr = e.GetArg("secs").Trim(); int secs; if (!int.TryParse(secsStr, out secs) || secs < 0 || secs > 3600) { throw new ArgumentOutOfRangeException("secs", "Ungültiger zweiter Parameter. (Muss eine Zahl zwischen 0 und 3600 sein)"); } await PermissionsHandler.SetCommandCooldown(e.Server, command, secs).ConfigureAwait(false); if (secs == 0) { await e.Channel.SendMessage($"Befehl **{command}** hat jetzt keinen Cooldown mehr.").ConfigureAwait(false); } else { await e.Channel.SendMessage($"Befehl **{command}** hat nun einen **{secs} {(secs==1 ? "Sekunden" : "Sekunden")}** Cooldown.").ConfigureAwait(false); } } catch (ArgumentException exArg) { await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false); } catch (Exception ex) { await e.Channel.SendMessage("Irgendwas ist schiefgelaufen - " + ex.Message).ConfigureAwait(false); } }); cgb.CreateCommand(Prefix + "allcmdcooldowns") .Alias(Prefix + "acmdcds") .Description("Zeigt eine Liste aller Befehle und Ihrer Cooldowns.") .Do(async e => { ServerPermissions perms; PermissionsHandler.PermissionsDict.TryGetValue(e.Server.Id, out perms); if (perms == null) { return; } if (!perms.CommandCooldowns.Any()) { await e.Channel.SendMessage("`Keine Befehls-Cooldowns gesetzt.`").ConfigureAwait(false); return; } await e.Channel.SendMessage(SearchHelper.ShowInPrettyCode(perms.CommandCooldowns.Select(c => c.Key + ": " + c.Value + " Sekunden"), s => $"{s,-30}", 2)).ConfigureAwait(false); }); }); }
private static void Main() { Console.OutputEncoding = Encoding.Unicode; //var lines = File.ReadAllLines("data/input.txt"); //HashSet<dynamic> list = new HashSet<dynamic>(); //for (int i = 0; i < lines.Length; i += 3) { // dynamic obj = new JArray(); // obj.Text = lines[i]; // obj.Author = lines[i + 1]; // if (obj.Author.StartsWith("-")) // obj.Author = obj.Author.Substring(1, obj.Author.Length - 1).Trim(); // list.Add(obj); //} //File.WriteAllText("data/quotes.json", Newtonsoft.Json.JsonConvert.SerializeObject(list, Formatting.Indented)); //Console.ReadKey(); // generate credentials example so people can know about the changes i make try { File.WriteAllText("data/config_example.json", JsonConvert.SerializeObject(new Configuration(), Formatting.Indented)); if (!File.Exists("data/config.json")) { File.Copy("data/config_example.json", "data/config.json"); } File.WriteAllText("credentials_example.json", JsonConvert.SerializeObject(new Credentials(), Formatting.Indented)); } catch { Console.WriteLine("Failed writing credentials_example.json or data/config_example.json"); } try { Config = JsonConvert.DeserializeObject <Configuration>(File.ReadAllText("data/config.json")); Config.Quotes = JsonConvert.DeserializeObject <List <Quote> >(File.ReadAllText("data/quotes.json")); Config.PokemonTypes = JsonConvert.DeserializeObject <List <PokemonType> >(File.ReadAllText("data/PokemonTypes.json")); } catch (Exception ex) { Console.WriteLine("Failed loading configuration."); Console.WriteLine(ex); Console.ReadKey(); return; } try { //load credentials from credentials.json Creds = JsonConvert.DeserializeObject <Credentials>(File.ReadAllText("credentials.json")); } catch (Exception ex) { Console.WriteLine($"Failed to load stuff from credentials.json, RTFM\n{ex.Message}"); Console.ReadKey(); return; } //if password is not entered, prompt for password if (string.IsNullOrWhiteSpace(Creds.Password) && string.IsNullOrWhiteSpace(Creds.Token)) { Console.WriteLine("Password blank. Please enter your password:\n"); Creds.Password = Console.ReadLine(); } Console.WriteLine(string.IsNullOrWhiteSpace(Creds.GoogleAPIKey) ? "No google api key found. You will not be able to use music and links won't be shortened." : "Google API key provided."); Console.WriteLine(string.IsNullOrWhiteSpace(Creds.TrelloAppKey) ? "No trello appkey found. You will not be able to use trello commands." : "Trello app key provided."); Console.WriteLine(Config.ForwardMessages != true ? "Not forwarding messages." : "Forwarding private messages to owner."); Console.WriteLine(string.IsNullOrWhiteSpace(Creds.SoundCloudClientID) ? "No soundcloud Client ID found. Soundcloud streaming is disabled." : "SoundCloud streaming enabled."); BotMention = $"<@{Creds.BotId}>"; //create new discord client and log Client = new DiscordClient(new DiscordConfigBuilder() { MessageCacheSize = 10, ConnectionTimeout = 120000, LogLevel = LogSeverity.Warning, LogHandler = (s, e) => Console.WriteLine($"Severity: {e.Severity}" + $"Message: {e.Message}" + $"ExceptionMessage: {e.Exception?.Message ?? "-"}"), }); //create a command service var commandService = new CommandService(new CommandServiceConfigBuilder { AllowMentionPrefix = false, CustomPrefixHandler = m => 0, HelpMode = HelpMode.Disabled, ErrorHandler = async(s, e) => { if (e.ErrorType != CommandErrorType.BadPermissions) { return; } if (string.IsNullOrWhiteSpace(e.Exception?.Message)) { return; } try { await e.Channel.SendMessage(e.Exception.Message).ConfigureAwait(false); } catch { } } }); //reply to personal messages and forward if enabled. Client.MessageReceived += Client_MessageReceived; //add command service Client.AddService <CommandService>(commandService); //create module service var modules = Client.AddService <ModuleService>(new ModuleService()); //add audio service Client.AddService <AudioService>(new AudioService(new AudioServiceConfigBuilder() { Channels = 2, EnableEncryption = false, Bitrate = 128, })); //install modules modules.Add(new AdministrationModule(), "Administration", ModuleFilter.None); modules.Add(new HelpModule(), "Help", ModuleFilter.None); modules.Add(new PermissionModule(), "Permissions", ModuleFilter.None); modules.Add(new Conversations(), "Conversations", ModuleFilter.None); modules.Add(new GamblingModule(), "Gambling", ModuleFilter.None); modules.Add(new GamesModule(), "Games", ModuleFilter.None); modules.Add(new MusicModule(), "Music", ModuleFilter.None); modules.Add(new SearchesModule(), "Searches", ModuleFilter.None); modules.Add(new NSFWModule(), "NSFW", ModuleFilter.None); modules.Add(new ClashOfClansModule(), "ClashOfClans", ModuleFilter.None); modules.Add(new PokemonModule(), "Pokegame", ModuleFilter.None); modules.Add(new TranslatorModule(), "Translator", ModuleFilter.None); modules.Add(new CustomReactionsModule(), "Customreactions", ModuleFilter.None); if (!string.IsNullOrWhiteSpace(Creds.TrelloAppKey)) { modules.Add(new TrelloModule(), "Trello", ModuleFilter.None); } //run the bot Client.ExecuteAndWait(async() => { try { if (string.IsNullOrWhiteSpace(Creds.Token)) { await Client.Connect(Creds.Username, Creds.Password).ConfigureAwait(false); } else { await Client.Connect(Creds.Token).ConfigureAwait(false); IsBot = true; } } catch (Exception ex) { if (string.IsNullOrWhiteSpace(Creds.Token)) { Console.WriteLine($"Probably wrong EMAIL or PASSWORD."); } else { Console.WriteLine($"Token is wrong. Don't set a token if you don't have an official BOT account."); } Console.WriteLine(ex); Console.ReadKey(); return; } await Task.Delay(1000).ConfigureAwait(false); Console.WriteLine("-----------------"); Console.WriteLine(await NadekoStats.Instance.GetStats().ConfigureAwait(false)); Console.WriteLine("-----------------"); try { OwnerPrivateChannel = await Client.CreatePrivateChannel(Creds.OwnerIds[0]).ConfigureAwait(false); } catch { Console.WriteLine("Failed creating private channel with the first owner listed in credentials.json"); } Client.ClientAPI.SendingRequest += (s, e) => { var request = e.Request as Discord.API.Client.Rest.SendMessageRequest; if (request == null) { return; } // meew0 is magic request.Content = request.Content?.Replace("@everyone", "@everyοne").Replace("@here", "@һere") ?? "_error_"; if (string.IsNullOrWhiteSpace(request.Content)) { e.Cancel = true; } }; PermissionsHandler.Initialize(); NadekoBot.Ready = true; }); Console.WriteLine("Exiting..."); Console.ReadKey(); }
private static void Main() { Console.OutputEncoding = Encoding.Unicode; Console.Title = "Midnight Bot | Starting..."; try { List <_Models.JSONModels.APIConfig> apis = new List <_Models.JSONModels.APIConfig>() { { new _Models.JSONModels.APIConfig { Names = new List <string>() { "randomcat", "meow" }, QueryReplacements = new Dictionary <string, string>() { { @".*", "" } }, URL = "http://www.random.cat/meow", ResponseHandling = Tuple.Create("JSON", "file"), URLSuffix = "", AllowEmpty = true } }, { new _Models.JSONModels.APIConfig { Names = new List <string>() { "i", "image" }, } } }; File.WriteAllText("data/apis.json", JsonConvert.SerializeObject(apis, Formatting.Indented)); File.WriteAllText("data/config_example.json", JsonConvert.SerializeObject(new Configuration(), Formatting.Indented)); if (!File.Exists("data/config.json")) { File.Copy("data/config_example.json", "data/config.json"); } File.WriteAllText("credentials_example.json", JsonConvert.SerializeObject(new Credentials(), Formatting.Indented)); } catch { Console.WriteLine("Failed writing credentials_example.json or data/config_example.json"); } try { Config = JsonConvert.DeserializeObject <Configuration> (File.ReadAllText("data/config.json", Encoding.UTF8)); Config.Quotes = JsonConvert.DeserializeObject <List <Quote> > (File.ReadAllText("data/quotes.json")); Config.PokemonTypes = JsonConvert.DeserializeObject <List <PokemonType> > (File.ReadAllText("data/PokemonTypes.json")); } catch (Exception ex) { Console.WriteLine("Einstellungen konnten nicht geladen werden."); Console.WriteLine(ex); Console.ReadKey(); return; } try { //load credentials from credentials.json Creds = JsonConvert.DeserializeObject <Credentials> (File.ReadAllText("credentials.json")); } catch (Exception ex) { Console.WriteLine($"Failed to load stuff from credentials.json, RTFM\n{ex.Message}"); Console.ReadKey(); return; } //if password is not entered, prompt for password if (string.IsNullOrWhiteSpace(Creds.Token)) { Console.WriteLine("Kein Token gesetzt. Bitte gib deinen Bot-Token ein:\n"); Creds.Token = Console.ReadLine(); } Console.WriteLine(string.IsNullOrWhiteSpace(GetRndGoogleAPIKey()) ? "Kein Google Api Key gefunden. Du kannst keine Musik benutzen und Links werden nicht gekürzt." : "Google API key vorhanden."); Console.WriteLine(string.IsNullOrWhiteSpace(Creds.TrelloAppKey) ? "Kein trello appkey gefunden. Du kannst keine trello Befehle benutzen." : "Trello app key vorhanden."); Console.WriteLine(Config.ForwardMessages != true ? "Keine Weiterleitung von Nachrichten." : "Nachrichten werden weitergeleitet."); Console.WriteLine(string.IsNullOrWhiteSpace(Creds.SoundCloudClientID) ? "Keine Soundcloud Client ID gefunden. Soundcloud Streaming ist deaktiviert." : "SoundCloud Streaming aktiviert."); Console.WriteLine(string.IsNullOrWhiteSpace(Creds.OsuAPIKey) ? "Kein osu! API Key gefunden. Song & Top Score Suche werden nicht funktionieren. Benutzer Suche ist verwendbar." : "osu! API Key gefunden."); BotMention = $"<@{Creds.BotId}>"; //create new discord client and log Client = new DiscordClient(new DiscordConfigBuilder() { MessageCacheSize = 10, ConnectionTimeout = 120000, LogLevel = LogSeverity.Warning, LogHandler = (s, e) => Console.WriteLine($"Severity: {e.Severity}" + $"Message: {e.Message}" + $"ExceptionMessage: {e.Exception?.Message ?? "-"}"), }); //create a command service var commandService = new CommandService(new CommandServiceConfigBuilder { AllowMentionPrefix = false, CustomPrefixHandler = m => 0, HelpMode = HelpMode.Disabled, ErrorHandler = async(s, e) => { if (e.ErrorType != CommandErrorType.BadPermissions) { return; } if (string.IsNullOrWhiteSpace(e.Exception?.Message)) { return; } try { await e.Channel.SendMessage(e.Exception.Message).ConfigureAwait(false); } catch { } } }); //reply to personal messages and forward if enabled. Client.MessageReceived += Client_MessageReceived; //add command service Client.AddService <CommandService> (commandService); //create module service var modules = Client.AddService <ModuleService> (new ModuleService()); //add audio service Client.AddService <AudioService> (new AudioService(new AudioServiceConfigBuilder() { Channels = 2, EnableEncryption = false, Bitrate = 128, })); AppDomain.CurrentDomain.ProcessExit += (s, e) => { MidnightBot.shutdownGracefully(); }; //install modules modules.Add(new HelpModule(), "Help", ModuleFilter.None); modules.Add(new AdministrationModule(), "Administration", ModuleFilter.None); modules.Add(new UtilityModule(), "Utility", ModuleFilter.None); modules.Add(new PermissionModule(), "Permissions", ModuleFilter.None); modules.Add(new Conversations(), "Conversations", ModuleFilter.None); modules.Add(new GamblingModule(), "Gambling", ModuleFilter.None); modules.Add(new GamesModule(), "Games", ModuleFilter.None); modules.Add(new LevelModule(), "Level", ModuleFilter.None); modules.Add(new MusicModule(), "Music", ModuleFilter.None); modules.Add(new SearchesModule(), "Searches", ModuleFilter.None); modules.Add(new ExtraModule(), "Extra", ModuleFilter.None); modules.Add(new PokemonModule(), "Pokegame", ModuleFilter.None); modules.Add(new TranslatorModule(), "Translator", ModuleFilter.None); modules.Add(new MemeModule(), "Memes", ModuleFilter.None); modules.Add(new NSFWModule(), "NSFW", ModuleFilter.None); modules.Add(new SoundsModule(), "Sounds", ModuleFilter.None); modules.Add(new ClashOfClansModule(), "ClashOfClans", ModuleFilter.None); modules.Add(new CustomReactionsModule(), "Customreactions", ModuleFilter.None); if (!string.IsNullOrWhiteSpace(Creds.TrelloAppKey)) { modules.Add(new TrelloModule(), "Trello", ModuleFilter.None); } //run the bot Client.ExecuteAndWait(async() => { Console.WriteLine("Bitte warte während der Bot startet..."); try { await Client.Connect(Creds.Token).ConfigureAwait(false); } catch (Exception ex) { Console.WriteLine($"Token ist fehlerhaft. Setze keinen Token wenn du keinen offiziellen BOT Account bestitzt."); Console.WriteLine(ex); Console.ReadKey(); return; } //Console.Write("Startvorgang dauert 10 Sekunden: "); //for(int i=10;i!=0;i--) //{ // Console.Write(i + " "); // await Task.Delay(1000).ConfigureAwait(false); //} //Console.WriteLine(); //await Task.Delay(10000).ConfigureAwait(false); Console.WriteLine("-----------------"); Console.WriteLine(await MidnightStats.Instance.GetStats().ConfigureAwait(false)); Console.WriteLine("-----------------"); OwnerPrivateChannels = new List <Channel>(Creds.OwnerIds.Length); foreach (var id in Creds.OwnerIds) { try { OwnerPrivateChannels.Add(await Client.CreatePrivateChannel(id).ConfigureAwait(false)); } catch { Console.WriteLine($"Konnte keinen privaten Channel mit dem Owner, welcher mit der ID {id} in der credentials.json gelistet ist"); } } //foreach (var ch in MidnightBot.Client.Servers.Select (s => s.DefaultChannel)) //{ // await ch.SendMessage ("`Hallo. Ich bin wieder da!`"); //} Client.ClientAPI.SendingRequest += (s, e) => { var request = e.Request as Discord.API.Client.Rest.SendMessageRequest; if (request == null) { return; } // meew0 is magic request.Content = request.Content?.Replace("@everyone", "@everyοne").Replace("@here", "@һere") ?? "_error_"; if (string.IsNullOrWhiteSpace(request.Content)) { e.Cancel = true; } }; //await Task.Delay(90000); PermissionsHandler.Initialize(); Console.Title = "Midnight Bot | Connected"; Console.WriteLine("Bot ist initialisiert."); MidnightBot.Ready = true; MidnightBot.OnReady(); }); Console.WriteLine("Beende..."); Console.ReadKey(); }
internal override void Init(CommandGroupBuilder cgb) { cgb.CreateCommand(Module.Prefix + "chnlfilterwords") .Alias(Module.Prefix + "cfw") .Description("Enables or disables automatic deleting of messages containing banned words on the channel." + "If no channel supplied, it will default to current one. Use ALL to apply to all existing channels at once." + $" | `{Prefix}cfw enable #general-chat`") .Parameter("bool") .Parameter("channel", ParameterType.Optional) .Do(async e => { try { var state = PermissionHelper.ValidateBool(e.GetArg("bool")); var chanStr = e.GetArg("channel")?.ToLowerInvariant().Trim(); if (chanStr != "all") { var chan = string.IsNullOrWhiteSpace(chanStr) ? e.Channel : PermissionHelper.ValidateChannel(e.Server, chanStr); await PermissionsHandler.SetChannelWordPermission(chan, state).ConfigureAwait(false); await e.Channel.SendMessage($"Word filtering has been **{(state ? "enabled" : "disabled")}** for **{chan.Name}** channel.").ConfigureAwait(false); return; } //all channels foreach (var curChannel in e.Server.TextChannels) { await PermissionsHandler.SetChannelWordPermission(curChannel, state).ConfigureAwait(false); } await e.Channel.SendMessage($"Word filtering has been **{(state ? "enabled" : "disabled")}** for **ALL** channels.").ConfigureAwait(false); } catch (Exception ex) { await e.Channel.SendMessage($"💢 Error: {ex.Message}").ConfigureAwait(false); } }); cgb.CreateCommand(Module.Prefix + "addfilterword") .Alias(Module.Prefix + "afw") .Description("Adds a new word to the list of filtered words" + $" | `{Prefix}afw poop`") .Parameter("word", ParameterType.Unparsed) .Do(async e => { try { var word = e.GetArg("word"); if (string.IsNullOrWhiteSpace(word)) { return; } await PermissionsHandler.AddFilteredWord(e.Server, word.ToLowerInvariant().Trim()).ConfigureAwait(false); await e.Channel.SendMessage($"Successfully added new filtered word.").ConfigureAwait(false); } catch (Exception ex) { await e.Channel.SendMessage($"💢 Error: {ex.Message}").ConfigureAwait(false); } }); cgb.CreateCommand(Module.Prefix + "rmvfilterword") .Alias(Module.Prefix + "rfw") .Description("Removes the word from the list of filtered words" + $" | `{Prefix}rw poop`") .Parameter("word", ParameterType.Unparsed) .Do(async e => { try { var word = e.GetArg("word"); if (string.IsNullOrWhiteSpace(word)) { return; } await PermissionsHandler.RemoveFilteredWord(e.Server, word.ToLowerInvariant().Trim()).ConfigureAwait(false); await e.Channel.SendMessage($"Successfully removed filtered word.").ConfigureAwait(false); } catch (Exception ex) { await e.Channel.SendMessage($"💢 Error: {ex.Message}").ConfigureAwait(false); } }); cgb.CreateCommand(Module.Prefix + "lstfilterwords") .Alias(Module.Prefix + "lfw") .Description("Shows a list of filtered words" + $" | `{Prefix}lfw`") .Do(async e => { try { Classes.ServerPermissions serverPerms; if (!PermissionsHandler.PermissionsDict.TryGetValue(e.Server.Id, out serverPerms)) { return; } await e.Channel.SendMessage($"There are `{serverPerms.Words.Count}` filtered words.\n" + string.Join("\n", serverPerms.Words)).ConfigureAwait(false); } catch (Exception ex) { await e.Channel.SendMessage($"💢 Error: {ex.Message}").ConfigureAwait(false); } }); cgb.CreateCommand(Module.Prefix + "srvrfilterwords") .Alias(Module.Prefix + "sfw") .Description($"Enables or disables automatic deleting of messages containing forbidden words on the server. | `{Prefix}sfw disable`") .Parameter("bool") .Do(async e => { try { var state = PermissionHelper.ValidateBool(e.GetArg("bool")); await PermissionsHandler.SetServerWordPermission(e.Server, state).ConfigureAwait(false); await e.Channel.SendMessage($"Word filtering has been **{(state ? "enabled" : "disabled")}** on this server.") .ConfigureAwait(false); } catch (Exception ex) { await e.Channel.SendMessage($"💢 Error: {ex.Message}").ConfigureAwait(false); } }); }
private void KickBanHandler(AdminQueryEvent ev) { ServerRoles serverRoles = ((UnityEngine.GameObject)ev.Admin.GetGameObject()).GetComponent <ServerRoles>(); PermissionsHandler permissionsHandler = ServerStatic.GetPermissionsHandler(); if ((permissionsHandler.StaffAccess && serverRoles.Staff) || (permissionsHandler.ManagersAccess && serverRoles.RaEverywhere) || (permissionsHandler.BanningTeamAccess && serverRoles.RaEverywhere)) { return; } Server server = PluginManager.Manager.Server; if (plugin.GetConfigBool("AP_HIERARCHY_ENABLE")) { bool isHigher = true; string[] queryArgs = ev.Query.Split(' '); if (queryArgs.Length > 1) { List <Player> playerList = server.GetPlayers(""); string[] players = queryArgs[1].Split('.'); playerList = playerList.FindAll(p => { if (Array.IndexOf(players, p.PlayerId.ToString()) > -1) { return(true); } return(false); }); if (playerList.Count > 0) { foreach (Player player in playerList) { if (!checkHierarchy(ev.Admin, player)) { isHigher = false; } } } } if (!isHigher) { ev.Successful = false; ev.Handled = true; ev.Output = "Player is higher rank than you!"; } } if (plugin.GetConfigBool("AP_DISABLE")) { bool isHigher = true; string[] queryArgs = ev.Query.Split(' '); if (queryArgs.Length > 1) { List <Player> playerList = new List <Player>(); foreach (string plyID in queryArgs[1].Split('.')) { playerList.AddRange(server.GetPlayers(plyID)); } if (playerList.Count > 0) { foreach (Player player in playerList) { if (!checkHierarchy(ev.Admin, player)) { isHigher = false; } } } } if (!isHigher) { ev.Successful = false; ev.Handled = true; ev.Output = "Player is higher rank than you!"; } } string perm = ""; string[] args = ev.Query.Split(' '); if (args.Length < 3) { return; } int time = Int32.Parse(args[args.Length - 1]); if (time <= 0) { perm = "AP_RM_PLAYER_KICK"; } else if (time > 0 && time < 60) { perm = "AP_RM_PLAYER_MINUTES"; } else if (time > 59 && time < 1440) { perm = "AP_RM_PLAYER_HOURS"; } else if (time > 1439 && time < 525600) { perm = "AP_RM_PLAYER_DAYS"; } else if (time > 525599) { perm = "AP_RM_PLAYER_YEARS"; } else { ev.Successful = false; ev.Handled = true; return; } if (!hasPerm(ev.Admin, ev.Admin.GetUserGroup().Name, perm)) { ev.Successful = false; ev.Handled = true; ev.Output = "You Don't Have Permission to do that! You require the permission " + perm + "!"; } }