private static string Warn(SocketUser user) { if (user.IsBot) { return("You cannot give a warning to a bot!"); } if (((SocketGuildUser)user).GuildPermissions.Administrator) { return("You cannot warn an administrator!"); } SocketGuildUser userGuild = (SocketGuildUser)user; UserAccountServerData userAccount = UserAccountsManager.GetAccount(userGuild).GetOrCreateServer(userGuild.Guild.Id); if (userAccount.IsAccountNotWarnable) { return($"A warning cannot be given to **{user}**. That person's account is set to not warnable."); } userAccount.Warnings++; UserAccountsManager.SaveAccounts(); return($"A warning was given to **{user}**"); }
public IHttpActionResult PutUserAccounts(UpdateAccountDTO updateAccount) // UPDATE USER ACCOUNT { TextResult httpResponse = new TextResult("Account has been updated!", msg); // Http response if (!ModelState.IsValid) { return(BadRequest(ModelState)); } UserAccountsManager umgr = new UserAccountsManager(); UserAccounts updatedUserAcc = umgr.UpdateAccountDetails(updateAccount); // Function to update account details if (updatedUserAcc is null) { httpResponse.ChangeHTTPMessage("Failed to update account!", msg); // Http response if user entity is null return(httpResponse); } bool entityIsUpdated = umgr.UpdateEntityInDb(updatedUserAcc); // Updating entity in DB if (entityIsUpdated.Equals(true)) { return(httpResponse); } httpResponse.ChangeHTTPMessage("Failed to update account!", msg); return(httpResponse); }
public async Task Top10Total() { //Get all accounts Pootis-Bot has and sort them List <UserAccount> totalUsers = UserAccountsManager.GetAllUserAccounts().ToList(); totalUsers.Sort(new SortUserAccount()); totalUsers.Reverse(); StringBuilder format = new StringBuilder(); format.Append($"```csharp\n 📋 Top 10 {Global.BotName} Accounts\n ========================\n"); int count = 1; foreach (UserAccount user in totalUsers.Where(user => count <= 10)) { format.Append( $"\n [{count}] -- # {Context.Client.GetUser(user.Id)}\n └ Level: {user.LevelNumber}\n └ Xp: {user.Xp}"); count++; } UserAccount userAccount = UserAccountsManager.GetAccount((SocketGuildUser)Context.User); format.Append( $"\n------------------------\n 😊 {Context.User.Username}'s Position: {totalUsers.IndexOf(userAccount) + 1} {Context.User.Username}'s Level: {userAccount.LevelNumber} {Context.User.Username}'s Xp: {userAccount.Xp}```"); await Context.Channel.SendMessageAsync(format.ToString()); }
public async Task Top10() { List <UserAccount> serverUsers = (from user in Context.Guild.Users where !user.IsBot && !user.IsWebhook select UserAccountsManager.GetAccount(user)).ToList(); serverUsers.Sort(new SortUserAccount()); serverUsers.Reverse(); StringBuilder format = new StringBuilder(); format.Append("```csharp\n 📋 Top 10 Server User Position\n ========================\n"); int count = 1; foreach (UserAccount user in serverUsers.Where(user => count <= 10)) { format.Append( $"\n [{count}] -- # {Context.Client.GetUser(user.Id)}\n └ Level: {user.LevelNumber}\n └ Xp: {user.Xp}"); count++; } UserAccount userAccount = UserAccountsManager.GetAccount((SocketGuildUser)Context.User); format.Append( $"\n------------------------\n 😊 {Context.User.Username}'s Position: {serverUsers.IndexOf(userAccount) + 1} {Context.User.Username}'s Level: {userAccount.LevelNumber} {Context.User.Username}'s Xp: {userAccount.Xp}```"); await Context.Channel.SendMessageAsync(format.ToString()); }
public async Task RequestData() { await Context.Channel.SendMessageAsync( "Hang on, I will DM you the JSON file once I have collected all of your account data."); //Create the temp directory if it doesn't exist if (!Directory.Exists("temp/")) { Directory.CreateDirectory("temp/"); } //Get the user account in a single json file string json = JsonConvert.SerializeObject(UserAccountsManager.GetAccount((SocketGuildUser)Context.User), Formatting.Indented); File.WriteAllText($"temp/{Context.User.Id}.json", json); //Get the user's dm and send the file IDMChannel dm = await Context.User.GetOrCreateDMChannelAsync(); await dm.SendFileAsync($"temp/{Context.User.Id}.json", "Here is your user data, all in one JSON file!"); //Delete the file File.Delete($"temp/{Context.User.Id}.json"); }
public IHttpActionResult LoginUser(UserAccounts userInput) // LOGIN ACCOUNT { if (!ModelState.IsValid) { return(BadRequest()); } ; UserAccountsManager umgr = new UserAccountsManager(); bool loginOk = umgr.Login(userInput.accountName, userInput.accountPassword);// Login function, returns bool string token = umgr.CreateToken(userInput.accountName); if (token is null && loginOk.Equals(false)) { return(Unauthorized()); } if (loginOk.Equals(true)) // If bool is true, return Ok(200) http response { return(Ok(token)); } return(Unauthorized()); // Returns if failed to verify account }
public async Task ResetProfile(string confirm = "") { if (confirm.ToLower() == "info") { await Context.Channel.SendMessageAsync( "Resting your profile will reset your XP back down to 0 and reset your profile message.\n**THIS WILL NOT RESET SERVER DATA ASSOCIATED WITH YOUR PROFILE!**\n\nTo confirm you want to reset your profile data do `resetprofile yes`."); return; } if (confirm.ToLower() != "yes") { await Context.Channel.SendMessageAsync( "For more info on profile resets do `resetprofile info`. To confirm you want to reset your profile data do `resetprofile yes`."); return; } UserAccount user = UserAccountsManager.GetAccount((SocketGuildUser)Context.User); user.ProfileMsg = ""; user.Xp = 0; UserAccountsManager.SaveAccounts(); await Context.Channel.SendMessageAsync("Your profile data has been reset!"); }
public void Initialize() { storageProvider = new Mock <IStorageProvider <IUserAccount> >(); manager = new UserAccountsManager { Storage = storageProvider.Object, }; }
public IHttpActionResult CreateUserAccount(RegistrationDTO userInput) // CREATE ACCOUNT { TextResult httpResponse = new TextResult("There is already an account with that name!", msg); UserAccountsManager umgr = new UserAccountsManager(); CustomerManager cmgr = new CustomerManager(); if (!ModelState.IsValid) { return(BadRequest()); } bool EmailIsOk = cmgr.IsValidEmail(userInput.Email); if (EmailIsOk.Equals(false)) { httpResponse.ChangeHTTPMessage("Enter valid email!", msg); return(httpResponse); // HTTP response if accountname already exists } ; bool accNameExist = umgr.CheckIfAccountNameExists(userInput.AccountName); // Check if username already exists, returns bool if (accNameExist.Equals(true)) { return(httpResponse); // HTTP response if accountname already exists } ; bool emailExists = cmgr.CheckIfEmailExists(userInput.Email); // check if email already exists, returns bool if (emailExists.Equals(true)) { httpResponse.ChangeHTTPMessage("Email already exists!", msg); // If email exists, HTTP response return(httpResponse); } ; bool passwordIsNotOk = umgr.CheckIfPasswordIsOk(userInput.AccountPassword); // checks if password is ok if (passwordIsNotOk.Equals(true)) { httpResponse.ChangeHTTPMessage("Password must contain atleast six characters, one digit and one uppercase!", msg); // If password is not ok, HTTP response return(httpResponse); } ; var customerObject = cmgr.AddCustomer(userInput.Email); // Creates customer entity var userObject = umgr.CreateUserAccount(userInput.AccountName, userInput.AccountPassword, userInput.PhoneNumber, userInput.CustomerName, customerObject); // creates useraccount entity try { db.Customers.Add(customerObject); // adds customer entity to DB db.UserAccounts.Add(userObject); // adds useraccount to DB db.SaveChanges(); } catch { httpResponse.ChangeHTTPMessage("Failed to create account!", msg); // HTTP response if fails to savechanges to DB return(httpResponse); } return(Ok()); // returns login token if registration succesfull }
public async Task ProfileMsg([Remainder] string message = "") { UserAccount account = UserAccountsManager.GetAccount((SocketGuildUser)Context.User); account.ProfileMsg = message; UserAccountsManager.SaveAccounts(); await Context.Channel.SendMessageAsync($"Your public profile message was set to '{message}'"); }
public async Task Profile(SocketGuildUser user) { //Check to see if the user requested to view the profile of is a bot if (user.IsBot) { await Context.Channel.SendMessageAsync("You can not get a profile of a bot!"); return; } //This will get the user's main role IReadOnlyCollection <SocketRole> roles = user.Roles; List <SocketRole> sortedRoles = roles.OrderByDescending(o => o.Position).ToList(); SocketRole userMainRole = sortedRoles.First(); //Get the user's account and server data relating to the user UserAccount account = UserAccountsManager.GetAccount(user); UserAccountServerData accountServer = account.GetOrCreateServer(Context.Guild.Id); EmbedBuilder embed = new EmbedBuilder(); string warningText = "No :sunglasses:"; if (!accountServer.IsAccountNotWarnable && !user.GuildPermissions.Administrator) { warningText = $"Yes\n**Warnings: ** {accountServer.Warnings}"; } embed.WithCurrentTimestamp(); embed.WithThumbnailUrl(user.GetAvatarUrl()); embed.WithTitle(user.Username + "'s Profile"); embed.AddField("Stats", $"**Level: ** {account.LevelNumber}\n**Xp: ** {account.Xp}\n", true); embed.AddField("Server", $"**Points: **{accountServer.Points}\n**Warnable: **{warningText}\n**Main Role: **{userMainRole.Name}\n", true); embed.AddField("Account", $"**Id: **{account.Id}\n**Creation Date: **{user.CreatedAt}"); embed.WithColor(userMainRole.Color); embed.WithFooter(account.ProfileMsg, user.GetAvatarUrl()); string description = ""; if (user.Id == Global.BotOwner.Id) { description += $":crown: {Global.BotName} owner!\n"; } if (HighLevelProfileMessageManager.GetHighLevelProfileMessage(user.Id) != null) { description += HighLevelProfileMessageManager.GetHighLevelProfileMessage(user.Id).Message; } embed.WithDescription(description); await Context.Channel.SendMessageAsync("", false, embed.Build()); }
public async Task RemoveXp(SocketGuildUser user, uint amount) { LevelingSystem.GiveUserXp(user, (SocketTextChannel)Context.Channel, (uint)-amount); await Task.Delay(500); await Context.Channel.SendMessageAsync( $"**{user.Username}** had {amount} xp removed. They are now have {UserAccountsManager.GetAccount(user).Xp} xp in total."); }
private void DecryptPassword() { string file = txtFilePath.Text; var password = txtBxPassword.Password; var salt = MasterConfigManager.getInstance().getPasswordSalt(); FileEncryptor.Decrypt(file, password, salt); listboxuseraccounts.ItemsSource = UserAccountsManager.getInstance().getUserAccounts(); }
public MainWindow() { SplashScreen sc = new SplashScreen(SPLASHSCRNIMGPATH); sc.Show(false); sc.Close(TimeSpan.FromSeconds(3)); System.Threading.Thread.Sleep(3000); sc = null; InitializeComponent(); this.DataContext = this; string projectDirectory = String.Empty; #if (DEBUG) //projectDirectory = @"C:\Program Files (x86)\AccountsManager"; projectDirectory = AppDomain.CurrentDomain.BaseDirectory; #else projectDirectory = AppDomain.CurrentDomain.BaseDirectory; #endif txtFilePath.Text = projectDirectory + ACCTSMGRFILEPATH; try { if (String.IsNullOrEmpty(projectDirectory + ACCTSMGRUSERSCONFIGPATH) || !File.Exists(projectDirectory + ACCTSMGRUSERSCONFIGPATH)) { throw new FileNotFoundException("Accounts Manager can't find specified config file " + projectDirectory + ACCTSMGRUSERSCONFIGPATH + " Application will now shutdown."); } if (String.IsNullOrEmpty(projectDirectory + ACCTSMGRFILEPATH) || !File.Exists(projectDirectory + ACCTSMGRFILEPATH)) { throw new FileNotFoundException("Accounts Manager can't find specified config file " + projectDirectory + ACCTSMGRFILEPATH + " Application will now shutdown."); } MasterConfigManager.getInstance(projectDirectory + ACCTSMGRUSERSCONFIGPATH); if (String.IsNullOrEmpty(MasterConfigManager.getInstance().getPasswordHash())) { System.Windows.MessageBox.Show("No master password has been set yet. " + Environment.NewLine + "Please enter a master password to be used to encrypt file."); SetMasterPasswordWindow smpw = new SetMasterPasswordWindow(); smpw.ShowDialog(); } if (MasterConfigManager.getInstance().getIsFileEncrypted() == false) { lblStatus.Visibility = Visibility.Hidden; } UserAccountsManager.getInstance(projectDirectory + ACCTSMGRFILEPATH); listboxuseraccounts.ItemsSource = UserAccountsManager.getInstance().getUserAccounts(); } catch (FileNotFoundException ex) { showErrorWindow(ex); } catch (FileFormatException ex) { showErrorWindow(ex); } }
public async Task WarnUser([Remainder] SocketGuildUser user = null) { if (user == null) { await Context.Channel.SendMessageAsync("You need to input a valid username!"); return; } await Context.Channel.SendMessageAsync(Warn(user)); UserAccountsManager.CheckUserWarnStatus(user); }
public IHttpActionResult GetUserAccountByName(AccountNameDTO accountName) // Gets UserAccount entity from DB with accountname; accountName is found in json body, not the url! { UserAccountsManager umgr = new UserAccountsManager(); UserAccounts user = new UserAccounts(); user = umgr.GetUserAccountByName(accountName.AccountName); // function thats gets user entity from DB if (user is null) // if user entity is null { TextResult failedToFindAccount = new TextResult("Failed to find account", msg); return(failedToFindAccount); } return(Ok(user)); }
/// <summary> /// Ends a vote running on a guild /// <para>If the vote is running, it will END it!</para> /// </summary> /// <param name="vote">The vote to end</param> /// <param name="guild"></param> /// <returns></returns> public static async Task EndVote(Vote vote, SocketGuild guild) { Logger.Log("The vote ended.", LogVerbosity.Debug); vote.CancellationToken.Cancel(); SocketUser user = guild.GetUser(vote.VoteStarterUserId); //Remove from user's last vote UserAccountsManager.GetAccount((SocketGuildUser)user).UserLastVoteId = 0; UserAccountsManager.SaveAccounts(); //Create a new embed with the results EmbedBuilder embed = new EmbedBuilder(); embed.WithTitle(vote.VoteTitle); embed.WithDescription(vote.VoteDescription + $"\nThe vote is now over! Here are the results:\n**Yes**: {vote.YesCount}\n**No**: {vote.NoCount}"); if (user != null) { embed.WithFooter($"Vote started by {user} and ended at {DateTime.Now:g}.", user.GetAvatarUrl()); } else { embed.WithFooter("Vote started by: a person who left the guild :("); } //Modify the message IMessage message = await guild.GetTextChannel(vote.VoteMessageChannelId).GetMessageAsync(vote.VoteMessageId); await MessageUtils.ModifyMessage(message as IUserMessage, embed); //Send the user who started the vote a message about their vote is over if (user != null) { EmbedBuilder userDmEmbed = new EmbedBuilder(); userDmEmbed.WithTitle("Vote: " + vote.VoteTitle); userDmEmbed.WithDescription($"Your vote that you started on the **{guild.Name}** guild is now over.\n" + $"You can see the results [here](https://discordapp.com/channels/{guild.Id}/{vote.VoteMessageChannelId}/{vote.VoteMessageId})."); IDMChannel userDm = await user.GetOrCreateDMChannelAsync(); await userDm.SendMessageAsync("", false, userDmEmbed.Build()); } //Remove our vote from the server's vote list ServerListsManager.GetServer(guild).Votes.Remove(vote); ServerListsManager.SaveServerList(); }
private void btnClickChangeAccountInfo(object sender, RoutedEventArgs e) { UserAccountsManager.getInstance().CurrentUserAccount = listboxuseraccounts.SelectedItem as UserAccount; if (UserAccountsManager.getInstance().CurrentUserAccount == null) { System.Windows.MessageBox.Show("Please select an account first."); return; } ChangeAccountWindow caw = new ChangeAccountWindow(); caw.ChangeAccountInfoEvent += caw_ChangeAccountInfoEvent; caw.CurrentUserAccount = UserAccountsManager.getInstance().CurrentUserAccount; caw.Show(); }
public IHttpActionResult PutUserAccounts(ChangePasswordDTO passwordInput) // CHANGE PASSWORD { TextResult httpResponse = new TextResult("Failed to change password!", msg); // Http response string salt; string hashedOldPassword = null; string hashedNewPassword; string hashedPasswordFromDb = null; if (!ModelState.IsValid) { return(BadRequest(ModelState)); } UserAccountsManager umgr = new UserAccountsManager(); bool passwordIsNotOk = umgr.CheckIfPasswordIsOk(passwordInput.NewPassword); // Check if password is valid if (passwordIsNotOk.Equals(true)) { httpResponse.ChangeHTTPMessage("Password must contain atleast six characters, one digit and one uppercase!", msg); // If password is not ok, HTTP response return(httpResponse); } try { salt = umgr.GetUserSalt(passwordInput.AccountName); // Gets salt from DB hashedOldPassword = umgr.HashPassword(salt, passwordInput.OldPassword); // Hashing old password with user salt hashedNewPassword = umgr.HashPassword(salt, passwordInput.NewPassword); // Hashing new password with user salt hashedPasswordFromDb = umgr.GetPassword(passwordInput.AccountName); // Gets old hashed password from DB } catch { return(httpResponse); // http response if above operations failed } if (hashedOldPassword.Equals(hashedPasswordFromDb)) // Compares new password vs old { UserAccounts updatedUser = new UserAccounts(); updatedUser.accountPassword = hashedNewPassword; // Adds new hashed password to user entity updatedUser.accountName = passwordInput.AccountName; // User entity account name bool entityIsUpdated = umgr.UpdateEntityInDb(updatedUser); // Updating entity in DB if (entityIsUpdated.Equals(true)) { httpResponse.ChangeHTTPMessage("Password changed!", msg); return(httpResponse); } return(httpResponse); } httpResponse.ChangeHTTPMessage("Password not correct!", msg); // if input password and password from DB do not match return(httpResponse); }
/// <summary> /// Checks how many users are mention in a single message, if it is higher then the threshold then remove it /// </summary> /// <param name="message">The message to check</param> /// <param name="guild">The guild of the message</param> /// <returns>Whether the user is allowed to do that action</returns> public bool CheckMentionUsers(SocketUserMessage message, SocketGuild guild) { SocketGuildUser user = (SocketGuildUser)message.Author; UserAccountServerData serverAccount = UserAccountsManager.GetAccount(user).GetOrCreateServer(guild.Id); if (serverAccount.IsAccountNotWarnable) { return(false); } //If it is the owner of the Discord server, ignore if (user.Id == guild.OwnerId) { return(false); } //If user is a admin, ignore if (user.GuildPermissions.Administrator) { return(false); } int guildMemberCount = guild.Users.Count; int mentionCount = message.MentionedUsers.Count; int percentage = mentionCount / guildMemberCount * 100; if (percentage > ServerListsManager.GetServer(guild).AntiSpamSettings.MentionUsersPercentage) { return(false); } message.Channel.SendMessageAsync( $"Hey {message.Author.Mention}, listing all members of this Discord server is not allowed!") .GetAwaiter().GetResult(); message.DeleteAsync().GetAwaiter().GetResult(); serverAccount.Warnings++; UserAccountsManager.CheckUserWarnStatus(user); UserAccountsManager.SaveAccounts(); return(true); }
public IHttpActionResult UserAccountBooking(UserAccountBookingDTO booking) // BOOKING WITH USER ACCOUNT, NOT FINISHED { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } TextResult httpResponse = new TextResult("", msg); SeatManager smgr = new SeatManager(); CustomerManager cmgr = new CustomerManager(); BookingManager bmgr = new BookingManager(); UserAccountsManager umgr = new UserAccountsManager(); DateTime currentDate = DateTime.Now; string token = umgr.CreateToken(booking.AccountName); var loginOk = umgr.CheckIfUserIsLoggedIn(booking.LoginToken, token); // token passed from frontend to check if user is logged in, token variabel content? if (loginOk.Equals(false)) { httpResponse.ChangeHTTPMessage("User is not logged in!", msg); return(httpResponse); } ; var convertedForDate = bmgr.DateTimeConverter(booking.BookingForDate); // Converting dates into DateTime objects if (convertedForDate.Equals(null)) // checking if date input is valid { httpResponse.ChangeHTTPMessage("Date input is not correct!", msg); return(httpResponse); } ; int?allSeatsId = smgr.GetSeatPlacementId(booking.RowNumber, booking.SeatNumber); // Gets the allSeatsId from AllSeats from row and seatnumber int bookingId = smgr.CheckIfSeatIsTaken(convertedForDate, allSeatsId); // checks if seat is taken, returns bookingId if (bookingId != 0) { httpResponse.ChangeHTTPMessage("That seat is taken!", msg); // http response if seat is taken return(httpResponse); } var custId = umgr.GetCustomerIdFromUserAccountName(booking.AccountName); var email = cmgr.GetCustomerEmailFromAccountName(custId); var bookingEntity = bmgr.UserAccountBooking(allSeatsId, custId, convertedForDate, currentDate); db.Bookings.Add(bookingEntity); db.SaveChanges(); httpResponse.ChangeHTTPMessage("Booking has been made!", msg); // HTTP response if fails to savechanges to DB return(httpResponse); }
public async Task UserJoined(SocketGuildUser user) { try { if (!user.IsBot) { ServerList server = ServerListsManager.GetServer(user.Guild); //Pre create the user account UserAccountsManager.GetAccount(user); UserAccountsManager.SaveAccounts(); //If the server has welcome messages enabled then we give them a warm welcome UwU if (server.WelcomeMessageEnabled) { //Format the message to include username and the server name string addUserMention = server.WelcomeMessage.Replace("[user]", user.Mention); string addServerName = addUserMention.Replace("[server]", user.Guild.Name); //Welcomes the new user with the server's message SocketTextChannel channel = _client.GetGuild(server.GuildId).GetTextChannel(server.WelcomeChannelId); if (channel != null) { await channel.SendMessageAsync(addServerName); } else { server.WelcomeMessageEnabled = false; server.WelcomeChannelId = 0; ServerListsManager.SaveServerList(); } } } } catch (Exception ex) { #if DEBUG Logger.Log(ex.ToString(), LogVerbosity.Error); #else Logger.Log(ex.Message, LogVerbosity.Error); #endif } }
public async Task GetNotWarnable() { StringBuilder builder = new StringBuilder(); builder.Append("__**Users who are not warnable**__\n"); foreach (SocketGuildUser user in Context.Guild.Users) { UserAccount userAccount = UserAccountsManager.GetAccount(user); if (userAccount.GetOrCreateServer(Context.Guild.Id).IsAccountNotWarnable) { builder.Append(user.Username + "\n"); } } await Context.Channel.SendMessageAsync(builder.ToString()); }
private Task HandleMessage(SocketMessage messageParam) { try { //Check the message to make sure it isn't a bot or such and get the SocketUserMessage and context if (!CheckMessage(messageParam, out SocketUserMessage msg, out SocketCommandContext context)) { return(Task.CompletedTask); } ServerList server = ServerListsManager.GetServer(context.Guild); UserAccount user = UserAccountsManager.GetAccount((SocketGuildUser)context.User); //Checks the message with the anti spam services if (!CheckMessageSpam(msg, context, user)) { return(Task.CompletedTask); } //If the message is in a banned channel then ignore it if (server.BannedChannels.Contains(msg.Channel.Id)) { return(Task.CompletedTask); } //Handle the command if (HandleCommand(msg, context, server)) { return(Task.CompletedTask); } //Since it isn't a command we do level up stuff UserAccountServerData userServerData = UserAccountsManager .GetAccount((SocketGuildUser)context.User).GetOrCreateServer(context.Guild.Id); DateTime now = DateTime.Now; HandleUserXpLevel(user, context, now); HandleUserPointsLevel(userServerData, server, context, now); } catch (Exception ex) { Logger.Error("An error occured while handling a command! {@Exception}", ex); } return(Task.CompletedTask); }
/// <summary> /// Levels up a user /// </summary> /// <param name="user"></param> /// <param name="channel"></param> /// <param name="amount"></param> public static async void GiveUserXp(SocketGuildUser user, SocketTextChannel channel, uint amount) { UserAccount userAccount = UserAccountsManager.GetAccount(user); uint oldLevel = userAccount.LevelNumber; //Nice one EternalClickbait... userAccount.Xp += amount; UserAccountsManager.SaveAccounts(); if (oldLevel != userAccount.LevelNumber) { await channel.SendMessageAsync( $"{user.Mention} leveled up! Now on level **{userAccount.LevelNumber}**!"); } Logger.Debug("{@Username} now has {@Xp} XP", user.Username, userAccount.Xp); }
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" }); UserAccountsManager _manager = new UserAccountsManager(); UserDTO user = await _manager.Login(context.UserName, context.Password); if (user == null) { context.SetError("invalid_grant", "The user name or password is incorrect."); return; } var identity = new ClaimsIdentity(context.Options.AuthenticationType); identity.AddClaim(new Claim("sub", context.UserName)); identity.AddClaim(new Claim("role", user.Roles.ToString())); context.Validated(identity); }
public async Task MuteUser(SocketGuildUser user = null) { //Check to see if the user is null if (user == null) { await Context.Channel.SendMessageAsync("You need to input a username of a user!"); return; } //Make sure the user being muted isn't the owner of the guild, because that would be retarded. if (user.Id == Context.Guild.OwnerId) { await Context.Channel.SendMessageAsync( "Excuse me, you are trying to mute... the owner? That is a terrible idea."); return; } //Yea, muting your self isn't normal either. if (user == Context.User) { await Context.Channel.SendMessageAsync( "Are you trying to mute your self? I don't think that is normal."); return; } UserAccount account = UserAccountsManager.GetAccount(user); UserAccountServerData accountServer = account.GetOrCreateServer(Context.Guild.Id); accountServer.IsMuted = true; UserAccountsManager.SaveAccounts(); if (accountServer.IsMuted) { await Context.Channel.SendMessageAsync($"**{user.Username}** is now muted."); } else { await Context.Channel.SendMessageAsync($"**{user.Username}** is now un-muted."); } }
/// <summary> /// Checks if a given user is allowed to @mention a certain role, and warns them if not /// </summary> /// <param name="message">The message to check</param> /// <param name="user">The author of the message</param> /// <returns>Whether the user is allowed to do that action</returns> public bool CheckRoleMentions(SocketUserMessage message, SocketGuildUser user) { UserAccountServerData serverAccount = UserAccountsManager.GetAccount(user).GetOrCreateServer(user.Guild.Id); if (serverAccount.IsAccountNotWarnable) { return(false); } //If it is the owner of the Discord server, ignore if (user.Id == user.Guild.OwnerId) { return(false); } ServerList server = ServerListsManager.GetServer(user.Guild); //Go over each role a user has foreach (SocketRole role in user.Roles) { foreach (ServerRoleToRoleMention notToMentionRoles in server.RoleToRoleMentions.Where(notToMentionRoles => role.Id == notToMentionRoles.RoleNotToMentionId)) { message.DeleteAsync(); if (serverAccount.RoleToRoleMentionWarnings >= server.AntiSpamSettings.RoleToRoleMentionWarnings) { message.Channel.SendMessageAsync( $"Hey {user.Mention}, you have been pinging the **{RoleUtils.GetGuildRole(user.Guild, notToMentionRoles.RoleId).Name}** role, which you are not allowed to ping!\nA warning has been added to your account, for info see your profile."); serverAccount.Warnings++; UserAccountsManager.SaveAccounts(); } serverAccount.RoleToRoleMentionWarnings++; return(true); } } return(false); }
private static string MakeNotWarnable(IEnumerable <SocketGuildUser> users) { List <SocketGuildUser> usersToChange = new List <SocketGuildUser>(); foreach (SocketGuildUser user in users) { if (user.IsBot) { return("You cannot change the warnable status of a bot!"); } if (user.GuildPermissions.Administrator) { return("You cannot change the warnable status of an administrator!"); } if (UserAccountsManager.GetAccount(user).GetOrCreateServer(user.Guild.Id).IsAccountNotWarnable) { return($"**{user.Username}** is already not warnable!"); } usersToChange.Add(user); } StringBuilder sb = new StringBuilder(); for (int i = 0; i < usersToChange.Count; i++) { UserAccountServerData userAccount = UserAccountsManager.GetAccount(usersToChange[i]).GetOrCreateServer(usersToChange[i].Guild.Id); userAccount.IsAccountNotWarnable = true; userAccount.Warnings = 0; sb.Append(i + 1 == usersToChange.Count ? usersToChange[i].Username : $"{usersToChange[i].Username}, "); } UserAccountsManager.SaveAccounts(); return(usersToChange.Count == 1 ? $"**{sb}** was made not warnable." : $"The accounts **{sb}** were all made not warnable."); }
public Task UserBanned(SocketUser user, SocketGuild guild) { //We remove the user's server data from the user account ONLY if they are banned since their chance of coming back if very low. //If the data was deleted when they left/kicked they would also loose their warnings. I am sure you can see what the issue would be if we allowed that. UserAccount userAccount = UserAccountsManager.GetAccountById(user.Id); //This should NEVER be true, but if it does SOMEHOW happen then well it is here just in case... if (userAccount == null) { return(Task.CompletedTask); } userAccount.Servers.Remove(userAccount.GetOrCreateServer(guild.Id)); UserAccountsManager.SaveAccounts(); return(Task.CompletedTask); }