public void AddAndUseCommand() { Assert.False(CustomCommand.CommandExists(commandName)); CustomCommand.CustomCommands.Add(new CustomCommand(author, commandName, commandContent)); Assert.True(CustomCommand.CommandExists(commandName)); string result = CustomCommand.UseCustomCommand(commandName, argument, author, userList); Assert.Equal(result, "~~~" + argument + " " + randomUser + "!"); }
private static async Task CheckForCustomCommand(MessageCreateEventArgs a) { string[] split = a.Message.Content.Split(new char[] { ' ' }, 2); string arguments = split.Length > 1 ? split[1] : string.Empty; string senderUsername = Useful.GetUsername(a); string command = split[0].TrimStart(Settings.Default.commandChar); if (CustomCommand.CommandExists(command)) { string result = CustomCommand.UseCustomCommand(command, arguments, senderUsername, GetUserList(a.Channel.Guild, senderUsername)); if (!string.IsNullOrEmpty(result)) { await a.Message.RespondAsync(result).ConfigureAwait(false); } } }
/// <summary> /// Called when a message is received in either a channel or DM. /// Checks if the message contains a banned word and purges and warns if it does. /// If the message is a command, checks if the guild has a bot spam channel and if it does, if the message is posted in there. /// Gives one gold per non-command message sent. /// </summary> /// <param name="MessageParam">Information about the message sent.</param> public async Task Client_MessageReceived(SocketMessage MessageParam) { SocketUserMessage Message = MessageParam as SocketUserMessage; SocketCommandContext Context = new SocketCommandContext(Client, Message); //Make sure the message isn't empty if (Context.Message == null || Context.User.IsBot) { return; } //Channel to send the chat logs in ulong channel = Data.GetChatLogChannel(Context.Guild.Id); if (channel != 0) { try { SocketTextChannel channelPost = Context.Guild.GetTextChannel(channel); //Format: Name#1111: "This is a sentence." -- #channel at 1/11/1111 1:11:11 PM EST timeUtc = DateTime.UtcNow; today = TimeZoneInfo.ConvertTimeFromUtc(timeUtc, easternZone); if (Context.Message.Content == "") { await channelPost.SendMessageAsync($"{Context.Message.Author} uploaded an image. -- <#{Context.Channel.Id}> at {today} EST"); } else { await channelPost.SendMessageAsync($"{Context.Message.Author}: \"{Context.Message}\" -- <#{Context.Channel.Id}> at {today} EST"); } } catch (Exception) { } } //If message is blank (picture/file), return after chat log if (Context.Message.Content == "") { return; } //Get the permissions of the user for use in checking for banned words and checking the bot spam channel SocketGuildUser User = Context.User as SocketGuildUser; //Make sure the message has no banned words //If it contains a banned word, purge the message and issue a warning //Three warnings and offender gets kicked if (Data.GetBannedWords(Context.Guild.Id).Length > 0 && User.GuildPermissions.KickMembers == false) { foreach (string word in Data.GetBannedWords(Context.Guild.Id)) { if (Message.Content.ToLower().Contains(word)) { try { //get the author of the message IGuildUser GuildUser = (IGuildUser)Message.Author; ulong userid = GuildUser.Id; ulong guildid = Context.Guild.Id; string username = GuildUser.Username; //Get the message and delete it, issue a warning await(Context.Channel as SocketTextChannel).DeleteMessageAsync(Context.Message.Id); await Data.AddWarnings(Context.User.Id, Context.Guild.Id, Context.User.Username); int amountOfWarnings = Data.GetWarnings(userid, guildid); //For the mod log to know which moderator to put SocketUser Nephry = Context.Guild.GetUser(322806920203337740); //If warnings is 3 or more, kick the offender if bot has kick permissions if (amountOfWarnings >= 3) { IRole nephry = null; foreach (IRole role in Context.Guild.Roles) { if (role.Name == "Nephry") { nephry = role; break; } } if (nephry == null) { return; } if (nephry.Permissions.KickMembers == false) { return; } await GuildUser.SendMessageAsync("You were kicked for accumulating too many warnings."); await Context.Channel.SendMessageAsync($"{GuildUser.Mention} has been kicked for accumulating too many warnings."); await GuildUser.KickAsync("Accumulated too many warnings"); await Data.RemoveWarnings(userid, guildid, username, amountOfWarnings); await ModLog.PostInModLog(Context.Guild, "Auto-Kicked", Nephry, GuildUser, "Accumulated too many warnings."); return; } await Context.Channel.SendMessageAsync($"{Context.User.Mention}, you have been warned for using inappropriate language. Please type \"!getbannedwords\" " + $"to see a list of banned words in this server. " + $"You now have {Data.GetWarnings(Context.User.Id, Context.Guild.Id)} warning(s)."); await ModLog.PostInModLog(Context.Guild, "Auto-Warn", Nephry, GuildUser, "Used inappropriate language."); return; } catch (Exception) { } } } } int ArgPos = 0; //Make sure the message doesn't start with ! for the gold bonus if (!Message.HasCharPrefix('!', ref ArgPos)) { await Data.SaveGold(Context.User.Id, 1, Context.Guild.Id, Context.User.Username); //Add one gold per message } //If message does not start with ! or bot mention, return if (!(Message.HasCharPrefix('!', ref ArgPos) || Message.HasMentionPrefix(Client.CurrentUser, ref ArgPos))) { return; } //Get the bot spam channel if there is one assigned //and make sure the command is in that channel if (Data.GetBotSpamChannel(Context.Guild.Id) != 0) { //put channel bot spam here and make sure the message is either in the correct channel, has kick or admin permissions if (Context.Channel.Id == Data.GetBotSpamChannel(Context.Guild.Id) || User.GuildPermissions.KickMembers == true || User.GuildPermissions.Administrator == true) { IResult Results = await Commands.ExecuteAsync(Context, ArgPos, null); if (!Results.IsSuccess) { CustomCommand customCommands = new CustomCommand(); await customCommands.UseCustomCommand(Context); } return; } else { return; } } //Search for a matching command and execute it IResult Result = await Commands.ExecuteAsync(Context, ArgPos, null); if (!Result.IsSuccess) { CustomCommand customCommands = new CustomCommand(); //If a hard-coded command isn't found, use the server's custom commands instead await customCommands.UseCustomCommand(Context); } }
private static async Task MainAsync(string[] args) { string token = args[0]; bool quit = false; bool tryReconnect = false; string botName = string.Empty; //TODO: This should be fixed once .net Core 3.0 is released /*if (Settings.Default.UpgradeNeeded) * { * Settings.Default.Upgrade(); * Settings.Default.UpgradeNeeded = false; * Settings.Default.Save(); * }*/ Console.WriteLine(DateTime.Now.ToString("[HH:mm:ss] ", CultureInfo.CreateSpecificCulture("en-GB")) + "Starting..."); if (string.IsNullOrWhiteSpace(Settings.Default.apikey)) { string api = string.Empty; if (args.Length > 1) { api = args[1]; } else { Console.WriteLine("Add api key for youtube search (or enter to ignore): "); api = Console.ReadLine(); } if (!string.IsNullOrWhiteSpace(api)) { Settings.Default.apikey = api; //TODO: This should be fixed once .net Core 3.0 is released //Settings.Default.Save(); } } if (string.IsNullOrWhiteSpace(Settings.Default.CleverbotAPI)) { string api = string.Empty; if (args.Length > 2) { api = args[2]; } else { Console.WriteLine("Add api key for Cleverbot (or enter to ignore): "); api = Console.ReadLine(); } if (!string.IsNullOrWhiteSpace(api)) { Settings.Default.CleverbotAPI = api; //TODO: This should be fixed once .net Core 3.0 is released //Settings.Default.Save(); } } GetDiscordClient = new DiscordClient(new DiscordConfiguration { Token = token, TokenType = TokenType.Bot }); GetDiscordClient.SocketErrored += async a => { tryReconnect = true; await Console.Out.WriteLineAsync(DateTime.Now.ToString("[HH:mm:ss] ", CultureInfo.CreateSpecificCulture("en-GB")) + "Error: " + a.Exception.Message).ConfigureAwait(false); }; GetDiscordClient.Ready += async a => { await Console.Out.WriteLineAsync(DateTime.Now.ToString("[HH:mm:ss] ", CultureInfo.CreateSpecificCulture("en-GB")) + "Ready!").ConfigureAwait(false); tryReconnect = false; }; GetDiscordClient.UnknownEvent += async unk => { await Console.Out.WriteLineAsync(DateTime.Now.ToString("[HH:mm:ss] ", CultureInfo.CreateSpecificCulture("en-GB")) + "Unknown Event: " + unk.EventName).ConfigureAwait(false); }; GetDiscordClient.MessageCreated += async e => { if (e.Message.Content.StartsWith("!quit", StringComparison.OrdinalIgnoreCase)) { DiscordMember author = await e.Guild.GetMemberAsync(e.Author.Id).ConfigureAwait(false); bool isBotAdmin = Useful.MemberIsBotOperator(author); if (author.IsOwner || isBotAdmin) { quit = true; Console.WriteLine(DateTime.Now.ToString("[HH:mm:ss] ", CultureInfo.CreateSpecificCulture("en-GB")) + "Quitting..."); } } //CustomCommands else if (e.Message.Content.StartsWith('!')) { string arguments = string.Empty; string[] split = e.Message.Content.Split(new char[] { ' ' }, 2); string command = split[0]; if (split.Length > 1) { arguments = split[1]; } string nick = ((DiscordMember)e.Message.Author).DisplayName; List <string> listU = Useful.GetOnlineNames(e.Channel.Guild); string result = CustomCommand.UseCustomCommand(command.TrimStart('!'), arguments, nick, listU); if (!string.IsNullOrEmpty(result)) { await e.Message.RespondAsync(result).ConfigureAwait(false); } } //Bot Talk and Cleverbot else if (e.Message.Content.StartsWith(botName + ",", StringComparison.OrdinalIgnoreCase)) { if (e.Message.Content.EndsWith('?')) { } else { await Think(e, botName).ConfigureAwait(false); } } else if (e.Message.Content.EndsWith(botName, StringComparison.OrdinalIgnoreCase)) { await Think(e, botName).ConfigureAwait(false); } //waifunator if (!string.IsNullOrWhiteSpace(e.Message.Content) && e.Message.Author.Id == Settings.Default.limid) //lims shitty id lul { if (e.Message.Content.Contains("wife", StringComparison.OrdinalIgnoreCase)) { await e.Message.CreateReactionAsync(DiscordEmoji.FromName(GetDiscordClient, ":regional_indicator_w:")).ConfigureAwait(false); await e.Message.CreateReactionAsync(DiscordEmoji.FromName(GetDiscordClient, ":regional_indicator_a:")).ConfigureAwait(false); await e.Message.CreateReactionAsync(DiscordEmoji.FromName(GetDiscordClient, ":regional_indicator_i:")).ConfigureAwait(false); await e.Message.CreateReactionAsync(DiscordEmoji.FromName(GetDiscordClient, ":regional_indicator_f:")).ConfigureAwait(false); await e.Message.CreateReactionAsync(DiscordEmoji.FromName(GetDiscordClient, ":regional_indicator_u:")).ConfigureAwait(false); } } //Update "last seen" for user that sent the message string username = ((DiscordMember)e.Message.Author).DisplayName.ToLower(CultureInfo.CreateSpecificCulture("en-GB")); Seen.MarkUserSeen(username); Seen.SaveSeen(Seen.SeenTime); //Ping users, leave this last cause it's sloooooooow await PingUser.SendPings(e).ConfigureAwait(false); }; //Register the commands defined on SekiCommands.cs commands = GetDiscordClient.UseCommandsNext(new CommandsNextConfiguration { StringPrefix = "!", CaseSensitive = false, EnableMentionPrefix = false }); commands.RegisterCommands <SekiCommands>(); //Connect to Discord await GetDiscordClient.ConnectAsync().ConfigureAwait(false); botName = GetDiscordClient.CurrentUser.Username; while (!quit) { if (tryReconnect) { try { await GetDiscordClient.DisconnectAsync().ConfigureAwait(false); } finally { Console.WriteLine(DateTime.Now.ToString("[HH:mm:ss] ", CultureInfo.CreateSpecificCulture("en-GB")) + "Attempting to Reconnect..."); await GetDiscordClient.ConnectAsync().ConfigureAwait(false); } } //Wait a bit await Task.Delay(10 * 1000).ConfigureAwait(false); } await GetDiscordClient.DisconnectAsync().ConfigureAwait(false); }