Exemplo n.º 1
0
        //Post ban message when UserBanned event is detected.
        private async Task PostBanMsg(SocketUser u, SocketGuild g)
        {
            if (active) //Bot only announces ban messages when it is on.
            {
                IReadOnlyCollection <Discord.Rest.RestBan> bCollection = await g.GetBansAsync();

                var b = bCollection.ToImmutableList().Find(item => item.User.Username == u.Username);

                //Send ban message to channel then increment index.
                var channel = g.GetTextChannel(banChannelID);
                var msg     = u.Username + " " + banMsgs[banMsgIndex];
                var eb      = new EmbedBuilder();
                if (b.Reason != null)
                {
                    eb.WithDescription(msg + " BAN REASON: " + b.Reason);
                }
                else
                {
                    eb.WithDescription(msg);
                }

                await channel.SendMessageAsync("", false, eb);

                banMsgIndex++;

                //If we've used all ban messages shuffle them and start using them over.
                if (banMsgIndex >= banMsgs.Count)
                {
                    banMsgs.Shuffle(); banMsgIndex = 0;
                }
            }
        }
Exemplo n.º 2
0
 public async Task PeriodicCheckBan(TimeSpan interval, CancellationToken cancellationToken)
 {
     while (true)
     {
         Parallel.For(0, Data.Bans.Bans.Count,
                      async index =>
         {
             try
             {
                 var current = Data.Bans.Bans.ElementAt(index);
                 if (DateTime.UtcNow.ToBinary() >= long.Parse(current.Value))
                 {
                     SocketGuild guild = _client.GetGuild(ulong.Parse(current.Key.Split(',')[1]));
                     IUser user        = null;
                     foreach (IBan ban in await guild.GetBansAsync())
                     {
                         if (ban.User.Id == ulong.Parse(current.Key.Split(',')[0]))
                         {
                             user = ban.User;
                         }
                     }
                     await guild.RemoveBanAsync(user);
                     Data.Bans.Remove(current.Key);
                 }
             }
             catch { }
         });
         await Task.Delay(interval, cancellationToken);
     }
 }
Exemplo n.º 3
0
        public async Task UnbanUser(SocketGuild guild, ulong userID)
        {
            await Context.Message.DeleteAsync();

            IUser user = (await guild.GetBansAsync()).Where(uid => uid.User.Id == userID).First().User;
            await guild.RemoveBanAsync(user);
        }
Exemplo n.º 4
0
        public Task ExecuteAsync(SocketUserMessage msg, string[] parameters)
        {
            Task.Run(async() =>
            {
                if (parameters.Length < 2)
                {
                    return;
                }

                string targetId        = msg.MentionedUsers.Count == 1 ? msg.MentionedUsers.First().Id.ToString() : parameters[0];
                SocketGuild server     = ((SocketGuildChannel)msg.Channel).Guild;
                SocketGuildUser target = server.Users.FirstOrDefault(x => x.Id.ToString() == targetId);

                if (target == null)
                {
                    await msg.Channel.SendMessageAsync($"Correct Usage: `;;ban <@username> (reason)`");
                    return;
                }

                var allBans   = await server.GetBansAsync();
                bool isBanned = allBans.Any(x => x.User.Id == target.Id);

                if (!isBanned)
                {
                    var senderHighest = ((SocketGuildUser)msg.Author).Hierarchy;

                    if (target.Hierarchy < senderHighest)
                    {
                        try
                        {
                            var dmChannel = await target.GetOrCreateDMChannelAsync();
                            await dmChannel.SendMessageAsync($"You have been banned from **{server.Name}** by Moderator **{msg.Author}**. Reason: **{String.Join(" ", parameters.Skip(1))}**");
                        }
                        catch (Exception e)
                        {
                            await msg.Author.GetOrCreateDMChannelAsync();
                            await msg.Author.SendMessageAsync($"Failed to send DM to **{target.Username}.\nError message: {e.Message}");
                        }

                        var TextChannelLogs = client.GetChannel(353561970038931458) as SocketTextChannel;

                        EmbedBuilder eb = new EmbedBuilder();

                        eb.Color = Color.Red;

                        eb.AddField("Case:", $"{Name}");
                        eb.AddField("Target", $"{target.Mention}");
                        eb.AddField($"Moderator: ", $"{msg.Author.Mention}");
                        eb.AddField($"Reason:", $"{String.Join(" ", parameters.Skip(1))}");

                        await TextChannelLogs.SendMessageAsync("", embed: eb);

                        await server.AddBanAsync(target);
                        await msg.Channel.SendMessageAsync($"**{target.Username}** has been banned by Moderator **{msg.Author}**. Reason: **{String.Join(" ", parameters.Skip(1))}**");
                    }
                }
            });
            return(Task.CompletedTask);
        }
        public static async Task UserBanned(SocketUser arg1, SocketGuild arg2)
        {
            GuildCfg guildCfg = GuildsCfgs.GetGuildCfg(arg2);
            ISocketMessageChannel modChannel = (ISocketMessageChannel)Methods.GetTextChannelByID(arg2, guildCfg.ModeratorChannelID);

            RestBan ban = arg2.GetBansAsync().Result.ToList().FirstOrDefault(x => x.User.Id == arg1.Id);

            await modChannel.SendMessageAsync($"{ban.User.Mention} ({ban.User.Id}) otrzymał bana. Powód: {ban.Reason}");
        }
