public override void ExecuteCommand(EvtChatCommandArgs args) { string logMessage = args.Command.ArgumentsAsString; if (string.IsNullOrEmpty(logMessage) == true) { QueueMessage(UsageMessage); return; } string username = args.Command.ChatMessage.Username.ToLowerInvariant(); //Add a new log GameLog newLog = new GameLog(); newLog.LogMessage = logMessage; newLog.User = username; newLog.LogDateTime = DateTime.UtcNow; //Add the game log to the database using (BotDBContext context = DatabaseManager.OpenContext()) { context.GameLogs.Add(newLog); context.SaveChanges(); } QueueMessage("Successfully logged message!"); }
public override void ExecuteCommand(EvtChatCommandArgs args) { List <string> arguments = args.Command.ArgumentsAsList; if (arguments.Count != 1) { QueueMessage(UsageMessage); return; } string macroName = arguments[0].ToLowerInvariant(); string message = string.Empty; using (BotDBContext context = DatabaseManager.OpenContext()) { InputMacro macro = context.Macros.FirstOrDefault(m => m.MacroName == macroName); if (macro == null) { message = $"Input macro \"{macroName}\" not found. For dynamic input macros, use the generic form (Ex. \"#test(*)\")."; } else { message = $"{macro.MacroName} = {macro.MacroValue}"; } } QueueMessage(message); }
public override void ExecuteCommand(EvtChatCommandArgs args) { List <string> arguments = args.Command.ArgumentsAsList; if (arguments.Count != 1) { QueueMessage(UsageMessage); return; } string consoleName = arguments[0].ToLowerInvariant(); int consoleID = 1; string actualConsoleName = string.Empty; using (BotDBContext context = DatabaseManager.OpenContext()) { GameConsole console = context.Consoles.FirstOrDefault(c => c.Name == consoleName); //Check if a valid console is specified if (console == null) { QueueMessage($"\"{consoleName}\" is not a valid console."); return; } consoleID = console.ID; } StringBuilder stringBuilder = null; using (BotDBContext context = DatabaseManager.OpenContext()) { IQueryable <InputSynonym> synonyms = context.InputSynonyms.Where(syn => syn.ConsoleID == consoleID); int count = synonyms.Count(); if (count == 0) { QueueMessage($"The {consoleName} console does not have any input synonyms."); return; } stringBuilder = new StringBuilder(count * 15); stringBuilder.Append("Synonyms for ").Append(consoleName).Append(':').Append(' '); //Show all input synonyms for this console foreach (InputSynonym synonym in synonyms) { stringBuilder.Append('{').Append(' ').Append(synonym.SynonymName).Append(',').Append(' '); stringBuilder.Append(synonym.SynonymValue).Append(' ').Append('}').Append(',').Append(' '); } } stringBuilder.Remove(stringBuilder.Length - 2, 2); int maxCharCount = (int)DataHelper.GetSettingInt(SettingsConstants.BOT_MSG_CHAR_LIMIT, 500L); QueueMessageSplit(stringBuilder.ToString(), maxCharCount, ", "); }
public static IEnumerable <BOT_ANSWER> BOT_ANSWER_GetByPreviousSelectAnswers(int prevAnswerId) { try { IEnumerable <BOT_ANSWER> listAnswer; using (BotDBContext context = new BotDBContext()) { try { //BotDBContext context = new BotDBContext(); BOT_ANSWER prevAnswer = context.BOT_ANSWER.Single(answer => answer.ANSWER_ID == prevAnswerId); if (prevAnswer.QUESTION_ID != null) { listAnswer = context.BOT_ANSWER.Where(answer => answer.LEVEL == prevAnswer.LEVEL && answer.QUESTION_ID == prevAnswer.ANSWER_ID); return(listAnswer.ToList()); } else { listAnswer = context.BOT_ANSWER.Where(answer => answer.LEVEL == prevAnswer.LEVEL && answer.PREVANSWER_ID == prevAnswer.PREVANSWER_ID); return(listAnswer.ToList()); } //return context.BOT_ANSWER.Where(answer => answer.LEVEL == prevAnswer.LEVEL); } catch (Exception ex) { return(null); } } } catch (Exception ex) { return(null); } }
public override void ExecuteCommand(EvtChatCommandArgs args) { List <string> arguments = args.Command.ArgumentsAsList; if (arguments.Count > 1) { QueueMessage(UsageMessage); return; } string infoUsername = (arguments.Count == 1) ? arguments[0].ToLowerInvariant() : args.Command.ChatMessage.Username.ToLowerInvariant(); using (BotDBContext context = DatabaseManager.OpenContext()) { User infoUser = DataHelper.GetUserNoOpen(infoUsername, context); if (infoUser == null) { QueueMessage($"User does not exist in database!"); return; } if (infoUser.IsOptedOut == true) { QueueMessage($"User: {infoUser.Name} | Level: {infoUser.Level} ({(PermissionLevels)infoUser.Level}) | Controller Port: {infoUser.ControllerPort}"); return; } //Print the user's information QueueMessage($"User: {infoUser.Name} | Level: {infoUser.Level} ({(PermissionLevels)infoUser.Level}) | Controller Port: {infoUser.ControllerPort} | Total Inputs: {infoUser.Stats.ValidInputCount} | Total Messages: {infoUser.Stats.TotalMessageCount}"); } }
public override void ExecuteCommand(EvtChatCommandArgs args) { List <string> arguments = args.Command.ArgumentsAsList; long curResMode = DataHelper.GetSettingInt(SettingsConstants.DEMOCRACY_RESOLUTION_MODE, 0L); DemocracyResolutionModes resMode = (DemocracyResolutionModes)curResMode; //See the virtual controller if (arguments.Count == 0) { QueueMessage($"The current Democracy resolution mode is {resMode}. To set the resolution mode, add one as an argument: {CachedResolutionModesStr}"); return; } //Invalid number of arguments if (arguments.Count > 1) { QueueMessage(UsageMessage); return; } using (BotDBContext context = DatabaseManager.OpenContext()) { //Check if the user has the ability to set the mode User user = DataHelper.GetUserNoOpen(args.Command.ChatMessage.Username, context); if (user != null && user.HasEnabledAbility(PermissionConstants.SET_DEMOCRACY_RESOLUTION_MODE_ABILITY) == false) { QueueMessage("You don't have the ability to set the Democracy resolution mode!"); return; } } string resModeStr = arguments[0]; //Parse if (EnumUtility.TryParseEnumValue(resModeStr, out DemocracyResolutionModes parsedResMode) == false) { QueueMessage($"Please enter a resolution mode: {CachedResolutionModesStr}"); return; } //Same mode if (parsedResMode == resMode) { QueueMessage($"The current resolution mode is already {resMode}!"); return; } using (BotDBContext context = DatabaseManager.OpenContext()) { //Set the value and save Settings resModeSetting = DataHelper.GetSettingNoOpen(SettingsConstants.DEMOCRACY_RESOLUTION_MODE, context); resModeSetting.ValueInt = (long)parsedResMode; context.SaveChanges(); } QueueMessage($"Changed the Democracy resolution mode from {resMode} to {parsedResMode}!"); }
public static BOT_CONVERSATION BOT_CONVERSATION_CreateConversation(int DOMAIN_ID, string DOMAIN_NAME) { try { BOT_CONVERSATION newConversation = new BOT_CONVERSATION(); using (BotDBContext context = new BotDBContext()) { try { newConversation.CREATE_DT = DateTime.Now; newConversation.DOMAIN_ID = DOMAIN_ID; newConversation.DOMAIN_NAME = DOMAIN_NAME; newConversation.ID = 0; newConversation.RECORD_STATUS = 1; newConversation.CUSTOMER_ID = null; newConversation.CUSTOMER_NAME = null; context.BOT_CONVERSATION.Add(newConversation); return(newConversation); } catch (Exception ex) { return(null); } } } catch (Exception ex) { return(null); } }
public static BOT_DOMAIN GetById(int?DOMAIN_ID, string DOMAIN_NAME) { try { BOT_DOMAIN botDomain; using (BotDBContext context = new BotDBContext()) { try { if (DOMAIN_ID != null) { botDomain = context.BOT_DOMAIN.Single(domain => domain.DOMAIN_ID == DOMAIN_ID); } else { botDomain = context.BOT_DOMAIN.Single(domain => domain.DOMAIN.Contains(DOMAIN_NAME)); } return(botDomain); } catch (Exception ex) { return(null); } } } catch (Exception ex) { return(null); } }
private async Task ProcessGuilds() { using (BotDBContext DBContext = DBFactory.Create <BotDBContext>()) { DBContext.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking; foreach (SocketGuild guild in Client.Guilds) { var guildObj = new DiscordGuild(guild.Id, guild.Name, guild.OwnerId, guild.CreatedAt, guild.IconUrl, guild.SplashUrl); var guildRecord = await DBContext.Guilds.FindAsync(guildObj.Id); if (guildRecord == null) { ConsoleEx.WriteColoredLine(LogSeverity.Verbose, ConsoleTextFormat.TimeAndText, "Adding new Guild ", ConsoleColor.Cyan, guild.Name, ConsoleColor.Gray, " to the database."); await DBContext.AddAsync(guildObj); } else { DBContext.DetachLocal(guildObj, guildObj.Id); } await DBContext.SaveChangesAsync(); await ProcessTextChannels(guild); await ProcessUsers(guild); } } }
public override void ExecuteCommand(EvtChatCommandArgs args) { List <string> arguments = args.Command.ArgumentsAsList; //Ignore with too few arguments if (arguments.Count > 1) { QueueMessage(UsageMessage); return; } if (arguments.Count == 0) { long maxRecentInputCount = DataHelper.GetSettingInt(SettingsConstants.MAX_USER_RECENT_INPUTS, 0L); QueueMessage($"The max number of recent inputs stored per user is {maxRecentInputCount}. To change this number, pass an integer as an argument."); return; } //Check for sufficient permissions using (BotDBContext context = DatabaseManager.OpenContext()) { User user = DataHelper.GetUserNoOpen(args.Command.ChatMessage.Username, context); if (user == null || user.HasEnabledAbility(PermissionConstants.SET_MAX_USER_RECENT_INPUTS_ABILITY) == false) { QueueMessage("You do not have the ability to set the number of recent inputs stored per user!"); return; } } string recentInputCountStr = arguments[0].ToLowerInvariant(); if (int.TryParse(recentInputCountStr, out int newRecentInputCount) == false) { QueueMessage("That's not a valid number!"); return; } if (newRecentInputCount < MIN_VALUE) { QueueMessage($"Value cannot be lower than {MIN_VALUE}!"); return; } using (BotDBContext context = DatabaseManager.OpenContext()) { Settings userMaxRecentInputs = DataHelper.GetSettingNoOpen(SettingsConstants.MAX_USER_RECENT_INPUTS, context); if (userMaxRecentInputs == null) { userMaxRecentInputs = new Settings(SettingsConstants.MAX_USER_RECENT_INPUTS, string.Empty, 0L); context.SettingCollection.Add(userMaxRecentInputs); } userMaxRecentInputs.ValueInt = newRecentInputCount; context.SaveChanges(); } QueueMessage($"Set the max number of recent inputs stored per user to {newRecentInputCount}!"); }
public async Task log([Remainder] int recentsLogs) { using (var con = new BotDBContext()) { var logs = con.Logs.Include(l => l.User).OrderByDescending(x => x.Date); int count = 0; StringBuilder builder = new StringBuilder(); foreach (var log in logs) { count++; if (builder.Length > 1900) { await ReplyAsync(builder.ToString()); builder = new StringBuilder(); } builder.AppendLine($"{count}. {log.Date}| {log?.User?.Name} | {log.Content}"); if (count > recentsLogs) { break; } } await ReplyAsync(builder.ToString()); } }
public async Task GuildInfo() { DateTime startTime = DateTime.Now; var orderedRoles = Context.Guild.Roles.Where(x => x.IsMentionable).ToList().OrderByDescending(x => x.Permissions.ToString()); EmbedBuilder embedBuilder = new EmbedBuilder(); EmbedService.BuildFeedbackEmbed(embedBuilder); embedBuilder.Title = $"{Context.Guild.Name.ToString()} Info"; embedBuilder.Description = $"{Context.Guild.DefaultChannel.Topic.SpliceText(50)}\n\n{"Roles:".Bold()} "; foreach (IRole role in orderedRoles) { embedBuilder.AppendEmbedDescription($"{role.Mention} ({Context.Guild.Users.Where(x => x.Roles.Contains(role)).Count().ToString().Bold()}), "); } using (BotDBContext DBContext = DBFactory.Create <BotDBContext>()) { embedBuilder.AddField(x => { x.Name = ":desktop: Default Channel"; x.Value = Context.Guild.DefaultChannel.Name; x.IsInline = true; }); embedBuilder.AddField(x => { x.Name = ":man: Users"; x.Value = Context.Guild.MemberCount; x.IsInline = true; }); embedBuilder.AddField(x => { x.Name = ":abc: Text Channels"; x.Value = Context.Guild.TextChannels.Count(); x.IsInline = true; }); embedBuilder.AddField(x => { x.Name = ":speaking_head: Voice Channels"; x.Value = Context.Guild.VoiceChannels.Count(); x.IsInline = true; }); embedBuilder.AddField(x => { x.Name = ":love_letter: Stored Messages"; x.Value = DBContext.Messages.FromSql("SELECT Messages.Id, Messages.ChannelId, TextChannels.GuildId FROM Messages INNER JOIN TextChannels ON TextChannels.Id = Messages.ChannelId WHERE TextChannels.GuildId = {0}", Context.Guild.Id.ToString()).AsNoTracking().Count().ToString(); x.IsInline = true; }); //embedBuilder.AddField(x => { x.Name = ":love_letter: Stored Messages"; x.Value = DBContext.Messages.Where(y => Context.Guild.Channels.FirstOrDefault(z => z.Id.ToString() == y.ChannelId) != null).Count().ToString(); x.IsInline = true; }); embedBuilder.AddField(x => { x.Name = ":camera_with_flash: Multifactor Authentication Level"; x.Value = Enum.GetName(typeof(MfaLevel), Context.Guild.MfaLevel); x.IsInline = true; }); embedBuilder.AddField(x => { x.Name = ":tools: Commands Executed"; x.Value = DBContext.CommandLogs.Where(y => y.GuildId == Context.Guild.Id.ToString()).Count().ToString().Number().Bold(); x.IsInline = true; }); } embedBuilder.WithThumbnailUrl(Context.Guild.IconUrl); embedBuilder.WithFooter(x => { x.Text = $"⏰ Generated in: {Math.Round((DateTime.Now.Subtract(startTime).TotalMilliseconds)).ToString()}ms"; }); await ReplyAsync("", embed : embedBuilder.Build()); }
public static IEnumerable <BOT_QUESTION> BOT_QUESTION_GetListFirstQuestionByActiveScenario(string domain) { try { IEnumerable <BOT_QUESTION> listQuestion; using (BotDBContext context = new BotDBContext()) { try { //BotDBContext context = new BotDBContext(); BOT_SCENARIO activeScenario = context.BOT_SCENARIO.Single(sc => sc.DOMAIN_NAME.Equals(domain) && sc.IS_ACTIVE.Value == true); listQuestion = context.BOT_QUESTION.Where(question => question.PREVQUESTION_ID == null && question.PREVANSWER_ID == null && question.SCENARIO_ID == activeScenario.SCENARIO_ID); return(listQuestion.ToList()); } catch (Exception ex) { return(null); } } } catch (Exception ex) { return(null); } }
public static IEnumerable <BOT_QUESTION> BOT_QUESTION_GetPreviousSelectQuestions(int prevQuestionId) { try { IEnumerable <BOT_QUESTION> listPrevQuestion; using (BotDBContext context = new BotDBContext()) { try { //BotDBContext context = new BotDBContext(); BOT_QUESTION prevQuestion = context.BOT_QUESTION.Single(prevquestion => prevquestion.QUESTION_ID == prevQuestionId); return(context.BOT_QUESTION.Where(question => question.LEVEL == prevQuestion.LEVEL)); if (prevQuestion.PREVQUESTION_ID != null) { listPrevQuestion = context.BOT_QUESTION.Where(question => question.LEVEL == prevQuestion.LEVEL && question.PREVQUESTION_ID == prevQuestion.PREVQUESTION_ID); return(listPrevQuestion.ToList()); } else { listPrevQuestion = context.BOT_QUESTION.Where(question => question.LEVEL == prevQuestion.LEVEL); return(listPrevQuestion.ToList()); } } catch (Exception ex) { return(null); } } } catch (Exception ex) { return(null); } }
public override void ExecuteCommand(EvtChatCommandArgs args) { QueueMessage("Checking to initialize default values for missing database entries."); int entriesAdded = 0; using (BotDBContext context = DatabaseManager.OpenContext()) { //Tell it to force initialize defaults Settings forceInitSetting = DataHelper.GetSettingNoOpen(SettingsConstants.FORCE_INIT_DEFAULTS, context); if (forceInitSetting != null) { forceInitSetting.ValueInt = 1; context.SaveChanges(); } } entriesAdded = DataHelper.InitDefaultData(); if (entriesAdded > 0) { QueueMessage($"Added {entriesAdded} additional entries to the database. Make sure to reload data if you're expecting new commands."); } else { QueueMessage("No new entries added."); } }
private async Task ProcessUsers(SocketGuild guild) { foreach (SocketGuildUser user in guild.Users) { if (guild.Users.Count > 100) { return; } using (BotDBContext DBContext = DBFactory.Create <BotDBContext>()) { DBContext.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking; var userObj = new DiscordUser(user.Id.ToString(), (short)user.DiscriminatorValue, user.Username, user.GetAvatarUrl(ImageFormat.Gif), user.CreatedAt, user.IsBot); var userRecord = await DBContext.Users.FindAsync(userObj.Id); if (userRecord == null) { ConsoleEx.WriteColoredLine(LogSeverity.Verbose, ConsoleTextFormat.TimeAndText, "Adding new User ", ConsoleColor.Cyan, user.Username + $"#{userObj.Discriminator}", ConsoleColor.Gray, " to the database."); await DBContext.AddAsync(userObj); } else { DBContext.DetachLocal(userObj, userObj.Id); } await DBContext.SaveChangesAsync(); } } }
public async Task <PrefixResponseData> TryRemovePrefix(IGuild guild, IUser user, string prefix) { if (PrefixDictionary.ContainsKey(guild.Id.ToString())) { List <DiscordCustomPrefix> customPrefixBag = PrefixDictionary.GetValue(guild.Id.ToString()); if (customPrefixBag == null || customPrefixBag.Count == 0) { return(new PrefixResponseData(false, "No custom prefixes exist on the current guild.")); } else { using (BotDBContext DBContext = Provider.GetService <DBContextFactory>().Create <BotDBContext>()) { foreach (DiscordCustomPrefix prefixObj in customPrefixBag) { if (prefixObj.Prefix == prefix && user.Id.ToString() == prefixObj.CreatorId) { PrefixDictionary.GetValue(guild.Id.ToString()).Remove(prefixObj); DBContext.DiscordCustomPrefixes.Remove(prefixObj); await DBContext.SaveChangesAsync(); return(new PrefixResponseData(true, "Successfully removed the specified prefix from this guild.")); } } } } } else { return(new PrefixResponseData(false, $"Unable to remove the specified prefix, it does not exist in this guild.")); } return(new PrefixResponseData(false, $"Unable to remove the specified prefix from the guild for an unknown reason.")); }
public override void ExecuteCommand(EvtChatCommandArgs args) { StringBuilder strBuilder = null; using (BotDBContext context = DatabaseManager.OpenContext()) { //No abilities if (context.PermAbilities.Count() == 0) { QueueMessage("There are no permission abilities!"); return; } //Order alphabetically IOrderedQueryable<PermissionAbility> permAbilities = context.PermAbilities.OrderBy(p => p.Name); strBuilder = new StringBuilder(250); strBuilder.Append("Hi, ").Append(args.Command.ChatMessage.Username); strBuilder.Append(", here's a list of all permission abilities: "); foreach (PermissionAbility pAbility in permAbilities) { strBuilder.Append(pAbility.Name); strBuilder.Append(',').Append(' '); } } strBuilder.Remove(strBuilder.Length - 2, 2); int maxCharCount = (int)DataHelper.GetSettingInt(SettingsConstants.BOT_MSG_CHAR_LIMIT, 500L); QueueMessageSplit(strBuilder.ToString(), maxCharCount, ", "); }
public async Task Tags() { using (BotDBContext DBContext = DBFactory.Create <BotDBContext>()) { List <ChannelTag> selectedTags = DBContext.ChannelTags.Where(x => x.ChannelId == Context.Channel.Id.ToString()).ToList(); if (selectedTags.Count > 0) { EmbedBuilder embedBuilder = new EmbedBuilder(); embedBuilder.WithFooter(x => x.Text = $"{selectedTags.Count.ToString()} total tags."); EmbedService.BuildFeedbackEmbed(embedBuilder); string builtString = ""; foreach (ChannelTag tag in selectedTags) { builtString += $"{tag.Name}, "; } builtString = builtString.Substring(0, builtString.Length - 2); embedBuilder.Description = $":paperclip: {builtString}"; await ReplyAsync("", embed : embedBuilder.Build()); } else { await ReplyAsync("", embed : EmbedService.MakeFailFeedbackEmbed("There's no tags on this channel.")); } } }
public static bool BOT_CONVERSATIONCONTENT_AddAnswer(int CONVERSATION_ID, int ANSWER_ID, string ANSWER_CONTENT) { try { using (BotDBContext context = new BotDBContext()) { try { BOT_CONVERSATIONCONTENT content = new BOT_CONVERSATIONCONTENT(); content.ID = 0; content.CONVERSATION_ID = CONVERSATION_ID; content.ANSWER_ID = ANSWER_ID; content.ANSWER = ANSWER_CONTENT; content.RECORD_STATUS = 1; content.CREATE_DT = DateTime.Now; context.BOT_CONVERSATIONCONTENT.Add(content); context.SaveChanges(); return(true); } catch (Exception ex) { return(false); } } } catch (Exception ex) { return(false); } }
private static void MakeTemplateDatabaseFile() { //Initialize database string databasePath = Path.Combine(DataConstants.DataFolderPath, DataConstants.DATABASE_FILE_NAME); Console.WriteLine($"Validating database at: {databasePath}"); if (FileHelpers.ValidatePathForFile(databasePath) == false) { Console.WriteLine($"Cannot create database path at {databasePath}. Check if you have permission to write to this directory. Aborting."); return; } Console.WriteLine("Database path validated! Initializing database and importing migrations."); DatabaseManager.SetDatabasePath(databasePath); DatabaseManager.InitAndMigrateContext(); Console.WriteLine("Checking to initialize default values for missing database entries."); using (BotDBContext context = DatabaseManager.OpenContext()) { //Check for and initialize default values if the database was newly created or needs updating int addedDefaultEntries = DataHelper.InitDefaultData(); if (addedDefaultEntries > 0) { Console.WriteLine($"Added {addedDefaultEntries} additional entries to the database."); } } }
public override void ExecuteCommand(EvtChatCommandArgs args) { List <string> arguments = args.Command.ArgumentsAsList; if (arguments.Count != 1) { QueueMessage(UsageMessage); return; } string macroName = arguments[0].ToLowerInvariant(); using (BotDBContext context = DatabaseManager.OpenContext()) { InputMacro macro = context.Macros.FirstOrDefault(m => m.MacroName == macroName); if (macro == null) { QueueMessage($"Input macro \"{macroName}\" could not be found."); return; } context.Macros.Remove(macro); context.SaveChanges(); } QueueMessage($"Removed input macro \"{macroName}\"."); }
public async Task GenerateAndSendWorkerAsync(TelegramBotClient bot, IList <string> parameters) { var currenciesNumber = 5; bool.TryParse(parameters[0], out bool sendAnyway); var result = await GetPricesAsync(currenciesNumber); if ((!sendAnyway && !result.Item2) || string.IsNullOrEmpty(result.Item1)) { return; } try { using (BotDBContext db = new BotDBContext()) { var clients = (from c in db.Clients join sub in db.Subscriptions on c.Subscription equals sub.Id where sub.SubsctiptionType == (int)Subscription.CoinCapMarket select c.ChatId ).Distinct(); foreach (var client in clients) { await bot.SendTextMessageAsync(client, result.Item1, parseMode : Telegram.Bot.Types.Enums.ParseMode.Html); } } } catch (Exception e) { TraceError.Error(e); } }
public override void ExecuteCommand(EvtChatCommandArgs args) { StringBuilder strBuilder = null; using (BotDBContext context = DatabaseManager.OpenContext()) { int memeCount = context.Memes.Count(); if (memeCount == 0) { QueueMessage("There are no memes!"); return; } //The capacity is the estimated average number of characters for each meme multiplied by the number of memes strBuilder = new StringBuilder(memeCount * 20); foreach (Meme meme in context.Memes) { strBuilder.Append(meme.MemeName).Append(',').Append(' '); } } strBuilder.Remove(strBuilder.Length - 2, 2); int maxCharCount = (int)DataHelper.GetSettingInt(SettingsConstants.BOT_MSG_CHAR_LIMIT, 500L); QueueMessageSplit(strBuilder.ToString(), maxCharCount, ", "); }
public IHttpActionResult PostQuestion([FromBody] QuestionsBank questionsBank) { try { if (!ModelState.IsValid) { return(BadRequest("Invalid data.")); } using (var botContext = new BotDBContext()) { botContext.QuestionsBank.Add(new QuestionsBank() { Question = questionsBank.Question }); botContext.SaveChanges(); } return(Ok("Success")); } catch (Exception ex) { LogWorker logworker = new LogWorker("QuestionsBankController", "PostQuestion", ex.ToString()); return(InternalServerError()); } }
public override void ExecuteCommand(EvtChatCommandArgs args) { List <string> arguments = args.Command.ArgumentsAsList; if (arguments.Count > 1) { QueueMessage(UsageMessage); return; } string creditsUsername = (arguments.Count == 1) ? arguments[0].ToLowerInvariant() : args.Command.ChatMessage.Username.ToLowerInvariant(); long creditsCount = 0L; using (BotDBContext context = DatabaseManager.OpenContext()) { User creditsUser = DataHelper.GetUserNoOpen(creditsUsername, context); if (creditsUser == null) { QueueMessage($"User does not exist in database!"); return; } creditsCount = creditsUser.Stats.Credits; } string creditsName = DataHelper.GetCreditsName(); QueueMessage($"{creditsUsername} has {creditsCount} {creditsName.Pluralize(false, creditsCount)}!"); }
public override void ExecuteCommand(EvtChatCommandArgs args) { List <string> arguments = args.Command.ArgumentsAsList; if (arguments.Count < 2) { QueueMessage(UsageMessage); return; } string memeName = arguments[0]; string memeValue = arguments[1]; if (memeName.ElementAt(0) == '/' || memeValue.ElementAt(0) == '/') { QueueMessage("Memes cannot start with Twitch chat commands!"); return; } if (memeName.StartsWith(Parser.DEFAULT_PARSER_REGEX_MACRO_INPUT) == true) { QueueMessage($"Memes cannot start with \"{Parser.DEFAULT_PARSER_REGEX_MACRO_INPUT}\"."); return; } if (memeName.ElementAt(0) == DataConstants.COMMAND_IDENTIFIER) { QueueMessage($"Memes cannot start with \'{DataConstants.COMMAND_IDENTIFIER}\'."); return; } if (memeName.Length > MAX_MEME_NAME_LENGTH) { QueueMessage($"Memes may have up to a max of {MAX_MEME_NAME_LENGTH} characters in their name!"); return; } string memeToLower = memeName.ToLowerInvariant(); using (BotDBContext context = DatabaseManager.OpenContext()) { Meme meme = context.Memes.FirstOrDefault(m => m.MemeName == memeToLower); string actualMemeValue = args.Command.ArgumentsAsString.Remove(0, memeName.Length + 1); if (meme != null) { meme.MemeValue = actualMemeValue; QueueMessage("Meme overwritten!"); } else { Meme newMeme = new Meme(memeToLower, actualMemeValue); context.Memes.Add(newMeme); } context.SaveChanges(); } }
public override void ExecuteCommand(EvtChatCommandArgs args) { string creditsName = DataHelper.GetCreditsName(); long median = 0; using (BotDBContext context = DatabaseManager.OpenContext()) { if (context.Users.Count() == 0) { QueueMessage("There are no users in the database!"); return; } List <User> orderedCredits = context.Users.OrderByDescending(u => u.Stats.Credits).ToList(); int medianIndex = orderedCredits.Count / 2; if (medianIndex >= orderedCredits.Count) { QueueMessage("Sorry, there's not enough data available in the database!"); return; } median = orderedCredits[medianIndex].Stats.Credits; } QueueMessage($"The median number of {creditsName.Pluralize(false, 0)} in the database is {median}!"); }
public static IEnumerable <BOT_SCENARIO> BOT_SCENARIO_GetByDomain(int?DOMAIN_ID, string DOMAIN_NAME) { try { IEnumerable <BOT_SCENARIO> listScenario; using (BotDBContext context = new BotDBContext()) { try { if (DOMAIN_ID != null) { listScenario = context.BOT_SCENARIO.Where(sc => sc.SCENARIO_ID == DOMAIN_ID && sc.RECORD_STATUS == 1 && sc.IS_ACTIVE == true); } else { listScenario = context.BOT_SCENARIO.Where(sc => sc.DOMAIN_NAME.Contains(DOMAIN_NAME) && sc.RECORD_STATUS == 1 && sc.IS_ACTIVE == true); } return(listScenario); } catch (Exception ex) { return(null); } } } catch (Exception ex) { return(null); } }
private async Task SendComicsAsync(Subscription subscriptionType) { using (var db = new BotDBContext()) { var clients = (from c in db.Clients join sub in db.Subscriptions on c.Subscription equals sub.Id where sub.SubsctiptionType == (int)subscriptionType select c.ChatId ).Distinct(); MessageToSend message = (subscriptionType == Subscription.Oglaf) ? GetOglafPicture() : GetXKCDPicture(); foreach (var client in clients) { var lastPostedKey = (from cli in db.Clients join sub in db.Subscriptions on cli.Subscription equals sub.Id where cli.ChatId == client && sub.SubsctiptionType == (int)subscriptionType orderby sub.Id descending select new { LTK = sub.LastPostedKey, SUBID = sub.Id } ).First(); if (message.Title.Equals(lastPostedKey.LTK)) { continue; } DatabaseInteractions.Subscription subToUpdate = db.Subscriptions.Where(x => x.Id == lastPostedKey.SUBID).First(); string newHash = message.Title; subToUpdate.LastPostedKey = newHash; db.Update(subToUpdate); //db.Subscriptions.Where(x => x.Id == lastPostedKey.SUBID).First().LastPostedKey = message.Title.GetHashCode().ToString(); try { await _bot.SendTextMessageAsync(client, message.Title.ToUpper()); await _bot.SendTextMessageAsync(client, message.SubTitle); await _bot.SendPhotoAsync(client, new InputOnlineFile(message.Image)); } catch (ChatNotFoundException e) { TraceError.Info(e.Message); var clientsRecords = db.Clients.Where(c => c.ChatId == client).ToList(); TraceError.Info("Client Recs to remove: " + string.Join(",", clientsRecords.Select(c => c.ChatId))); var subscriptionsToRemove = db.Subscriptions.Where(x => clientsRecords.Select(o => o.Subscription).Contains(x.Id)); TraceError.Info("Subscription Recs to remove: " + string.Join(",", subscriptionsToRemove.Select(s => s.SubsctiptionType.ToString()))); db.Subscriptions.RemoveRange(subscriptionsToRemove); db.Clients.RemoveRange(clientsRecords); } } await db.SaveChangesAsync(); } }