private void SetCommands() { var ccfg = new CommandsNextConfiguration() { CaseSensitive = false, EnableDefaultHelp = true, EnableDms = false, EnableMentionPrefix = true, IgnoreExtraArguments = true, StringPrefix = Prefix, }; this._context = new DiscordContext(); this.Commands = this.client.UseCommandsNext(ccfg); foreach (Type type in Assembly.GetExecutingAssembly().GetTypes().Where(t => t.IsClass && t.Namespace == "Sabrina.Commands" && t.DeclaringType == null)) { if (type == null || type.Name == "BlackJackGame" || type.IsAbstract || type.FullName == "Sabrina.Commands.Edges+<AssignEdgesAsync>d__2") //Really shitty solution, but im lazy { continue; } var info = type.GetTypeInfo(); this.Commands.RegisterCommands(type); } }
public static async Task PostRandom(DiscordContext context, IEnumerable <DiscordChannel> channels) { Random rnd = new Random(); foreach (var channel in channels) { var post = await GetRandomTumblrPost(); if (post == null) { // Can't reach tumblr rn return; } TumblrPosts dbPost = await context.TumblrPosts.FindAsync(post.Response.Posts[0].Id); var builder = new DiscordEmbedBuilder() { Author = new DiscordEmbedBuilder.EmbedAuthor() { Name = "YourAnimeAddiction" }, Color = DiscordColor.Orange, ImageUrl = post.Response.Posts[0].Photos.First().AltSizes.OrderByDescending(size => size.Height).First().Url, Title = context.Puns.Skip(new Random().Next(context.Puns.Count() - 1)).First().Text }; dbPost.LastPosted = DateTime.Now; dbPost.TumblrId = post.Response.Posts[0].Id; await context.SaveChangesAsync(); await channel.SendMessageAsync(embed : builder.Build()); } }
public AccountLoginPageViewModel(DiscordContext discordContext, INavigationService navService) { _DiscordContext = discordContext; _NavigationService = navService; Mail = new ReactiveProperty <string>(""); Password = new ReactiveProperty <string>(""); IsRememberPassword = new ReactiveProperty <bool>(false); TryLoginCommand = Observable.CombineLatest( Mail.Select(x => !string.IsNullOrEmpty(x)), /* TODO: check with regex */ Password.Select(x => !string.IsNullOrWhiteSpace(x)) ) .Select(x => x.All(y => y)) .ToReactiveCommand(); NowTryLogin = new ReactiveProperty <bool>(false); TryLoginCommand.Subscribe(async _ => await TryLogin(Mail.Value, Password.Value, IsRememberPassword.Value)); if (_DiscordContext.TryGetRecentLoginAccount(out var mailAndPassword)) { Mail.Value = mailAndPassword.Item1; Password.Value = mailAndPassword.Item2; IsRememberPassword.Value = true; } IsFailedLogin = new ReactiveProperty <bool>(); IsLoginSuccess = new ReactiveProperty <bool>(); }
public BlackJackGame(int betEdges, CommandContext ctx) { _context = new DiscordContext(); this.user = UserExtension.GetUser(ctx.Message.Author.Id).GetAwaiter().GetResult(); this.ctx = ctx; // 2 Decks for (var i = 0; i < 2; i++) { // Iterate through each Card Variant foreach (Card.CardVariation variation in Enum.GetValues(typeof(Card.CardVariation))) { foreach (Card.CardValue cardValue in Enum.GetValues(typeof(Card.CardValue))) { this.Deck.Add(new Card { Variation = variation, Value = cardValue }); } } } this.BetEdges = betEdges; for (var i = 0; i < 2; i++) { this.DrawCardHouse(); this.DrawCardPlayer(); } }
public async Task CheckLoli(MessageReactionAddEventArgs e) { var name = e.Emoji.GetDiscordName(); if (name != Config.Emojis.Underage) { return; } var msg = await e.Client.Guilds.First(g => g.Key == e.Message.Channel.GuildId).Value.GetChannel(e.Message.ChannelId) .GetMessageAsync(e.Message.Id); if (msg.Embeds.Count != 1) { return; } bool isParceville = ulong.TryParse(msg.Embeds[0].Footer.Text, out ulong id); if (!isParceville) { return; } DiscordContext context = new DiscordContext(); var post = await context.TumblrPosts.FindAsync(Convert.ToInt64(id)); post.IsLoli = 1; await context.SaveChangesAsync(); await msg.DeleteAsync(":underage:"); }
public async Task InitializeAsync() { if (Config.SankakuLogin == null || Config.SankakuPassword == null) { Console.WriteLine("No Login info for Sankaku provided. Skipping Initialization of SankakuBot."); return; } _client.MessageReactionAdded += Client_MessageReactionAdded; _client.MessageReactionRemoved += Client_MessageReactionRemoved; var scrapingTask = Task.Run(async() => await ScrapeNewest()); _scrapeTimer = new Timer(TimeSpan.FromMinutes(30).TotalMilliseconds) { AutoReset = true }; _scrapeTimer.Elapsed += async(object o, ElapsedEventArgs e) => await ScrapeNewest(); _postTimer = new Timer(TimeSpan.FromMinutes(30).TotalMilliseconds) { AutoReset = true }; _postTimer.Elapsed += async(object sender, ElapsedEventArgs e) => await _postTimer_Elapsed(); _postTimer.Start(); DiscordContext context = new DiscordContext(); if (!context.SankakuPost.Any() || context.SankakuPost.OrderByDescending(sp => sp.Date).First().Date < DateTime.Now - TimeSpan.FromMinutes(20)) { await _postTimer_Elapsed(); } }
private async Task PostToAll() { Console.WriteLine("WaifuBot: Sending to all"); DiscordContext context = new DiscordContext(); var channels = context.SabrinaSettings.Where(ss => ss.FeetChannel != null).Select(setting => setting.FeetChannel.Value); foreach (var channelId in channels) { DiscordChannel channel = null; if (_client.Guilds.Any(g => g.Value.Channels.Any(c => c.Id == Convert.ToUInt64(channelId)))) { channel = await _client.GetChannelAsync(Convert.ToUInt64(channelId)); try { await PostRandom(channel); } catch (Exception e) { Console.WriteLine("Error in WaifuJOIBot PostRandom"); Console.WriteLine(e); } } } }
private async Task <float> CalculateCumScore(DiscordContext context, Users user) { float cumScore = 1; var lastOrgasm = await WheelOutcomeExtension.GetLastOutcome(UserSetting.Outcome.O****m, user.UserId, null, context); var lastRuin = await WheelOutcomeExtension.GetLastOutcome(UserSetting.Outcome.Ruin, user.UserId, null, context); if (lastOrgasm != null || lastRuin != null) { DbWheelOutcome lastCum = null; if (lastOrgasm != null && lastRuin != null) { lastCum = lastOrgasm?.Time > lastRuin?.Time ? lastOrgasm : lastRuin; } else { lastCum = lastOrgasm ?? lastRuin; } var allSinceLastCum = (await WheelOutcomeExtension.GetLastOutcomesUntil(lastCum, context)).ToList(); var denialSinceLastCum = allSinceLastCum.Where(cOutcome => cOutcome.Type == (int)UserSetting.Outcome.Denial); var taskSinceLastCum = allSinceLastCum.Where(cOutcome => cOutcome.Type == (int)UserSetting.Outcome.Task); var edgeSinceLastCum = allSinceLastCum.Where(cOutcome => cOutcome.Type == (int)UserSetting.Outcome.Edge); cumScore = (denialSinceLastCum.Count() * 6 + taskSinceLastCum.Count() * 2 + edgeSinceLastCum.Count()) / 6f; } return(cumScore); }
public TwitchController(TwitchService service, DiscordBot discord, DiscordContext ctx, ILogger <TwitchController> logger) { _service = service; _discord = discord; _db = ctx; _logger = logger; }
public async Task GetPrivAsync(IUser requestedUser = null) { using (DiscordContext db = new DiscordContext()) { ulong userId; if (requestedUser != null) { userId = requestedUser.Id; } else { userId = Context.User.Id; } User user = db.Users.FirstOrDefault(x => x.DiscordId == userId); if (user != null) { Logger.Verbose(Context.User.Username, $"Looking for {userId} privilege."); if (user.Privilege == User.Privileges.Admin || user.Privilege == User.Privileges.Owner) { await ReplyAsync($"<@{userId}> is an `{user.Privilege.ToString()}`"); return; } await ReplyAsync($"<@{userId}> is a `{user.Privilege.ToString()}`"); return; } Logger.Verbose(Context.User.Username, $"Failed to find user: {userId}"); await ReplyAsync($"Failed to find user: `{Context.User.Username}`"); } }
public async Task GetSnugAsync(IUser requestedUser = null) { using (DiscordContext db = new DiscordContext()) { ulong userId; if (requestedUser != null) { userId = requestedUser.Id; } else { userId = Context.User.Id; } User user = db.Users.FirstOrDefault(x => x.DiscordId == userId); if (user != null) { Logger.Verbose(Context.User.Username, $"Looking for snug counts."); await ReplyAsync($"<@{userId}> has given {user.SnugG} snugs and have recieved {user.SnugR} snugs."); return; } Logger.Warning(Context.User.Username, $"Failed to find user: {userId}"); await ReplyAsync($"Failed to find user: `{Context.User.Username}`"); } }
public async Task GetGenderAsync(IUser requestedUser = null) { using (DiscordContext db = new DiscordContext()) { ulong userId; if (requestedUser != null) { userId = requestedUser.Id; } else { userId = Context.User.Id; } User user = db.Users.FirstOrDefault(x => x.DiscordId == userId); if (user != null) { Logger.Warning(Context.User.Username, $"looking for user @<{userId}> gender."); await ReplyAsync($"<@{userId}> is {user.Gender.ToString().ToLower()}"); return; } Logger.Verbose(Context.User.Username, $"Failed to find user: {userId}"); await ReplyAsync($"Failed to find user: `{Context.User.Username}`"); } }
/// <summary> /// Call when client Message is created. Logs all Messages to Database. /// </summary> /// <param name="e">The Message Event Args.</param> /// <returns>A <see cref="Task"/>.</returns> private async Task ClientMessageCreated(MessageCreateEventArgs e) { var context = new DiscordContext(); if (context.Messages.Any(msg => msg.MessageId == Convert.ToInt64(e.Message.Id))) { return; } var user = await UserExtension.GetUser(e.Message.Author.Id, context); var cMsg = new Messages() { AuthorId = Convert.ToInt64(user.UserId), MessageText = e.Message.Content, ChannelId = Convert.ToInt64(e.Message.Channel.Id), CreationDate = e.Message.CreationTimestamp.DateTime, MessageId = Convert.ToInt64(e.Message.Id) }; try { user = await UserExtension.GetUser(e.Message.Author.Id, context); await _context.Messages.AddAsync(cMsg); await _context.SaveChangesAsync(); } catch (Exception ex) { Console.WriteLine("Error trying to enter Message into Database"); Console.WriteLine(ex.Message); } }
public static bool manualRegister(SocketGuildUser user) { using (DiscordContext db = new DiscordContext()) { ulong userId = user.Id; if (db.Users.Where(x => x.DiscordId == userId).Count() != 0) { Logger.Verbose("System", $"User {user.Username} already registered"); return(false); } Logger.Verbose("System", $"Creating User {user.Username} Data"); User newUser = new User(); newUser.Nickname = ""; newUser.DiscordId = userId; newUser.Level = 1; newUser.LastMessage = DateTime.UtcNow; newUser.Privilege = 0; newUser.TutorialFinished = false; newUser.Gender = User.Genders.Null; newUser.SnugG = 0; newUser.SnugR = 0; db.Users.Add(newUser); db.SaveChanges(); Logger.Verbose("System", $"Created user {user.Username} successfully"); return(true); } }
public async Task ApplySettings(DiscordContext context = null) { bool dispose = context == null; if (context == null) { #pragma warning disable IDE0068 // Use recommended dispose pattern context = new DiscordContext(); #pragma warning restore IDE0068 // Use recommended dispose pattern } var userId = Settings.Values.First().UserId; foreach (var setting in Settings) { await UserSetting.SetSettingAsync(userId, setting.Key, setting.Value.Value, context, false); } if (dispose) { context.Dispose(); } await context.SaveChangesAsync(); }
/// <summary> /// Gets or creates the bot Channel /// </summary> /// <param name="discordUser"></param> /// <param name="discordChannel"></param> /// <returns></returns> public DiscordBotChannel GetBotChannel(DiscordUser discordUser, DiscordChannel discordChannel) { DiscordBotChannel returnChannel; Console.WriteLine("Test1"); using (DiscordContext discordContext = _discordRepository.GetDiscordContext()) { Console.WriteLine("Test12"); // Channel search returnChannel = discordContext.DiscordBotChannels.FirstOrDefault(channel => channel.ChannelId == discordChannel.Id); // Can't found the channel in Database -> create if (returnChannel == null) { returnChannel = discordContext.DiscordBotChannels.Add(new DiscordBotChannel { DiscordBotId = discordContext.DiscordBots.First(bot => bot.DiscordId == discordUser.Id).Id, ChannelId = discordChannel.Id, ChannelName = discordChannel.Name }); discordContext.SaveChanges(); } } return(returnChannel); }
public string GetText(TextType type) { using DiscordContext context = new DiscordContext(); var filteredTexts = context.DungeonText.Where(dT => dT.RoomType == (int)Type && dT.TextType == (int)type); var text = filteredTexts.Skip(Helpers.RandomGenerator.RandomInt(0, filteredTexts.Count())).FirstOrDefault(); if (text == null) { return(null); } var endText = text.Text; if (text.Text.Contains("{0}")) { var variables = context.DungeonVariable.Where(dv => dv.TextId == text.Id).OrderBy(dv => dv.Position); List <string> resolvedVars = new List <string>(); foreach (var variable in variables) { resolvedVars.Add(ResolveVariable(variable)); } endText = String.Format(text.Text, resolvedVars.ToArray()); } WaitAfterMessage += 4000; return(endText); }
public async Task SetDescAsync([Remainder] string parameter) { using (DiscordContext db = new DiscordContext()) { SocketUser author = Context.User; ulong userId = author.Id; User user = db.Users.FirstOrDefault(x => x.DiscordId == userId); if (user != null) { Logger.Verbose(author.Username, $"Setting description for {userId} to: {parameter}"); user.Description = parameter; db.SaveChanges(); await ReplyAsync($"Changed <@{userId}>'s description to: {user.Description}"); return; } Logger.Verbose(author.Username, $"Failed to find user: {userId}"); await ReplyAsync($"Failed to find user: `{author.Username}`"); } }
public ServerListPageViewModel(Models.DiscordContext discordContext, INavigationService navService) { _DiscordContext = discordContext; _NavigationService = navService; Guilds = _DiscordContext.Guilds; }
public async Task SetAgeAsync(int age) { if (age < 0) { await ReplyAsync("You can't be unborn, no matter how much you try... Age cannot be less than `0`"); return; } using (DiscordContext db = new DiscordContext()) { SocketUser author = Context.User; ulong userId = author.Id; User user = db.Users.FirstOrDefault(x => x.DiscordId == userId); if (user != null) { Logger.Verbose(author.Username, $"Setting {userId} description to {age}"); user.Age = age; db.SaveChanges(); await ReplyAsync($"Changed <@{userId}> age to `{user.Age}` years old."); return; } Logger.Verbose(author.Username, $"Failed to find user: {userId}"); await ReplyAsync($"Failed to find user: `{author.Username}`"); } }
private async Task RefreshCache() { Console.WriteLine("WaifuBot: Refreshing Cache"); _cachedImages.Clear(); DiscordContext context = new DiscordContext(); var groupedChannels = context.WaifuJoiAlbum.GroupBy(album => album.ChannelId); Random rnd = new Random(); HttpClient client = new HttpClient(); foreach (var group in groupedChannels) { List <Content> pictures = new List <Content>(); foreach (var album in group) { var response = await client.GetAsync(AlbumAddress + "/" + album.ContentId); var model = await MessagePack.MessagePackSerializer.DeserializeAsync <ModelArray>( await response.Content.ReadAsStreamAsync()); pictures.AddRange(model.Contents); } _cachedImages.Add(group.Key, pictures); } }
public async Task BanAsync(IUser requestedUser, [Remainder] string reason = null) { using (DiscordContext db = new DiscordContext()) { ulong userId = Context.User.Id; if (db.Users.Where(x => x.DiscordId == userId).FirstOrDefault().Privilege < User.Privileges.Moderator) { Logger.Warning(Context.User.Username, "User tried to use ban command and failed"); await ReplyAsync($"Looks like someone wants to *get* a ban. Call a mod will ya?"); return; } if (reason == null) { await Context.Guild.AddBanAsync(requestedUser, 0, $"Banned by {Context.User.Username}: no reason given"); return; } await Context.Guild.AddBanAsync(requestedUser, 0, $"Banned by {Context.User.Username}: {reason}"); await BotReporting.ReportAsync(ReportColors.adminCommand, (SocketTextChannel)Context.Channel, $"Ban Command by {Context.User.Username}", $"<@{requestedUser.Id}> has been kicked. Reason: `{reason}`", Context.User, (SocketUser)requestedUser).ConfigureAwait(false); } }
public SettingsModule(DiscordContext context, DiscordDmChannel dm, CommandContext ctx, long userId) { _context = context; _dm = dm; _userId = userId; _ctx = ctx; }
public async Task KickAsync(IUser requestedUser, [Remainder] string reason = null) { using (DiscordContext db = new DiscordContext()) { ulong userId = Context.User.Id; if (db.Users.Where(x => x.DiscordId == userId).FirstOrDefault().Privilege < User.Privileges.Moderator) { Logger.Warning(Context.User.Username, "User tried to use kick command and failed"); await ReplyAsync($"No can do Jonny boy. You need moddlet for that."); return; } await KickUserHelper.KickAsync(Context.Channel as SocketTextChannel, requestedUser as SocketGuildUser); Logger.Warning(Context.User.Username, $"Kicked {requestedUser.Username} by {Context.User.Username}"); await BotReporting.ReportAsync(ReportColors.adminCommand, (SocketTextChannel)Context.Channel, $"Kick Command by {Context.User.Username}", $"<@{requestedUser.Id}> has been kicked", Context.User, (SocketUser)requestedUser).ConfigureAwait(false); } }
public static async Task <TumblrPost> GetRandomTumblrPost() { TumblrPost post = null; var context = new DiscordContext(); int cDays = 30; Random rnd = new Random(); int retry = 0; var minDateTime = DateTime.Now - TimeSpan.FromDays(cDays); while (retry < 5) { var validPosts = context.TumblrPosts.Where(tPost => (tPost.LastPosted == null || tPost.LastPosted < minDateTime) && tPost.IsLoli < 1); var count = validPosts.Count(); var rndInt = rnd.Next(count); var tumblrPost = validPosts.Skip(rndInt).First(); post = await GetTumblrPostById(tumblrPost.TumblrId); if (post == null) { post = null; retry++; continue; } } return(post); }
public async Task denyUserAsync(IUser requestedUser) { using (DiscordContext db = new DiscordContext()) { ulong userId = Context.User.Id; if (db.Users.Where(x => x.DiscordId == userId).FirstOrDefault().Privilege < User.Privileges.Moderator) { Logger.Warning(Context.User.Username, "User tried to use deny command and failed"); await ReplyAsync($"You're not my real mom. Go away."); return; } } if (Context.Channel.Id != Channels.ProvingGrounds) { await ReplyAsync("You can only use the deny command in #proving-grounds."); return; } await ReplyAsync($"<@{requestedUser.Id}> has been denied by <@{Context.User.Id}>."); await BotReporting.ReportAsync(ReportColors.modCommand, Context.Channel as SocketTextChannel, $"User denied", $"<@{Context.User.Id}> denied <@{requestedUser.Id}>", Context.User, requestedUser as SocketUser); await KickUserHelper.KickAsync(Context.Channel as SocketTextChannel, requestedUser as SocketGuildUser); }
public void ApplyMigrations(DiscordContext context) { if (context.Database.GetPendingMigrations().Any()) { context.Database.Migrate(); } }
public static DiscordServerMember GetServerMember(DiscordUser discordUser) { DiscordServerMember returnMember; using (DiscordContext discordContext = DiscordRepository.GetDiscordContext()) { // Channel search returnMember = discordContext.DiscordServerMembers.FirstOrDefault(member => member.DiscordId == discordUser.Id); // Can't found the channel in Database -> create if (returnMember == null) { returnMember = discordContext.DiscordServerMembers.Add(new DiscordServerMember { DiscordId = discordUser.Id, Username = discordUser.Username, Nickalert = discordUser.Mention }); discordContext.SaveChanges(); } } return(returnMember); }
public async Task FixRoomsAsync() { await ReplyAsync("Checking rooms..."); int roomCount = 0; using (DiscordContext db = new DiscordContext()) { foreach (SocketGuildUser user in Context.Guild.Users) { Logger.Verbose("system", $"Room check for {user.Username}"); SocketTextChannel pRoom = Context.Guild.TextChannels.Where(x => x.Name.Contains(user.Id.ToString())).FirstOrDefault(); if (pRoom == null) { Logger.Verbose("system", $"No room found. Creating room."); await ReplyAsync($"No room found for {user.Username}. Room created"); RestTextChannel newPersonalRoom = await RoomUtilities.CreatePersonalRoomAsync(Context.Guild, user); db.Users.Where(u => u.DiscordId == user.Id).FirstOrDefault().PersonalRoom = newPersonalRoom.Id; roomCount++; } else { db.Users.Where(u => u.DiscordId == user.Id).FirstOrDefault().PersonalRoom = pRoom.Id; } } } await ReplyAsync($"Finished checking rooms. Rooms created: {roomCount}"); }
public BlackJackGame(int betEdges, CommandContext ctx, DiscordContext context) { _context = new DiscordContext(); this.user = context.Users.Find(Convert.ToInt64(Convert.ToInt64(ctx.Message.Author.Id))); this.ctx = ctx; // 2 Decks for (var i = 0; i < 2; i++) { // Iterate through each Card Variant foreach (Card.CardVariation variation in Enum.GetValues(typeof(Card.CardVariation))) { foreach (Card.CardValue cardValue in Enum.GetValues(typeof(Card.CardValue))) { this.Deck.Add(new Card { Variation = variation, Value = cardValue }); } } } this.BetEdges = betEdges; for (var i = 0; i < 2; i++) { this.DrawCardHouse(); this.DrawCardPlayer(); } }