Exemplo n.º 6
0
        private static async Task ReadyAddBansToDatabase(SocketGuild g)
        {
            if (g.GetUser(DiscordBot.Bot.CurrentUser.Id).IsGuildAdministrator() || g.GetUser(DiscordBot.Bot.CurrentUser.Id).GuildPermissions.BanMembers)
            {
                var bans = await g.GetBansAsync();

                foreach (IBan b in bans)
                {
                    var(dataReader, mysqlConnection) = DatabaseActivity.ExecuteReader("SELECT * FROM bans WHERE issuedTo=" + b.User.Id + " AND inGuild=" + g.Id + ";");

                    int count = 0;
                    while (dataReader.Read())
                    {
                        count++;
                    }

                    dataReader.Close();
                    mysqlConnection.Close();

                    if (count != 0)
                    {
                        continue;
                    }

                    //Insert banned users into the database by using INSERT IGNORE
                    List <(string, string)> queryParams = new List <(string id, string value)>()
                    {
                        ("@issuedTo", b.User.Id.ToString()),
                        ("@issuedBy", DiscordBot.Bot.CurrentUser.Id.ToString()),                         // unable to get the issuedBy user ID, so use the Bot ID instead.
                        ("@inGuild", g.Id.ToString()),
                        ("@reason", b.Reason),
                        ("@date", DateTime.Now.ToString("u"))
                    };

                    DatabaseActivity.ExecuteNonQueryCommand(
                        "INSERT IGNORE INTO " +
                        "bans(issuedTo,issuedBy,inGuild,banDescription,dateIssued) " +
                        "VALUES (@issuedTo, @issuedBy, @inGuild, @reason, @date);", queryParams);

                    //end.
                }
            }
            else
            {
                await new LogMessage(LogSeverity.Info, "Guild Bans", "Unable to get banned users - Bot doesn't have the required permission(s).").PrintToConsole();
            }
        }
Exemplo n.º 7
0
        public async Task ExecuteAsync(SocketUserMessage msg, string[] parameters)
        {
            if (parameters.Length < 2 || true)
            {
                return;
            }

            string          targetId = msg.MentionedUsers.Count == 1 ? msg.MentionedUsers.First().Id.ToString() : parameters[0];
            SocketGuild     server   = ((SocketGuildChannel)msg.Channel).Guild;
            SocketGuildUser target   = server.Users.FirstOrDefault(x => x.Id.ToString() == targetId);

            if (target == null)
            {
                await msg.Channel.SendMessageAsync("No users found");

                return;
            }

            var allBans = await server.GetBansAsync();

            bool isBanned = allBans.Any(x => x.User.Id == target.Id);

            if (!isBanned)
            {
                var senderHighest = ((SocketGuildUser)msg.Author).Hierarchy;

                if (target.Hierarchy < senderHighest)
                {
                    await server.AddBanAsync(target);

                    await msg.Channel.SendMessageAsync($"**{target.Username}** has been banned by Moderator **{msg.Author}**. Reason: **{String.Join(" ", parameters.Skip(1))}**");

                    try
                    {
                        var dmChannel = await target.GetOrCreateDMChannelAsync();

                        await dmChannel.SendMessageAsync($"You have been banned from **{server.Name}** by Moderator **{msg.Author}** for **{String.Join(" ", parameters.Skip(1))}**");
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine($"Failed to send PM to banned user.\nError message: {e.Message}");
                    }
                }
            }
        }
