public Task OnMinutePassed(DateTime time) { if (birthdays != null) { foreach (Date date in birthdays) { // userID = 0 if the user hasn't set a date. if (date.userID == 0) { continue; } DateTime dateThisYear = new DateTime(DateTime.Now.Year, date.day.Month, date.day.Day, date.day.Hour, date.day.Minute, date.day.Second); if (DateTime.Now > dateThisYear && date.lastPassedYear != DateTime.Now.Year) { AnnounceBirthday(date); date.lastPassedYear = DateTime.Now.Year; UserConfiguration.SetSetting(date.userID, "Birthday", date); } } } return(Task.CompletedTask); }
public static void ChangeGameRole(SocketUser user, string gameName, bool add) { // When you need to use containskey, but want it to ignore case /shrug if (gameRoles.Where(x => x.Key.ToUpper() == gameName).Count() != 0 && UserConfiguration.GetSetting <bool> (user.Id, "AutoManageGameRoles")) { ulong roleID = gameRoles [gameName]; SocketRole role = Utility.GetServer().GetRole(roleID); if (role != null) { if (add) { Utility.SecureAddRole(user as SocketGuildUser, role); } else { Utility.SecureRemoveRole(user as SocketGuildUser, role); } } else { Logging.Log(Logging.LogType.WARNING, "Failed to find game role for " + gameName + " despite the data being present, please make sure the ID's match up as well."); } } }
public static async Task UpdateVoiceChannel(SocketVoiceChannel voice) { Game highestGame = new Game("", "", StreamType.NotStreaming); if (voice != null && allVoiceChannels.ContainsKey(voice.Id)) { VoiceChannel voiceChannel = allVoiceChannels [voice.Id]; List <SocketGuildUser> users = Utility.ForceGetUsers(voice.Id); if (voiceChannel.ignore) { return; } if (voice.Users.Count() == 0) { voiceChannel.Reset(); } else { if (voiceChannel.desiredMembers > 0) { if (users.Count >= voiceChannel.desiredMembers) { voiceChannel.SetStatus(VoiceChannel.VoiceChannelStatus.Full, false); } else { voiceChannel.SetStatus(VoiceChannel.VoiceChannelStatus.Looking, false); } } } Dictionary <Game, int> numPlayers = new Dictionary <Game, int> (); foreach (SocketGuildUser user in users) { if (UserConfiguration.GetSetting <bool> (user.Id, "AutoLooking") && users.Count == 1) { voiceChannel.SetStatus(VoiceChannel.VoiceChannelStatus.Looking, false); } if (user.Game.HasValue && user.IsBot == false) { if (numPlayers.ContainsKey(user.Game.Value)) { numPlayers [user.Game.Value]++; } else { numPlayers.Add(user.Game.Value, 1); } } } int highest = int.MinValue; for (int i = 0; i < numPlayers.Count; i++) { KeyValuePair <Game, int> value = numPlayers.ElementAt(i); if (value.Value > highest) { highest = value.Value; highestGame = value.Key; } } if (enableVoiceChannelTags) { GetTags(voiceChannel); } string tagsString = ""; foreach (VoiceChannelTag tag in voiceChannel.currentTags) { tagsString += tag.tagEmoji; } tagsString += tagsString.Length > 0 ? " " : ""; string [] splitVoice = voiceChannel.name.Split(';'); string possibleShorten = shortenChannelNames && splitVoice.Length > 1 ? splitVoice [1] : splitVoice [0]; int mixedLimit = highest >= 2 ? 2 : Utility.ForceGetUsers(voice.Id).Count == 1 ? int.MaxValue : 1; // Nested compact if statements? What could go wrong! string gameName = numPlayers.Where(x => x.Value >= mixedLimit).Count() > mixedLimit ? "Mixed Games" : gameNameReplacements.ContainsKey(highestGame.Name) ? gameNameReplacements[highestGame.Name] : highestGame.Name; // What even is this string newName; if (autoRenameChannels) { newName = gameName != "" ? tagsString + possibleShorten + " - " + gameName : tagsString + splitVoice [0]; } else { newName = tagsString + splitVoice [0]; } if (voiceChannel.customName != "") { newName = tagsString + possibleShorten + " - " + voiceChannel.customName; } // Trying to optimize API calls here, just to spare those poor souls at the Discord API HQ stuff if (voice.Name != newName) { Logging.Log(Logging.LogType.BOT, "Channel name updated: " + newName); await voice.ModifyAsync((delegate(VoiceChannelProperties properties) { properties.Name = newName; })); } voiceChannel.CheckLocker(); } }
public Task <Result> Execute(SocketUserMessage e) { bool result = UserConfiguration.ToggleBoolean(e.Author.Id, "AllowSnooping"); return(TaskResult(result, "Bot snooping enabled: " + result.ToString())); }
public Task <Result> Execute(SocketUserMessage e) { bool result = UserConfiguration.ToggleBoolean(e.Author.Id, "AutoManageGameRoles"); return(TaskResult(result, "Auto roles enabled: " + result.ToString())); }
public Task <Result> Execute(SocketUserMessage e) { bool result = UserConfiguration.ToggleBoolean(e.Author.Id, "AutoLooking"); return(TaskResult(result, "Autolooking on voice channels enabled: " + result.ToString())); }
public Task <Result> Execute(SocketUserMessage e) { bool result = UserConfiguration.ToggleBoolean(e.Author.Id, "AdvancedCommandsMode"); return(TaskResult(result, "Advanced commands mode enabled: " + result.ToString())); }
public Task <Result> Execute(SocketUserMessage e, CultureInfo info) { UserConfiguration.SetSetting(e.Author.Id, "Culture", info); return(TaskResult(info, "Successfully sat culture to " + info.DisplayName)); }
public object superDefaultValue; // The value default from the code. public override void Initialize() { base.Initialize(); UserConfiguration.AddCommand(this); }
/// <summary> /// Formatted for the danish format! /// </summary> public static bool TryParseDatetime(string input, ulong userID, out DateTime result) { CultureInfo danishCulture = new CultureInfo (UserConfiguration.GetSetting<string>(userID, "Culture")); return DateTime.TryParse (input, danishCulture.DateTimeFormat, DateTimeStyles.None, out result); }
public static async Task <FoundCommandResult> FindAndExecuteCommand(SocketMessage e, string commandName, List <string> arguements, Command [] commandList, int depth, bool printMessage, bool allowQuickCommands) { for (int i = 0; i < commandList.Length; i++) { if (commandList [i].command == commandName) { if (arguements.Count > 0 && arguements [0] == "?") { Command command = commandList [i]; if (command is CommandSet) { messageControl.SendMessage(e, command.GetHelp(e), command.allowInMain); } else { messageControl.SendEmbed(e.Channel, command.GetHelpEmbed(e, UserConfiguration.GetSetting <bool> (e.Author.Id, "AdvancedCommandsMode"))); } return(null); } else { FoundCommandResult result = new FoundCommandResult(await commandList [i].TryExecute(e as SocketUserMessage, depth, arguements.ToArray()), commandList [i]); if (result != null) { if (printMessage) { messageControl.SendMessage(e, result.result.message, result.command.allowInMain); } if (depth == 0) { CommandVariables.Clear(e.Id); } return(result); } } } } if (allowQuickCommands) { return(await FindAndExecuteCommand(e, commandName, arguements, quickCommands.ToArray(), depth, printMessage, false)); } return(null); }
public async Task Start(string [] args) { dataPath = AppContext.BaseDirectory + "/data/"; dataPath = dataPath.Replace('\\', '/'); InitializeDirectories(); Logging.Log(Logging.LogType.BOT, "Initializing bot.. Datapath: " + dataPath); BotConfiguration.Initialize(); Encryption.Initialize(); BotConfiguration.AddConfigurable(this); LoadConfiguration(); discordClient = new DiscordSocketClient(); messageControl = new MessageControl(); karma = new Karma(); new StreamingMonitor(); LegalJunk.Initialize(); Logging.Log(Logging.LogType.BOT, "Loading data.."); InitializeCommands(); UserConfiguration.Initialize(); InviteHandler.Initialize(); CommandChain.Initialize(); Permissions.Initialize(); AutoCommands.Initialize(); clock = new Clock(); InitializeData(); UserGameMonitor.Initialize(); bootedTime = DateTime.Now.AddSeconds(BOOT_WAIT_TIME); Logging.Log(Logging.LogType.BOT, "Setting up events.."); discordClient.MessageReceived += async(e) => { Logging.Log(Logging.LogType.CHAT, Utility.GetChannelName(e) + " says: " + e.Content); bool hideTrigger = false; if (e.Content.Length > 0 && ContainsCommandTrigger(e.Content, out hideTrigger)) { FindAndExecuteCommand(e, e.Content, commands, 0, true, true); } if (e.Author.Id != discordClient.CurrentUser.Id) { FindPhraseAndRespond(e); AutoCommands.RunEvent(AutoCommands.Event.MessageRecieved, e.Content, e.Channel.Id.ToString()); } if (e.Content.Length > 0 && hideTrigger) { e.DeleteAsync(); allowedDeletedMessages.Add(e.Content); } }; discordClient.MessageUpdated += async(cache, message, channel) => { Logging.Log(Logging.LogType.CHAT, "Message edited: " + Utility.GetChannelName(message as SocketMessage) + " " + message.Content); AutoCommands.RunEvent(AutoCommands.Event.MessageDeleted, message.Content, message.Channel.Id.ToString()); }; discordClient.MessageDeleted += async(cache, channel) => { IMessage message = await cache.GetOrDownloadAsync(); Logging.Log(Logging.LogType.CHAT, "Message deleted: " + Utility.GetChannelName(channel as SocketGuildChannel)); AutoCommands.RunEvent(AutoCommands.Event.MessageDeleted, channel.Id.ToString()); }; discordClient.UserJoined += async(e) => { Younglings.OnUserJoined(e); RestInviteMetadata possibleInvite = await InviteHandler.FindInviter(); Logging.Log(Logging.LogType.BOT, "User " + e.Username + " joined."); AutoCommands.RunEvent(AutoCommands.Event.UserJoined, e.Id.ToString()); SocketGuildUser inviter; if (possibleInvite != null) { inviter = Utility.GetServer().GetUser(possibleInvite.Inviter.Id); string joinMessage = Utility.SelectRandom(onUserJoinFromInviteMessage); messageControl.SendMessage(Utility.GetMainChannel() as SocketTextChannel, joinMessage.Replace("{USERNAME}", Utility.GetUserName(e)).Replace("{INVITERNAME}", Utility.GetUserName(inviter)), true); } else { string joinMessage = Utility.SelectRandom(onUserJoinMessage); messageControl.SendMessage(Utility.GetMainChannel() as SocketTextChannel, joinMessage.Replace("{USERNAME}", Utility.GetUserName(e)), true); } string [] welcomeMessage = SerializationIO.LoadTextFile(dataPath + "welcomemessage" + gitHubIgnoreType); string combined = ""; for (int i = 0; i < welcomeMessage.Length; i++) { combined += welcomeMessage [i] + "\n"; } await messageControl.SendMessage(e, combined); }; discordClient.UserLeft += (e) => { string leftMessage = Utility.SelectRandom(onUserLeaveMessage); Logging.Log(Logging.LogType.BOT, "User " + e.Username + " left."); AutoCommands.RunEvent(AutoCommands.Event.UserLeft, e.Id.ToString()); if (automaticLeftReason.ContainsKey(e.Id)) { leftMessage = $"**{Utility.GetUserName (e)}** left - " + automaticLeftReason [e.Id]; automaticLeftReason.Remove(e.Id); } messageControl.SendMessage(Utility.GetMainChannel() as SocketTextChannel, leftMessage.Replace("{USERNAME}", Utility.GetUserName(e)), true); return(Task.CompletedTask); }; discordClient.UserVoiceStateUpdated += async(user, before, after) => { Logging.Log(Logging.LogType.BOT, "User voice updated: " + user.Username); SocketGuild guild = (user as SocketGuildUser).Guild; if (after.VoiceChannel != null) { Voice.allVoiceChannels [after.VoiceChannel.Id].OnUserJoined(user as SocketGuildUser); } if (before.VoiceChannel == null && after.VoiceChannel != null) { AutoCommands.RunEvent(AutoCommands.Event.JoinedVoice, user.Id.ToString(), after.VoiceChannel.Id.ToString()); } if (before.VoiceChannel != null && after.VoiceChannel == null) { AutoCommands.RunEvent(AutoCommands.Event.LeftVoice, user.Id.ToString(), before.VoiceChannel.Id.ToString()); } await Voice.OnUserUpdated(guild, before.VoiceChannel, after.VoiceChannel); return; }; discordClient.GuildMemberUpdated += async(before, after) => { if ((before as SocketGuildUser).Nickname != (after as SocketGuildUser).Nickname) { MentionNameChange(before, after); } }; discordClient.UserUpdated += (before, after) => { if (before.Username != after.Username && (after as SocketGuildUser).Nickname == "") { MentionNameChange(before as SocketGuildUser, after as SocketGuildUser); } return(Task.CompletedTask); }; discordClient.UserBanned += (e, guild) => { SocketChannel channel = Utility.GetMainChannel(); if (channel == null) { return(Task.CompletedTask); } string banMessage = Utility.SelectRandom(onUserBannedMessage); messageControl.SendMessage(channel as SocketTextChannel, banMessage.Replace("{USERNAME}", Utility.GetUserName(e as SocketGuildUser)), true); return(Task.CompletedTask); }; discordClient.UserUnbanned += (e, guild) => { SocketChannel channel = Utility.GetMainChannel(); if (channel == null) { return(Task.CompletedTask); } string unbannedMessage = Utility.SelectRandom(onUserUnbannedMessage); messageControl.SendMessage(channel as SocketTextChannel, unbannedMessage.Replace("{USERNAME}", Utility.GetUserName(e as SocketGuildUser)), true); return(Task.CompletedTask); }; discordClient.Ready += () => { Logging.Log(Logging.LogType.BOT, "Bot is ready and running!"); return(Task.CompletedTask); }; string token = ""; try { token = SerializationIO.LoadTextFile(dataPath + "bottoken" + gitHubIgnoreType)[0]; }catch (Exception e) { Logging.Log(Logging.LogType.CRITICAL, "Bottoken not found, please create a file at <botroot>/data/bottoken.botproperty and insert bottoken there. " + e.Message); } Logging.Log(Logging.LogType.BOT, "Connecting to Discord.."); await discordClient.LoginAsync(TokenType.Bot, token); await discordClient.StartAsync(); BotConfiguration.PostInit(); await Utility.AwaitFullBoot(); try { if (args.Length > 0 && args [0] == "true" && onPatchedAnnounceChannel != 0) { using (HttpClient client = new HttpClient()) { string changelog = await client.GetStringAsync(AutoPatcher.url + "changelog.txt"); string version = await client.GetStringAsync(AutoPatcher.url + "version.txt"); string total = $"Succesfully installed new patch, changelog for {version}:\n{changelog}"; SocketGuildChannel patchNotesChannel = Utility.GetServer().GetChannel(onPatchedAnnounceChannel); if (patchNotesChannel != null) { messageControl.SendMessage(patchNotesChannel as ISocketMessageChannel, total, true, "```"); } } } } catch (Exception e) { Logging.Log(e); } BakeQuickCommands(); await Task.Delay(-1); }