void IModule.Install(ModuleManager manager) { _manager = manager; _client = _manager.Client; manager.CreateCommands("colors", group => { //group.SetAlias("colours"); //TODO: add group alias and absolute vs relative alias group.CreateCommand("list") .Description("Gives a list of all available username colors.") .Do(async e => { string text = $"{Format.Bold("Available Colors:")}\n" + string.Join(", ", _colors.Select(x => '`' + x.Name + '`')); await _client.Reply(e, text); }); group.CreateCommand("set") .Parameter("color") .Description("Sets your username to a custom color.") .Do(e => SetColor(e, e.User, e.Args[0])); group.CreateCommand("set") .Parameter("user") .Parameter("color") .MinPermissions((int)PermissionLevel.BotOwner) .Description("Sets another user's name to a custom color.") .Do(e => { User user = e.Server.FindUsers(e.Args[0]).FirstOrDefault(); if (user == null) return _client.ReplyError(e, "Unknown user"); return SetColor(e, user, e.Args[1]); }); group.CreateCommand("clear") .Description("Removes your username color, returning it to default.") .Do(async e => { if (!e.Server.CurrentUser.ServerPermissions.ManageRoles) { await _client.ReplyError(e, "This command requires the bot have Manage Roles permission."); return; } var otherRoles = GetOtherRoles(e.User); await e.User.Edit(roles: otherRoles); await _client.Reply(e, $"Reset username color."); }); }); }
void IModule.Install(ModuleManager manager) { _manager = manager; _client = manager.Client; _service = manager.Client.Modules(true); manager.CreateCommands("modules", group => { group.MinPermissions((int)PermissionLevel.BotOwner); group.CreateCommand("list") .Description("Gives a list of all available modules.") .Do(async e => { string text = "Available Modules: " + string.Join(", ", _service.Modules.Select(x => x.Id)); await _client.Reply(e, text); }); group.CreateCommand("enable") .Description("Enables a module for this server.") .Parameter("module") .PublicOnly() .Do(e => { var module = GetModule(e.Args[0]); if (module == null) { _client.ReplyError(e, "Unknown module"); return; } if (module.FilterType == ModuleFilter.None || module.FilterType == ModuleFilter.AlwaysAllowPrivate) { _client.ReplyError(e, "This module is global and cannot be enabled/disabled."); return; } if (!module.FilterType.HasFlag(ModuleFilter.ServerWhitelist)) { _client.ReplyError(e, "This module doesn't support being enabled for servers."); return; } var server = e.Server; if (!module.EnableServer(server)) { _client.ReplyError(e, $"Module {module.Id} was already enabled for server {server.Name}."); return; } _client.Reply(e, $"Module {module.Id} was enabled for server {server.Name}."); }); group.CreateCommand("disable") .Description("Disables a module for this server.") .Parameter("module") .PublicOnly() .Do(e => { var module = GetModule(e.Args[0]); if (module == null) { _client.ReplyError(e, "Unknown module"); return; } if (module.FilterType == ModuleFilter.None || module.FilterType == ModuleFilter.AlwaysAllowPrivate) { _client.ReplyError(e, "This module is global and cannot be enabled/disabled."); return; } if (!module.FilterType.HasFlag(ModuleFilter.ServerWhitelist)) { _client.ReplyError(e, "This module doesn't support being enabled for servers."); return; } var server = e.Server; if (!module.DisableServer(server)) { _client.ReplyError(e, $"Module {module.Id} was not enabled for server {server.Name}."); return; } _client.Reply(e, $"Module {module.Id} was disabled for server {server.Name}."); }); }); }
private void Start(string[] args) { GlobalSettings.Load(); //Set up the base client itself with no voice and small message queues _client = new DiscordClient(new DiscordConfig { AppName = "VoltBot", AppUrl = "https://github.com/RogueException/DiscordBot", AppVersion = DiscordConfig.LibVersion, LogLevel = LogSeverity.Info, MessageCacheSize = 0, UsePermissionsCache = false }) //** Core Services **// //These are services adding functionality from other Discord.Net.XXX packages //Enable commands on this bot and activate the built-in help command .UsingCommands(new CommandServiceConfig { CommandChar = '~', HelpMode = HelpMode.Public }) //Enable command modules .UsingModules() //Enable audio support .UsingAudio(new AudioServiceConfig { Mode = AudioMode.Outgoing, EnableMultiserver = false, EnableEncryption = true, Bitrate = 512, BufferLength = 10000 }) //** Command Permission Services **// // These allow you to use permission checks on commands or command groups, or apply a permission globally (such as a blacklist) //Add a blacklist service so we can add people that can't run any commands. We have used a whitelist instead to restrict it to just us. .UsingGlobalBlacklist() //.EnableGlobalWhitelist(GlobalSettings.Users.DevId)) //Assign users to our own role system based on their permissions in the server/channel a command is run in. .UsingPermissionLevels((u, c) => { if (u.Id == GlobalSettings.Users.DevId) return (int)PermissionLevel.BotOwner; if (u.Server != null) { if (u == c.Server.Owner) return (int)PermissionLevel.ServerOwner; var serverPerms = u.ServerPermissions; if (serverPerms.ManageRoles) return (int)PermissionLevel.ServerAdmin; if (serverPerms.ManageMessages && serverPerms.KickMembers && serverPerms.BanMembers) return (int)PermissionLevel.ServerModerator; var channelPerms = u.GetPermissions(c); if (channelPerms.ManagePermissions) return (int)PermissionLevel.ChannelAdmin; if (channelPerms.ManageMessages) return (int)PermissionLevel.ChannelModerator; } return (int)PermissionLevel.User; }) //** Helper Services**// //These are used by the modules below, and will likely be removed in the future .AddService<SettingsService>() .AddService<HttpService>() //** Command Modules **// //Modules allow for events such as commands run or user joins to be filtered to certain servers/channels, as well as provide a grouping mechanism for commands .AddModule<AdminModule>("Admin", ModuleFilter.ServerWhitelist) .AddModule<ColorsModule>("Colors", ModuleFilter.ServerWhitelist) .AddModule<FeedModule>("Feeds", ModuleFilter.ServerWhitelist) .AddModule<GithubModule>("Repos", ModuleFilter.ServerWhitelist) .AddModule<ModulesModule>("Modules", ModuleFilter.None) .AddModule<PublicModule>("Public", ModuleFilter.None) .AddModule<TwitchModule>("Twitch", ModuleFilter.ServerWhitelist); //.AddModule(new ExecuteModule(env, exporter), "Execute", ModuleFilter.ServerWhitelist); //** Events **// _client.Log.Message += (s, e) => WriteLog(e); //Display errors that occur when a user tries to run a command //(In this case, we hide argcount, parsing and unknown command errors to reduce spam in servers with multiple bots) _client.Commands().CommandErrored += (s, e) => { string msg = e.Exception?.GetBaseException().Message; if (msg == null) //No exception - show a generic message { switch (e.ErrorType) { case CommandErrorType.Exception: //msg = "Unknown error."; break; case CommandErrorType.BadPermissions: msg = "You do not have permission to run this command."; break; case CommandErrorType.BadArgCount: //msg = "You provided the incorrect number of arguments for this command."; break; case CommandErrorType.InvalidInput: //msg = "Unable to parse your command, please check your input."; break; case CommandErrorType.UnknownCommand: //msg = "Unknown command."; break; } } if (msg != null) { _client.ReplyError(e, msg); _client.Log.Error("Command", msg); } }; //Log to the console whenever someone uses a command _client.Commands().CommandExecuted += (s, e) => _client.Log.Info("Command", $"{e.Command.Text} ({e.User.Name})"); //Used to load private modules outside of this repo #if PRIVATE PrivateModules.Install(_client); #endif //** Run **// #if !DNXCORE50 Console.Title = $"{_client.Config.AppName} v{_client.Config.AppVersion} (Discord.Net v{DiscordConfig.LibVersion})"; #endif //Convert this method to an async function and connect to the server //DiscordClient will automatically reconnect once we've established a connection, until then we loop on our end //Note: Run is only needed for Console projects as Main can't be declared as async. UI/Web applications should *not* use this function. _client.Run(async () => { while (true) { try { await _client.Connect(GlobalSettings.Discord.Email, GlobalSettings.Discord.Password); _client.SetGame("Discord.Net"); break; } catch (Exception ex) { _client.Log.Error($"Login Failed", ex); await Task.Delay(_client.Config.FailedReconnectDelay); } } }); }
void IModule.Install(ModuleManager manager) { _manager = manager; _client = manager.Client; manager.CreateCommands("", group => { group.PublicOnly(); group.CreateCommand("kick") .Description("Kicks a user from this server.") .Parameter("user") .Parameter("discriminator", ParameterType.Optional) .MinPermissions((int)PermissionLevel.ServerModerator) .Do(async e => { var user = await _client.FindUser(e, e.Args[0], e.Args[1]); if (user == null) return; await user.Kick(); await _client.Reply(e, $"Kicked user {user.Name}."); }); group.CreateCommand("ban") .Description("Bans a user from this server.") .Parameter("user") .Parameter("discriminator", ParameterType.Optional) .MinPermissions((int)PermissionLevel.ServerModerator) .Do(async e => { var user = await _client.FindUser(e, e.Args[0], e.Args[1]); if (user == null) return; await user.Server.Ban(user); await _client.Reply(e, $"Banned user {user.Name}."); }); group.CreateCommand("mute") .Parameter("user") .Parameter("discriminator", ParameterType.Optional) .MinPermissions((int)PermissionLevel.ServerModerator) .Do(async e => { var user = await _client.FindUser(e, e.Args[0], e.Args[1]); if (user == null) return; await user.Edit(isMuted: true); await _client.Reply(e, $"Muted user {user.Name}."); }); group.CreateCommand("unmute") .Parameter("user") .Parameter("discriminator", ParameterType.Optional) .MinPermissions((int)PermissionLevel.ServerModerator) .Do(async e => { var user = await _client.FindUser(e, e.Args[0], e.Args[1]); if (user == null) return; await user.Edit(isMuted: false); await _client.Reply(e, $"Unmuted user {user.Name}."); }); group.CreateCommand("deafen") .Parameter("user") .Parameter("discriminator", ParameterType.Optional) .MinPermissions((int)PermissionLevel.ServerModerator) .Do(async e => { var user = await _client.FindUser(e, e.Args[0], e.Args[1]); if (user == null) return; await user.Edit(isDeafened: true); await _client.Reply(e, $"Deafened user {user.Name}."); }); group.CreateCommand("undeafen") .Parameter("user") .Parameter("discriminator", ParameterType.Optional) .MinPermissions((int)PermissionLevel.ServerModerator) .Do(async e => { var user = await _client.FindUser(e, e.Args[0], e.Args[1]); if (user == null) return; await user.Edit(isDeafened: false); await _client.Reply(e, $"Undeafened user {user.Name}."); }); group.CreateCommand("cleanup") .Parameter("count") .Parameter("user", ParameterType.Optional) .Parameter("discriminator", ParameterType.Optional) .MinPermissions((int)PermissionLevel.ChannelModerator) .Do(async e => { int count = int.Parse(e.Args[0]); string username = e.Args[1]; string discriminator = e.Args[2]; User[] users = null; if (username != "") { users = await _client.FindUsers(e, username, discriminator); if (users == null) return; } IEnumerable<Message> msgs; var cachedMsgs = e.Channel.Messages; if (cachedMsgs.Count() < count) msgs = (await e.Channel.DownloadMessages(count)); else msgs = e.Channel.Messages.OrderByDescending(x => x.Timestamp).Take(count); if (username != "") msgs = msgs.Where(x => users.Contains(x.User)); if (msgs.Any()) { foreach (var msg in msgs) await msg.Delete(); await _client.Reply(e, $"Cleaned up {msgs.Count()} messages."); } else await _client.ReplyError(e, $"No messages found."); }); }); }