public async Task <IActionResult> Index([Bind("ForwardMessages,ForwardToAllOwners,CurrencyGenerationChance,CurrencyGenerationCooldown,RotatingStatuses,RemindMessageFormat,CurrencySign,CurrencyName,CurrencyPluralName,MinimumBetAmount,BetflipMultiplier,CurrencyDropAmount,CurrencyDropAmountMax,Betroll67Multiplier,Betroll91Multiplier,Betroll100Multiplier,DMHelpString,HelpString,OkColor,ErrorColor,Locale,DefaultPrefix,CustomReactionsStartWith,LogUsernames,FirstAprilHereChance,DmCommandsOwnerOnly,Id")] BotConfig botConfig) { if (ModelState.IsValid) { using var uow = _db.UnitOfWork; if (uow.BotConfig.GetOrCreate().Id != botConfig.Id) { return(NotFound()); } else { var bc = uow.BotConfig.GetOrCreate(); bc.ForwardMessages = botConfig.ForwardMessages; bc.ForwardToAllOwners = botConfig.ForwardToAllOwners; bc.CurrencyGenerationChance = botConfig.CurrencyGenerationChance; bc.CurrencyGenerationCooldown = botConfig.CurrencyGenerationCooldown; bc.RotatingStatuses = botConfig.RotatingStatuses; bc.RemindMessageFormat = botConfig.RemindMessageFormat; bc.CurrencySign = botConfig.CurrencySign; bc.CurrencyName = botConfig.CurrencyName; bc.CurrencyPluralName = botConfig.CurrencyPluralName; bc.MinimumBetAmount = botConfig.MinimumBetAmount; bc.BetflipMultiplier = botConfig.BetflipMultiplier; bc.CurrencyDropAmount = botConfig.CurrencyDropAmount; bc.CurrencyDropAmountMax = botConfig.CurrencyDropAmountMax; bc.Betroll67Multiplier = botConfig.Betroll67Multiplier; bc.Betroll91Multiplier = botConfig.Betroll91Multiplier; bc.Betroll100Multiplier = botConfig.Betroll100Multiplier; bc.DMHelpString = botConfig.DMHelpString; bc.HelpString = botConfig.HelpString; bc.OkColor = botConfig.OkColor; bc.ErrorColor = botConfig.ErrorColor; bc.Locale = botConfig.Locale; bc.DefaultPrefix = botConfig.DefaultPrefix; bc.CustomReactionsStartWith = botConfig.CustomReactionsStartWith; bc.LogUsernames = botConfig.LogUsernames; bc.FirstAprilHereChance = botConfig.FirstAprilHereChance; bc.DmCommandsOwnerOnly = botConfig.DmCommandsOwnerOnly; uow.BotConfig.Update(bc); await uow.SaveChangesAsync(); _bcp.Reload(); return(RedirectToAction(nameof(Index))); } } else { return(View(botConfig)); } }
public SelfService(DiscordSocketClient client, EvilMortyBot bot, CommandHandler cmdHandler, DbService db, IBotConfigProvider bc, ILocalization localization, EvilMortyStrings strings, IBotCredentials creds, IDataCache cache) { _redis = cache.Redis; _bot = bot; _cmdHandler = cmdHandler; _db = db; _log = LogManager.GetCurrentClassLogger(); _localization = localization; _strings = strings; _client = client; _creds = creds; _bc = bc; _cache = cache; _imgs = cache.LocalImages; var sub = _redis.GetSubscriber(); sub.Subscribe(_creds.RedisKey() + "_reload_images", delegate { _imgs.Reload(); }, CommandFlags.FireAndForget); sub.Subscribe(_creds.RedisKey() + "_reload_bot_config", delegate { _bc.Reload(); }, CommandFlags.FireAndForget); Task.Run(async() => { await bot.Ready.Task.ConfigureAwait(false); foreach (var cmd in bc.BotConfig.StartupCommands) { var prefix = _cmdHandler.GetPrefix(cmd.GuildId); //if someone already has .die as their startup command, ignore it if (cmd.CommandText.StartsWith(prefix + "die")) { continue; } await cmdHandler.ExecuteExternal(cmd.GuildId, cmd.ChannelId, cmd.CommandText); await Task.Delay(400).ConfigureAwait(false); } }); Task.Run(async() => { await bot.Ready.Task.ConfigureAwait(false); await Task.Delay(5000).ConfigureAwait(false); if (client.ShardId == 0) { await LoadOwnerChannels().ConfigureAwait(false); } }); }
public PlayingRotateService(DiscordSocketClient client, IBotConfigProvider bcp, DbService db) { _client = client; _bcp = bcp; _db = db; _log = LogManager.GetCurrentClassLogger(); _rep = new ReplacementBuilder() .WithClient(client) .WithStats(client) .Build(); _t = new Timer(async(objState) => { try { bcp.Reload(); var state = (TimerState)objState; if (!BotConfig.RotatingStatuses) { return; } if (state.Index >= BotConfig.RotatingStatusMessages.Count) { state.Index = 0; } if (!BotConfig.RotatingStatusMessages.Any()) { return; } var status = BotConfig.RotatingStatusMessages[state.Index++].Status; if (string.IsNullOrWhiteSpace(status)) { return; } status = _rep.Replace(status); try { await client.SetGameAsync(status).ConfigureAwait(false); } catch (Exception ex) { _log.Warn(ex); } } catch (Exception ex) { _log.Warn("Rotating playing status errored.\n" + ex); } }, new TimerState(), TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(1)); }
public async Task TimelySet(int num, int period = 24) { if (num < 0 || period < 0) { return; } using (var uow = _db.UnitOfWork) { var bc = uow.BotConfig.GetOrCreate(set => set); bc.TimelyCurrency = num; bc.TimelyCurrencyPeriod = period; uow.Complete(); } _bc.Reload(); if (num == 0) { await ReplyConfirmLocalized("timely_set_none").ConfigureAwait(false); } else { await ReplyConfirmLocalized("timely_set", Format.Bold(num + _bc.BotConfig.CurrencySign), Format.Bold(period.ToString())).ConfigureAwait(false); } }
public SelfService(DiscordSocketClient client, NadekoBot bot, CommandHandler cmdHandler, DbService db, IBotConfigProvider bc, ILocalization localization, NadekoStrings strings, IBotCredentials creds, IDataCache cache) { _redis = cache.Redis; _bot = bot; _cmdHandler = cmdHandler; _db = db; _log = LogManager.GetCurrentClassLogger(); _localization = localization; _strings = strings; _client = client; _creds = creds; _bc = bc; _cache = cache; _imgs = cache.LocalImages; if (_client.ShardId == 0) { _updateTimer = new Timer(async _ => { try { var ch = ownerChannels?.Values.FirstOrDefault(); if (ch == null) // no owner channels { return; } var cfo = _bc.BotConfig.CheckForUpdates; if (cfo == UpdateCheckType.None) { return; } string data; if ((cfo == UpdateCheckType.Commit && (data = await GetNewCommit()) != null) || (cfo == UpdateCheckType.Release && (data = await GetNewRelease()) != null)) { await ch.SendConfirmAsync("New Bot Update", data).ConfigureAwait(false); } } catch (Exception ex) { _log.Warn(ex); } }, null, TimeSpan.FromHours(8), TimeSpan.FromHours(8)); } var sub = _redis.GetSubscriber(); sub.Subscribe(_creds.RedisKey() + "_reload_images", delegate { _imgs.Reload(); }, CommandFlags.FireAndForget); sub.Subscribe(_creds.RedisKey() + "_reload_bot_config", delegate { _bc.Reload(); }, CommandFlags.FireAndForget); Task.Run(async() => { await bot.Ready.Task.ConfigureAwait(false); _autoCommands = bc.BotConfig .StartupCommands .Where(x => x.Interval >= 5) .GroupBy(x => x.GuildId) .ToDictionary( x => x.Key, y => y.ToDictionary(x => x.Id, x => TimerFromStartupCommand((StartupCommand)x)) .ToConcurrent()) .ToConcurrent(); foreach (var cmd in bc.BotConfig.StartupCommands.Where(x => x.Interval <= 0)) { try { await ExecuteCommand(cmd); } catch { } } }); Task.Run(async() => { await bot.Ready.Task.ConfigureAwait(false); await Task.Delay(5000).ConfigureAwait(false); if (client.ShardId == 0) { await LoadOwnerChannels().ConfigureAwait(false); } }); }
public async Task MassKill([Remainder] string people) { if (string.IsNullOrWhiteSpace(people)) { return; } var gusers = ((SocketGuild)Context.Guild).Users; //get user objects and reasons var bans = people.Split("\n") .Select(x => { var split = x.Trim().Split(" "); var reason = string.Join(" ", split.Skip(1)); if (ulong.TryParse(split[0], out var id)) { return(Original: split[0], Id: id, Reason: reason); } return(Original: split[0], Id: gusers .FirstOrDefault(u => u.ToString().ToLowerInvariant() == x) ?.Id, Reason: reason); }) .ToArray(); //if user is null, means that person couldn't be found var missing = bans .Where(x => !x.Id.HasValue) .ToArray(); //get only data for found users var found = bans .Where(x => x.Id.HasValue) .Select(x => x.Id.Value) .ToArray(); var missStr = string.Join("\n", missing); if (string.IsNullOrWhiteSpace(missStr)) { missStr = "-"; } //send a message but don't wait for it var banningMessageTask = Context.Channel.EmbedAsync(new EmbedBuilder() .WithDescription(GetText("mass_kill_in_progress", bans.Length)) .AddField(GetText("invalid", missing.Length), missStr) .WithOkColor()); using (var uow = _db.UnitOfWork) { var bc = uow.BotConfig.GetOrCreate(set => set.Include(x => x.Blacklist)); //blacklist the users bc.Blacklist.AddRange(found.Select(x => new BlacklistItem { ItemId = x, Type = BlacklistType.User, })); //clear their currencies uow.Currency.RemoveFromMany(found.Select(x => (long)x).ToList()); uow.Complete(); } _bc.Reload(); //do the banning await Task.WhenAll(bans .Where(x => x.Id.HasValue) .Select(x => Context.Guild.AddBanAsync(x.Id.Value, 7, x.Reason, new RequestOptions() { RetryMode = RetryMode.AlwaysRetry, }))) .ConfigureAwait(false); //wait for the message and edit it var banningMessage = await banningMessageTask.ConfigureAwait(false); await banningMessage.ModifyAsync(x => x.Embed = new EmbedBuilder() .WithDescription(GetText("mass_kill_completed", bans.Length)) .AddField(GetText("invalid", missing.Length), missStr) .WithOkColor() .Build()).ConfigureAwait(false); }
//private readonly Timer _updateTimer; public SelfService(DiscordSocketClient client, NadekoBot bot, CommandHandler cmdHandler, DbService db, IBotConfigProvider bc, ILocalization localization, NadekoStrings strings, IBotCredentials creds, IDataCache cache, IHttpClientFactory factory) { _redis = cache.Redis; _bot = bot; _cmdHandler = cmdHandler; _db = db; _log = LogManager.GetCurrentClassLogger(); _localization = localization; _strings = strings; _client = client; _creds = creds; _bc = bc; _cache = cache; _imgs = cache.LocalImages; _httpFactory = factory; var sub = _redis.GetSubscriber(); if (_client.ShardId == 0) { sub.Subscribe(_creds.RedisKey() + "_reload_images", delegate { _imgs.Reload(); }, CommandFlags.FireAndForget); //_updateTimer = new Timer(async _ => //{ // try // { // var ch = ownerChannels?.Values.FirstOrDefault(); // if (ch == null) // no owner channels // return; // var cfo = _bc.BotConfig.CheckForUpdates; // if (cfo == UpdateCheckType.None) // return; // string data; // if ((cfo == UpdateCheckType.Commit && (data = await GetNewCommit().ConfigureAwait(false)) != null) // || (cfo == UpdateCheckType.Release && (data = await GetNewRelease().ConfigureAwait(false)) != null)) // { // await ch.SendConfirmAsync("New Bot Update", data).ConfigureAwait(false); // } // } // catch (Exception ex) // { // _log.Warn(ex); // } //}, null, TimeSpan.FromHours(8), TimeSpan.FromHours(8)); } sub.Subscribe(_creds.RedisKey() + "_reload_bot_config", delegate { _bc.Reload(); }, CommandFlags.FireAndForget); sub.Subscribe(_creds.RedisKey() + "_leave_guild", async(ch, v) => { try { var guildStr = v.ToString()?.Trim().ToUpperInvariant(); if (string.IsNullOrWhiteSpace(guildStr)) { return; } var server = _client.Guilds.FirstOrDefault(g => g.Id.ToString() == guildStr) ?? _client.Guilds.FirstOrDefault(g => g.Name.Trim().ToUpperInvariant() == guildStr); if (server == null) { return; } if (server.OwnerId != _client.CurrentUser.Id) { await server.LeaveAsync().ConfigureAwait(false); _log.Info($"Left server {server.Name} [{server.Id}]"); } else { await server.DeleteAsync().ConfigureAwait(false); _log.Info($"Deleted server {server.Name} [{server.Id}]"); } } catch { } }, CommandFlags.FireAndForget); Task.Run(async() => { await bot.Ready.Task.ConfigureAwait(false); _autoCommands = bc.BotConfig .StartupCommands .Where(x => x.Interval >= 5) .GroupBy(x => x.GuildId) .ToDictionary( x => x.Key, y => y.ToDictionary(x => x.Id, x => TimerFromStartupCommand((StartupCommand)x)) .ToConcurrent()) .ToConcurrent(); foreach (var cmd in bc.BotConfig.StartupCommands.Where(x => x.Interval <= 0)) { try { await ExecuteCommand(cmd).ConfigureAwait(false); } catch { } } }); Task.Run(async() => { await bot.Ready.Task.ConfigureAwait(false); await Task.Delay(5000).ConfigureAwait(false); if (client.ShardId == 0) { await LoadOwnerChannels().ConfigureAwait(false); } }); }