Exemplo n.º 8
0
        private async Task HandleUserBanned(SocketUser arg1, SocketGuild arg2)
        {
            var    bans   = arg2.GetBansAsync().Result.ToList();
            string reason = "";

            foreach (var ban in bans)
            {
                if (ban.User.Id == arg1.Id)
                {
                    reason = ban.Reason;
                }
            }
            if (reason == "")
            {
                await Utilities.SendEmbed(arg2.GetTextChannel(294699220743618561), "Ban", $"{arg1} has been banned.", Colors.Red, "", arg1.GetAvatarUrl());
            }
            else
            {
                await Utilities.SendEmbed(arg2.GetTextChannel(294699220743618561), "Ban", $"{arg1} has been banned for {reason}.", Colors.Red, "", arg1.GetAvatarUrl());
            }
        }
Exemplo n.º 9
0
        //Parses commands made to the bot in text channels.
        private async Task MessageReceived(SocketMessage m)
        {
            //Determine if this message was said in the free channel and if it was said by a bot admin.
            bool isFree  = m.Channel.Id == freeChannelID;
            bool isOwner = botOwners.Contains(m.Author.Id);

            //If the message was said in the free channel or by a bot admin parse it, otherwise waste of time to parse it.
            if (isFree || isOwner)
            {
                var    eb = new EmbedBuilder();                        //Prepare embed for message posting.
                string command; int spacePos = m.Content.IndexOf(" "); //Find index of space in message if there is one.
                //If there is a space get the part prior to it. If there is no space get entire message.
                if (spacePos == -1)
                {
                    command = m.Content;
                }
                else
                {
                    command = m.Content.Substring(0, spacePos);
                }

                switch (command)
                {
                //Provides helpful information for commands to use with the bot.
                case ",help":
                    if (active)     //Bot only responds to help command when on.
                    {
                        eb.WithDescription("COMMANDS HELP\n" +
                                           ",help : Displays this message." +
                                           ",ping : Simple command to make the bot say 'Pong!'. Used to confirm the bot is online.\n\n" +
                                           ",uid %string% : Bot will return the UID of the user who said the command if no %string% is given.\n" +
                                           "Otherwise it gives the UID of the username given. UID is the unique ID a user possesses for recognition by Discord's backend.\n\n" +
                                           ",amadmin : Bot will tell the user who said the command whether or not they are a bot admin.\n\n" +
                                           ",lad : Bot will list out all the current bot admins including their usernames and UIDs.\n\n" +
                                           ",lbm : Bot will list out all the ban messages and the index of each message. Index is used for deleting ban messages.\n\n" +
                                           ",lbu : Lists all banned users along with the reason given for their ban.\n\n" +
                                           "ADMIN COMMANDS, Will only run if user is an admin.\n" +
                                           ",on : Will turn the bot on causing it to process commands and events.\n\n" +
                                           ",off : Will turn the bot off causing it to essentially just sit online till turned back on.\n\n" +
                                           ",aau %uid% : Takes a UID as an argument, will make this user into a bot admin immediately.\n\n" +
                                           ",rma %uid% : Takes a UID as an argument, will remove a bot admin immediately.\n\n" +
                                           ",abm %string% : Adds a ban message to the list of possible messages the bot will say when someone is banned where %string% is the message to add.\n\n" +
                                           ",rbm %index% : Removes a ban message with the given index from the list of possible ban messages.\n\n" +
                                           ",mute %string% : Adds a role to the user which will mute them from posting in any text channel on the server.\n\n" +
                                           ",unmute %string% : Unmutes a user if they have been previously muted from posting in any text channel.\n\n");
                        eb.WithColor(info);
                        await m.Channel.SendMessageAsync("", false, eb);
                    }
                    break;

                //Pings the bot and it replies with pong.
                case ",ping":
                    if (active)     //Only perform when on.
                    {
                        eb.WithDescription("Pong!"); eb.WithColor(info);
                        await m.Channel.SendMessageAsync("", false, eb);
                    }
                    break;

                //Tells the user their uid or if a string is given attempts to tell the uid of that user.
                case ",uid":
                    if (active)                                         //Only perform when on.
                    {
                        string usr = m.Content.Substring(spacePos + 1); //Parse out the value part of the command.
                        if (spacePos == -1)
                        {
                            eb.WithDescription(m.Author.Username + " your UID is: " + m.Author.Id); eb.WithColor(info);
                            await m.Channel.SendMessageAsync("", false, eb);
                        }
                        else
                        {
                            var usrObj = discordContains(usr);
                            if (usrObj != null)
                            {
                                eb.WithDescription("The UID of " + usr + " is: " + usrObj.Id); eb.WithColor(info);
                                await m.Channel.SendMessageAsync("", false, eb);
                            }
                            else
                            {
                                eb.WithDescription("Improper username provided or user does not exist on this server!"); eb.WithColor(warning);
                                await m.Channel.SendMessageAsync("", false, eb);
                            }
                        }
                    }
                    break;

                //Tells the user whether the bot considers them an admin.
                case ",amadmin":
                    if (active)     //Only perform when on.
                    {
                        if (isOwner)
                        {
                            eb.WithDescription(m.Author.Username + ", I recognize you as an admin."); eb.WithColor(ok);
                        }
                        else
                        {
                            eb.WithDescription(m.Author.Username + ", you are not an admin."); eb.WithColor(error);
                        }
                        await m.Channel.SendMessageAsync("", false, eb);
                    }
                    break;

                //Lists all recognized admins UIDs and their usernames.
                case ",lad":
                    if (active)     //Only perform when on.
                    {
                        string msg = "";
                        foreach (var owner in botOwners)
                        {
                            IUser tmp = await m.Channel.GetUserAsync(owner);

                            msg = msg + tmp.Username + ": " + tmp.Id + "\n";
                        }
                        eb.WithDescription(msg); eb.WithColor(info);
                        await m.Channel.SendMessageAsync("", false, eb);
                    }
                    break;

                //List all ban messages along with their index.
                case ",lbm":
                    if (active)     //Only perform when on.
                    {
                        string msg = "";
                        for (int i = 0; i < banMsgs.Count; i++)
                        {
                            msg = msg + "[" + i + "] : " + banMsgs[i] + "\n";
                        }
                        eb.WithDescription(msg); eb.WithColor(info);
                        await m.Channel.SendMessageAsync("", false, eb);
                    }
                    break;

                //List all banned users along with the reason for being banned.
                case ",lbu":
                    if (active)     //Only perform when on.
                    {
                        IReadOnlyCollection <Discord.Rest.RestBan> bCollection = await CoEDiscord.GetBansAsync();

                        string msg = "Banned User List";
                        foreach (var ban in bCollection)
                        {
                            msg = msg + ban.User.Username + ", REASON: " + ban.Reason + "\n";
                        }
                        eb.WithDescription(msg); eb.WithColor(info);
                        await m.Channel.SendMessageAsync("", false, eb);
                    }
                    break;

                //Tell the bot to start doing things again if it was turned off.
                case ",on":
                    if (isOwner)                                    //Only parse command if the author is an owner.
                    {
                        if (active)                                 //Only perform when on.
                        {
                            eb.WithDescription("I am already on!"); //Bot announces it is already on.
                            eb.WithColor(warning);
                            await m.Channel.SendMessageAsync("", false, eb);
                        }
                        else
                        {
                            active = true;
                            eb.WithDescription("Turning on!");     //Bot acknowledges successful turn on. One of two response/actions bot should make while off.
                            eb.WithColor(ok);
                            await m.Channel.SendMessageAsync("", false, eb);
                        }
                    }
                    break;

                //Tell the bot to stop doing anything like announcing bans and so on.
                case ",off":
                    if (isOwner)     //Only parse command if the author is an owner.
                    {
                        if (active)  //Only perform when on.
                        {
                            active = false;
                            eb.WithDescription("Turning off!");     //Bot acknowledges successful turn off.
                            eb.WithColor(ok);
                            await m.Channel.SendMessageAsync("", false, eb);
                        }
                        else
                        {
                            eb.WithDescription("I am already off!");     //Bot announces it is already off. One of two response/actions bot should make while off.
                            eb.WithColor(warning);
                            await m.Channel.SendMessageAsync("", false, eb);
                        }
                    }
                    break;

                //Adds a discord user as a bot admin.
                case ",aau":
                    if (isOwner)                                                             //Only parse command if the author is an owner.
                    {
                        if (active)                                                          //Only perform when on.
                        {
                            ulong uid = Convert.ToUInt64(m.Content.Substring(spacePos + 1)); //Parse out the value part of the command.
                            IUser tmp = await m.Channel.GetUserAsync(uid);

                            if (tmp == null)
                            {
                                eb.WithDescription("The provided UID is not a user on this server!"); eb.WithColor(warning);
                                await m.Channel.SendMessageAsync("", false, eb);
                            }
                            else if (botOwners.Contains(uid))
                            {
                                eb.WithDescription(tmp.Username + ": " + uid + " is already an admin!"); eb.WithColor(warning);
                                await m.Channel.SendMessageAsync("", false, eb);
                            }
                            else
                            {
                                botOwners.Add(uid);
                                using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"ownerIDs.txt", true)) { file.Write("\n" + m.Content.Substring(spacePos + 1)); }
                                eb.WithDescription(tmp.Username + ": " + uid + " added as a bot admin!"); eb.WithColor(ok);
                                await m.Channel.SendMessageAsync("", false, eb);
                            }
                        }
                    }
                    break;

                //Removes a discord user as a bot admin.
                case ",rma":
                    if (isOwner)                                                             //Only parse command if the author is an owner.
                    {
                        if (active)                                                          //Only perform when on.
                        {
                            ulong uid = Convert.ToUInt64(m.Content.Substring(spacePos + 1)); //Parse out the value part of the command.
                            IUser tmp = await m.Channel.GetUserAsync(uid);

                            if (!botOwners.Contains(uid))
                            {
                                eb.WithDescription("The provided UID is not a bot admin!"); eb.WithColor(warning);
                                await m.Channel.SendMessageAsync("", false, eb);
                            }
                            else
                            {
                                botOwners.RemoveAll(item => item == uid);

                                using (System.IO.StreamWriter writer = new StreamWriter(@"ownerIDs.txt", false))
                                {
                                    writer.Write(botOwners[0]);
                                    for (int i = 1; i < botOwners.Count; i++)
                                    {
                                        writer.Write("\n" + botOwners[i]);
                                    }
                                }

                                eb.WithDescription(tmp.Username + ": " + uid + " removed as a bot admin!"); eb.WithColor(ok);
                                await m.Channel.SendMessageAsync("", false, eb);
                            }
                        }
                    }
                    break;

                //Add a new ban message to the bot from discord itself.
                case ",abm":
                    if (isOwner)                                                                                                               //Only parse command if the author is an owner.
                    {
                        if (active)                                                                                                            //Only perform when on.
                        {
                            string msg = m.Content.Substring(spacePos + 1);                                                                    //Parse out the value part of the command.
                            using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"banMsgs.txt", true)) { file.Write("\n" + msg); } //Write to the banMsgs.txt file so this addition is persistent over bot restarts.
                            banMsgs.Add(msg);                                                                                                  //Add this ban message to the list of possible ones.
                            banMsgs.Shuffle(); banMsgIndex = 0;                                                                                //Re-shuffle the list with the new addition.
                            eb.WithDescription("Successfully added new ban message: USER " + msg); eb.WithColor(ok);
                            await m.Channel.SendMessageAsync("", false, eb);                                                                   //Provide feedback of success for the user.
                        }
                    }
                    break;

                //Remove a ban message from the bot.
                case ",rbm":
                    if (isOwner)                                                            //Only parse command if the author is an owner.
                    {
                        if (active)                                                         //Only perform when on.
                        {
                            int index = Convert.ToInt16(m.Content.Substring(spacePos + 1)); //Parse out the value part of the command.
                            if (index < 0 || index >= banMsgs.Count)
                            {
                                eb.WithDescription("Invalid index to delete. Try again."); eb.WithColor(warning);
                                await m.Channel.SendMessageAsync("", false, eb);
                            }
                            else
                            {
                                banMsgs.RemoveAt(index);

                                using (System.IO.StreamWriter writer = new StreamWriter(@"banMsgs.txt", false))
                                {
                                    if (banMsgs.Count >= 1)
                                    {
                                        writer.Write(banMsgs[0]);
                                        for (int i = 1; i < botOwners.Count; i++)
                                        {
                                            writer.Write("\n" + botOwners[i]);
                                        }
                                    }
                                    else
                                    {
                                        //Nothing to write.
                                    }
                                }

                                eb.WithDescription("Ban message with index " + index + " has been removed!"); eb.WithColor(ok);
                                await m.Channel.SendMessageAsync("", false, eb);
                            }
                        }
                    }
                    break;

                //Mute a user.
                case ",mute":
                    if (isOwner)                                            //Only parse command if the author is an owner.
                    {
                        if (active)                                         //Only perform when on.
                        {
                            string usr = m.Content.Substring(spacePos + 1); //Parse out the value part of the command.
                            if (spacePos == -1)
                            {
                                eb.WithDescription("No user to be muted was provided! Try again.");
                                await m.Channel.SendMessageAsync("", false, eb);
                            }
                            else
                            {
                                IGuildUser usrObj = discordContainsGuild(usr);
                                if (usrObj != null && !usrObj.RoleIds.ToImmutableList <ulong>().Contains(muted.Id))
                                {
                                    await usrObj.AddRoleAsync(muted).ConfigureAwait(false);

                                    eb.WithDescription(usrObj.Username + " has been muted.");
                                    await m.Channel.SendMessageAsync("", false, eb);
                                }
                                else
                                {
                                    eb.WithDescription("Improper username provided or user does not exist on this server!"); eb.WithColor(warning);
                                    await m.Channel.SendMessageAsync("", false, eb);
                                }
                            }
                        }
                    }
                    break;

                //Unmute a user.
                case ",unmute":
                    if (isOwner)                                            //Only parse command if the author is an owner.
                    {
                        if (active)                                         //Only perform when on.
                        {
                            string usr = m.Content.Substring(spacePos + 1); //Parse out the value part of the command.
                            if (spacePos == -1)
                            {
                                eb.WithDescription("No user to be unmuted was provided! Try again.");
                                await m.Channel.SendMessageAsync("", false, eb);
                            }
                            else
                            {
                                IGuildUser usrObj = discordContainsGuild(usr);
                                if (usrObj != null && usrObj.RoleIds.ToImmutableList <ulong>().Contains(muted.Id))
                                {
                                    await usrObj.RemoveRoleAsync(muted).ConfigureAwait(false);

                                    eb.WithDescription(usrObj.Username + " has been unmuted.");
                                    await m.Channel.SendMessageAsync("", false, eb);
                                }
                                else
                                {
                                    eb.WithDescription("Improper username provided or user does not exist on this server!"); eb.WithColor(warning);
                                    await m.Channel.SendMessageAsync("", false, eb);
                                }
                            }
                        }
                    }
                    break;
                }
            }
        }
Exemplo n.º 10
0
 public virtual IAsyncEnumerable <IReadOnlyCollection <RestBan> > GetBansAsync(int limit = 100, RequestOptions?options = null)
 {
     return(_socketGuild.GetBansAsync(limit, options));
 }