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}**");
        }
Beispiel #2
0
        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());
        }
Beispiel #3
0
        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 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!");
        }
Beispiel #6
0
        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());
        }
Beispiel #7
0
        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.");
        }
Beispiel #8
0
        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}'");
        }
Beispiel #9
0
        /// <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();
        }
Beispiel #10
0
        /// <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 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());
        }
Beispiel #12
0
        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
            }
        }
Beispiel #13
0
        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);
        }
Beispiel #14
0
        /// <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 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.");
            }
        }
        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.");
        }
Beispiel #17
0
        /// <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);
        }
Beispiel #18
0
		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)
			{
#if DEBUG
				Logger.Log(ex.ToString(), LogVerbosity.Error);
#else
				Logger.Log(ex.Message, LogVerbosity.Error);
#endif
			}

			return Task.CompletedTask;
		}
Beispiel #19
0
        /// <summary>
        /// Gives a user server points, and gives them a role if they past a certain amount of points
        /// </summary>
        /// <param name="user"></param>
        /// <param name="channel"></param>
        /// <param name="amount"></param>
        public static async void GiveUserServerPoints(SocketGuildUser user, SocketTextChannel channel, uint amount)
        {
            UserAccountServerData userAccount = UserAccountsManager.GetAccount(user).GetOrCreateServer(user.Guild.Id);

            userAccount.Points += amount;

            UserAccountsManager.SaveAccounts();

            //Give the user a role if they have enough points for it.
            ServerList       server     = ServerListsManager.GetServer(user.Guild);
            ServerRolePoints serverRole =
                server.GetServerRolePoints(userAccount.Points);

            Logger.Debug("{@Username} now has {@Points} points on guild {@GuildId}", user.Username, userAccount.Points, user.Guild.Id);

            if (serverRole.PointsRequired == 0)
            {
                return;
            }
            await user.AddRoleAsync(RoleUtils.GetGuildRole(user.Guild, serverRole.RoleId));

            await channel.SendMessageAsync(
                $"Congrats {user.Mention}, you got {userAccount.Points} points and got the **{RoleUtils.GetGuildRole(user.Guild, serverRole.RoleId).Name}** role!");
        }
Beispiel #20
0
        /// <summary>
        /// Starts and adds a new vote to a server
        /// </summary>
        /// <param name="voteTitle"></param>
        /// <param name="voteDescription"></param>
        /// <param name="lastTime"></param>
        /// <param name="yesEmoji"></param>
        /// <param name="noEmoji"></param>
        /// <param name="guild"></param>
        /// <param name="channel"></param>
        /// <param name="userWhoExecuted"></param>
        /// <returns></returns>
        public static async Task StartVote(string voteTitle, string voteDescription, TimeSpan lastTime, string yesEmoji,
                                           string noEmoji, SocketGuild guild, IMessageChannel channel, SocketUser userWhoExecuted)
        {
            if (lastTime.TotalMilliseconds > Config.bot.VoteSettings.MaxVoteTime.TotalMilliseconds)
            {
                await channel.SendMessageAsync("The vote time succeeds the maximum allowed time for a vote to last!");

                return;
            }

            ServerList server = ServerListsManager.GetServer(guild);

            if (server.Votes.Count >= Config.bot.VoteSettings.MaxRunningVotesPerGuild)
            {
                await channel.SendMessageAsync(
                    $"There are already {Config.bot.VoteSettings.MaxRunningVotesPerGuild} votes running on this guild right now!\nEnd a vote to start a new one.");

                return;
            }

            //Setup Emojis
            Emoji yesEmote = new Emoji(yesEmoji);
            Emoji noEmote  = new Emoji(noEmoji);

            //Setup embed
            EmbedBuilder embed = new EmbedBuilder();

            embed.WithTitle("Setting up vote...");

            //Send the message and add the initial reactions
            IUserMessage voteMessage = await channel.SendMessageAsync("", false, embed.Build());

            await voteMessage.AddReactionAsync(yesEmote);

            await voteMessage.AddReactionAsync(noEmote);

            Vote newVote = new Vote
            {
                VoteMessageId        = voteMessage.Id,
                VoteMessageChannelId = channel.Id,
                VoteTitle            = voteTitle,
                VoteDescription      = voteDescription,
                VoteStarterUserId    = userWhoExecuted.Id,
                NoCount           = 0,
                YesCount          = 0,
                NoEmoji           = noEmoji,
                YesEmoji          = yesEmoji,
                VoteLastTime      = lastTime,
                VoteStartTime     = DateTime.Now,
                CancellationToken = new CancellationTokenSource()
            };

            //User last vote
            UserAccountsManager.GetAccount((SocketGuildUser)userWhoExecuted).UserLastVoteId = voteMessage.Id;
            UserAccountsManager.SaveAccounts();

            //Add our vote to the server list
            server.Votes.Add(newVote);
            ServerListsManager.SaveServerList();

            embed.WithTitle(voteTitle);
            embed.WithDescription(voteDescription +
                                  $"\nReact to this message with {yesEmoji} to say **YES** or react with {noEmoji} to say **NO**.");
            embed.WithFooter($"Vote started by {userWhoExecuted} at {DateTime.Now:g} and will end at {DateTime.Now.Add(lastTime):g}.", userWhoExecuted.GetAvatarUrl());

            await MessageUtils.ModifyMessage(voteMessage, embed);

            await RunVote(newVote, guild);
        }
Beispiel #21
0
        public async Task EndVote([Remainder] string voteId = "0")
        {
            //The input is just a number
            if (ulong.TryParse(voteId, NumberStyles.None, CultureInfo.InvariantCulture, out ulong id))
            {
                //Cancel last vote the user started
                if (id == 0)
                {
                    UserAccount user = UserAccountsManager.GetAccount((SocketGuildUser)Context.User);
                    if (user.UserLastVoteId != 0)
                    {
                        await VotingService.EndVote(
                            ServerListsManager.GetServer(Context.Guild).GetVote(user.UserLastVoteId), Context.Guild);
                    }
                    else
                    {
                        await Context.Channel.SendMessageAsync(
                            "You don't appear to have any votes running, if you do, put in the ID of the vote message with this command as well!");
                    }
                    return;
                }

                Vote vote = ServerListsManager.GetServer(Context.Guild).GetVote(id);
                if (vote == null)
                {
                    await Context.Channel.SendMessageAsync("There are no votes with that ID!");

                    return;
                }

                if (((SocketGuildUser)Context.User).GuildPermissions.ManageMessages)
                {
                    await VotingService.EndVote(vote, Context.Guild);

                    await Context.Channel.SendMessageAsync("That vote was ended.");

                    return;
                }
                if (vote.VoteStarterUserId != Context.User.Id)
                {
                    await VotingService.EndVote(vote, Context.Guild);

                    await Context.Channel.SendMessageAsync("Your vote was ended.");

                    return;
                }
            }

            //End all votes
            if (voteId.RemoveWhitespace() == "*")
            {
                if (!((SocketGuildUser)Context.User).GuildPermissions.ManageMessages)
                {
                    await Context.Channel.SendMessageAsync("You don't have permissions to end all votes!");

                    return;
                }

                Vote[] votes = ServerListsManager.GetServer(Context.Guild).Votes.ToArray();
                foreach (Vote vote in votes)
                {
                    await VotingService.EndVote(vote, Context.Guild);
                }

                await Context.Channel.SendMessageAsync("All votes were ended.");

                return;
            }

            await Context.Channel.SendMessageAsync(
                "Unknown argument! Either needs to be none or a message ID to end a vote, or `*` to end all.");
        }