Exemple #1
0
 public void Process(Mute mute)
 {
     _sender.Invoke($"<{mute.Sender.OriginalNick}> <=== just muted {mute.Victim}");
 }
Exemple #2
0
        public async Task <RuntimeResult> MuteUser(IGuildUser user, string duration, [Optional][Remainder] string reason)
        {
            if (CommandHandler.FeatureFlagDisabled(FeatureFlag.MODERATION))
            {
                return(CustomResult.FromIgnored());
            }
            if (user.IsBot)
            {
                return(CustomResult.FromError("You can't mute bots."));
            }

            if (user.GuildPermissions.PrioritySpeaker)
            {
                return(CustomResult.FromError("You can't mute staff."));
            }


            TimeSpan span       = Extensions.GetTimeSpanFromString(duration);
            var      now        = DateTime.Now;
            DateTime targetTime = now.Add(span);

            if (reason is null)
            {
                return(CustomResult.FromError("You need to provide a reason."));
            }

            var author = Context.Message.Author;

            var guild         = Context.Guild;
            var mutedRoleName = "textmuted";

            if (!Global.Roles.ContainsKey(mutedRoleName))
            {
                return(CustomResult.FromError("Text mute role has not been configured. Check your DB entry!"));
            }

            mutedRoleName = "voicemuted";
            if (!Global.Roles.ContainsKey(mutedRoleName))
            {
                return(CustomResult.FromError("Voice mute role has not been configured. Check your DB entry!"));
            }

            await Extensions.MuteUser(user);

            await user.ModifyAsync(x => x.Channel = null);

            try
            {
                const string muteMessage = "You were muted on r/OnePlus for the following reason: {0} until {1}.";
                await user.SendMessageAsync(string.Format(muteMessage, reason, Extensions.FormatDateTime(targetTime)));
            }
            catch (HttpException)
            {
                await Context.Channel.SendMessageAsync("Seems like user disabled DMs, cannot send message about the mute.");
            }

            var muteData = new Mute
            {
                MuteDate    = now,
                UnmuteDate  = targetTime,
                MutedUserID = user.Id,
                MutedByID   = author.Id,
                Reason      = reason,
                MuteEnded   = false
            };

            using (var db = new Database())
            {
                db.Mutes.Add(muteData);
                db.SaveChanges();
            }

            var builder = new EmbedBuilder();

            builder.Title = "A user has been muted!";
            builder.Color = Color.Red;

            builder.Timestamp = Context.Message.Timestamp;

            builder.ThumbnailUrl = user.GetAvatarUrl();

            const string discordUrl = "https://discord.com/channels/{0}/{1}/{2}";

            builder.AddField("Muted User", Extensions.FormatUserNameDetailed(user))
            .AddField("Muted by", Extensions.FormatUserNameDetailed(author))
            .AddField("Location of the mute",
                      $"[#{Context.Message.Channel.Name}]({string.Format(discordUrl, Context.Guild.Id, Context.Channel.Id, Context.Message.Id)})")
            .AddField("Reason", reason ?? "No reason was provided.")
            .AddField("Mute duration", Extensions.FormatTimeSpan(span))
            .AddField("Muted until", $"{ Extensions.FormatDateTime(targetTime)}")
            .AddField("Mute id", muteData.ID);

            await guild.GetTextChannel(Global.PostTargets[PostTarget.MUTE_LOG]).SendMessageAsync(embed: builder.Build());

            // in case the mute is shorter than the timer defined in Mutetimer.cs, we better just start the unmuting process directly
            if (targetTime <= DateTime.Now.AddMinutes(60))
            {
                var difference = targetTime - DateTime.Now;
                MuteTimerManager.UnmuteUserIn(user.Id, difference, muteData.ID);
                using (var db = new Database())
                {
                    db.Mutes.AsQueryable().Where(m => m.ID == muteData.ID).First().UnmuteScheduled = true;
                    db.SaveChanges();
                }
            }

            return(CustomResult.FromSuccess());
        }
Exemple #3
0
 public void Process(Mute mute)
 {
 }
        public async Task <RuntimeResult> MuteUser(IGuildUser user, params string[] arguments)
        {
            if (user.IsBot)
            {
                return(CustomResult.FromError("You can't mute bots."));
            }

            if (user.GuildPermissions.PrioritySpeaker)
            {
                return(CustomResult.FromError("You can't mute staff."));
            }

            if (arguments.Length < 1)
            {
                return(CustomResult.FromError("The correct usage is `;mute <duration> <reason>`"));
            }

            string durationStr = arguments[0];

            string reason;

            if (arguments.Length > 1)
            {
                string[] reasons = new string[arguments.Length - 1];
                Array.Copy(arguments, 1, reasons, 0, arguments.Length - 1);
                reason = string.Join(" ", reasons);
            }
            else
            {
                return(CustomResult.FromError("You need to provide a reason."));
            }

            CaptureCollection captures = Regex.Match(durationStr, @"(\d+[a-z]+)+").Groups[1].Captures;

            DateTime targetTime = DateTime.Now;
            // this basically means *one* of the values has been wrong, maybe negative or something like that
            bool validFormat = false;

            foreach (Capture capture in captures)
            {
                // this means, that one *valid* unit has been found, not necessarily a valid valid, this is needed for the case, in which there is
                // no valid value possible (e.g. 3y), this would cause the for loop to do nothing, but we are unaware of that
                bool timeUnitApplied = false;
                foreach (char format in timeFormats)
                {
                    var captureValue = capture.Value;
                    // this check is needed in order that our durationSplit check makes sense
                    // if the format is not present, the split would return a wrong value, and the check would be wrong
                    if (captureValue.Contains(format))
                    {
                        timeUnitApplied = true;
                        var durationSplit = captureValue.Split(format);
                        var isNumeric     = int.TryParse(durationSplit[0], out int n);
                        if (durationSplit.Length == 2 && durationSplit[1] == "" && isNumeric && n > 0)
                        {
                            switch (format)
                            {
                            case 'm': targetTime = targetTime.AddMinutes(n); break;

                            case 'h': targetTime = targetTime.AddHours(n); break;

                            case 'd': targetTime = targetTime.AddDays(n); break;

                            case 'w': targetTime = targetTime.AddDays(n * 7); break;

                            case 's': targetTime = targetTime.AddSeconds(n); break;

                            default: validFormat = false; goto AfterLoop;
                            }
                            validFormat = true;
                        }
                        else
                        {
                            validFormat = false;
                            goto AfterLoop;
                        }
                    }
                }
                if (!timeUnitApplied)
                {
                    validFormat = false;
                    break;
                }
            }

AfterLoop:
            if (!validFormat)
            {
                return(CustomResult.FromError("Invalid format, it needs to be positive, and combinations of " + string.Join(", ", timeFormats)));
            }

            var author = Context.Message.Author;

            var guild         = Context.Guild;
            var mutedRoleName = "textmuted";

            if (!Global.Roles.ContainsKey(mutedRoleName))
            {
                return(CustomResult.FromError("Text mute role has not been configured. Check your DB entry!"));
            }

            mutedRoleName = "voicemuted";
            if (!Global.Roles.ContainsKey(mutedRoleName))
            {
                return(CustomResult.FromError("Voice mute role has not been configured. Check your DB entry!"));
            }

            await Extensions.MuteUser(user);

            var muteData = new Mute
            {
                MuteDate    = DateTime.Now,
                UnmuteDate  = targetTime,
                MutedUser   = user.Username + '#' + user.Discriminator,
                MutedUserID = user.Id,
                MutedByID   = author.Id,
                MutedBy     = author.Username + '#' + author.Discriminator,
                Reason      = reason,
                MuteEnded   = false
            };

            using (var db = new Database())
            {
                db.Mutes.Add(muteData);
                db.SaveChanges();
            }

            var builder = new EmbedBuilder();

            builder.Title = "A user has been muted!";
            builder.Color = Color.Red;

            builder.Timestamp = Context.Message.Timestamp;

            builder.ThumbnailUrl = user.GetAvatarUrl();

            const string discordUrl = "https://discordapp.com/channels/{0}/{1}/{2}";

            builder.AddField("Muted User", Extensions.FormatUserName(user))
            .AddField("Muted by", Extensions.FormatUserName(author))
            .AddField("Location of the mute",
                      $"[#{Context.Message.Channel.Name}]({string.Format(discordUrl, Context.Guild.Id, Context.Channel.Id, Context.Message.Id)})")
            .AddField("Reason", reason ?? "No reason was provided.")
            .AddField("Muted until", $"{ targetTime:dd.MM.yyyy HH:mm}")
            .AddField("Mute id", muteData.ID);

            await guild.GetTextChannel(Global.Channels["mutes"]).SendMessageAsync(embed: builder.Build());

            // in case the mute is shorter than the timer defined in Mutetimer.cs, we better just start the unmuting process directly
            if (targetTime <= DateTime.Now.AddMinutes(60))
            {
                var difference = targetTime - DateTime.Now;
                MuteTimerManager.UnmuteUserIn(user.Id, difference, muteData.ID);
            }

            return(CustomResult.FromSuccess());
        }
 public virtual void Visit(Mute mute)
 {
     Print(mute);
 }
 // Use this for initialization
 void OnEnable()
 {
     muter = gameObject.GetComponent <Mute> ();
     ChangeTexture(!muter.GetMute());
 }
Exemple #7
0
 public AVMuteCommand(Mute setting)
 {
     _cmdDetail = setting;
 }
Exemple #8
0
        public override void Visit(Mute mute)
        {
            var obj = new MuteSender(mute.Victim, mute.Duration);

            _websocket.Send($"MUTE {JsonConvert.SerializeObject(obj)}");
        }
Exemple #9
0
        private static async Task ActionUsers(IEnumerable <ulong> userIds, ulong guildId, string action)
        {
            Server server = await DatabaseQueries.GetOrCreateServerAsync(guildId);

            SocketGuild guild      = ConfigProperties.Client.GetGuild(guildId);
            var         guildUsers = new List <SocketGuildUser>();

            foreach (ulong userId in userIds)
            {
                SocketGuildUser guildUser = guild.GetUser(userId);

                if (guildUser != null)
                {
                    guildUsers.Add(guildUser);
                }
            }

            if (guildUsers.Count == 0)
            {
                await ConsoleLogger.LogAsync($"The antiraid service was triggered in guild: {guild.Id} " +
                                             "but no guild users were found from the provided set of IDs!", LogLvl.WARN);

                return;
            }

            KaguyaEvents.TriggerRaid(new AntiRaidEventArgs(guildUsers, guild, action));

            // We need to message the actioned users, if applicable, before actioning.

            if (!string.IsNullOrWhiteSpace(server.AntiraidPunishmentDirectMessage))
            {
                foreach (SocketGuildUser guildUser in guildUsers)
                {
                    // content must be inside the foreach because of how we modify it below
                    // on a per-user basis.
                    string content = server.AntiraidPunishmentDirectMessage;

                    var embed = new KaguyaEmbedBuilder(EmbedColor.ORANGE)
                    {
                        Title       = "Kaguya Anti-Raid Notification",
                        Description = content
                    };

                    var sb = new StringBuilder(content);

                    sb = sb.Replace("{USERNAME}", guildUser.UsernameAndDescriminator());
                    sb = sb.Replace("{USERMENTION}", guildUser.Mention);
                    sb = sb.Replace("{SERVER}", guild.Name);
                    sb = sb.Replace("{PUNISHMENT}", FormattedAntiraidPunishment(action.ToLower()));

                    embed.Description = sb.ToString();

                    try
                    {
                        await guildUser.SendEmbedAsync(embed);
                    }
                    catch (HttpException httpEx)
                    {
                        await ConsoleLogger.LogAsync(
                            $"Tried to send user {guildUser.Id} a custom anti-raid DM notification " +
                            $"from guild [Name: {guild.Name} | ID: {guild.Id}] but failed to do so due to " +
                            $"an Http Exception (Failure Reason: {httpEx.Reason})", LogLvl.WARN);
                    }
                    catch (Exception ex)
                    {
                        await ConsoleLogger.LogAsync(ex, $"An unexpected error occurred when attempting to send user {guildUser.Id} a custom " +
                                                     $"anti-raid DM notification from guild [Name: {guild.Name} | ID: {guild.Id}].\n");
                    }
                }
            }

            switch (server.AntiRaid.Action.ToLower())
            {
            case "mute":
                var mute = new Mute();
                foreach (SocketGuildUser user in guildUsers)
                {
                    try
                    {
                        await mute.AutoMute(user);
                    }
                    catch (Exception)
                    {
                        await ConsoleLogger.LogAsync("Attempted to auto-mute user " +
                                                     $"{user.ToString() ?? "NULL"} as " +
                                                     "part of the antiraid service, but " +
                                                     "an exception was thrown!!", LogLvl.ERROR);
                    }
                }

                break;

            case "kick":
                var kick = new Kick();
                foreach (SocketGuildUser user in guildUsers)
                {
                    try
                    {
                        await kick.AutoKickUserAsync(user, "Kaguya Anti-Raid protection.");
                    }
                    catch (Exception)
                    {
                        await ConsoleLogger.LogAsync("Attempted to auto-kick user " +
                                                     $"{user.ToString() ?? "NULL"} as " +
                                                     "part of the antiraid service, but " +
                                                     "an exception was thrown!!", LogLvl.ERROR);
                    }
                }

                break;

            case "shadowban":
                var sb = new Shadowban();
                foreach (SocketGuildUser user in guildUsers)
                {
                    try
                    {
                        await sb.AutoShadowbanUserAsync(user);
                    }
                    catch (Exception)
                    {
                        await ConsoleLogger.LogAsync("Attempted to auto-shadowban user " +
                                                     $"{user.ToString() ?? "NULL"} as " +
                                                     "part of the antiraid service, but " +
                                                     "an exception was thrown!!", LogLvl.ERROR);
                    }
                }

                break;

            case "ban":
                var ban = new Ban();
                foreach (SocketGuildUser user in guildUsers)
                {
                    try
                    {
                        await ban.AutoBanUserAsync(user, "Kaguya Anti-Raid protection.");
                    }
                    catch (Exception)
                    {
                        await ConsoleLogger.LogAsync("Attempted to auto-ban user " +
                                                     $"{user.ToString() ?? "NULL"} as " +
                                                     "part of the antiraid service, but " +
                                                     "an exception was thrown!!", LogLvl.ERROR);
                    }
                }

                break;

            default:
                await ConsoleLogger.LogAsync("Antiraid service triggered, but no users actioned. " +
                                             "Antiraid action string is different than expected. " +
                                             "Expected \"mute\" \"kick\" \"shadowban\" OR \"ban\". " +
                                             $"Received: '{action.ToLower()}'. " +
                                             $"Guild: {guildId}.", LogLvl.ERROR);

                break;
            }

            await ConsoleLogger.LogAsync($"Antiraid: Successfully actioned {guildUsers.Count:N0} users in guild {guild.Id}.", LogLvl.INFO);
        }
Exemple #10
0
 static Mute()
 {
     Instance = new Mute();
 }
Exemple #11
0
        public void Invoke(DiscordHandler client, CommandHandler handler, CommandEventArg args)
        {
            using DBContext c = new DBContext();
            DiscordGuildConfig dgc = args.Config;

            if (dgc == null || dgc.MutedRoleId == 0)
            {
                args.Channel.SendMessageAsync("You need to setup your muted role first in the config");
                return;
            }

            args.Parameters[0] = args.Parameters[0].Trim('<', '@', '!', '>');

            DiscordMember member = null;

            if (ulong.TryParse(args.Parameters[0], out ulong uid))
            {
                try
                {
                    member = args.Guild.GetMemberAsync(uid).ConfigureAwait(false).GetAwaiter().GetResult();
                }
                catch (DSharpPlus.Exceptions.NotFoundException)
                {
                }
            }

            if (member == null)
            {
                HelpCommand.ShowHelp(args.Channel, this, "Could not find member or parse id: " + args.Parameters[0]);
                return;
            }

            if (!long.TryParse(args.Parameters[1], out long durationM))
            {
                HelpCommand.ShowHelp(args.Channel, this, "Failed to parse duration: " + args.Parameters[1]);
                return;
            }

            var  drole = args.Guild.GetRole((ulong)dgc.MutedRoleId);
            Mute m;

            if (member.Roles.Contains(drole))
            {
                //Update duration if diffrent
                m = c.Mute.FirstOrDefault(mu => mu.DiscordGuildId == (long)args.Guild.Id && mu.DiscordUserId == (long)uid && !mu.Unmuted);

                if (m != null)
                {
                    if (m.DurationM == durationM)
                    {
                        args.Channel.SendMessageAsync("Not updated, time is the same");
                        return;
                    }

                    m.DurationM = durationM;
                    c.Mute.Update(m);
                    c.SaveChanges();

                    args.Channel.SendMessageAsync("Updated duration");

                    return;
                }
                else
                {
                    member.RevokeRoleAsync(drole, "invalid mute, revoking").ConfigureAwait(false).GetAwaiter().GetResult();
                }
            }

            if (args.Parameters.Count < 3)
            {
                HelpCommand.ShowHelp(args.Channel, this);
                return;
            }

            StringBuilder reasonBuilder = new StringBuilder(args.Parameters[2]);

            for (int i = 3; i < args.Parameters.Count; i++)
            {
                reasonBuilder.Append(" " + args.Parameters[i]);
            }

            m = new Mute((long)uid, (long)args.Guild.Id, DateTime.UtcNow, durationM, args.ParameterString.Remove(0, args.Parameters[0].Length + args.Parameters[1].Length + 2));

            member.GrantRoleAsync(drole, $"muted by {args.User.Username} for {durationM} minutes, reason: {m.Reason}");

            c.Mute.Add(m);
            c.SaveChanges();

            args.Channel.SendMessageAsync($"Muted {member.Username} for {durationM} minutes, reason: {m.Reason}");
        }
Exemple #12
0
 private void Awake()
 {
     Instance = this;
 }
Exemple #13
0
        public async Task MuteAsync(SocketGuildUser targetFake, string time, [Remainder] string reason)
        {
            //VARIABLES
            var user      = Context.User as SocketGuildUser;
            var staffRole = user.Roles.FirstOrDefault(x => x.Name == "Staff");

            //If the user has the staff role
            if (staffRole != null)
            {
                //Get the server recs
                var serverRecs = MongoCRUD.Instance.LoadRecords <GuildModel>("Servers");
                //Gets the index of the recs array where the guild id is equal to the guild the command was used in
                int index = serverRecs.IndexOf(serverRecs.Where(p => p.GuildID == Context.Guild.Id.ToString()).FirstOrDefault());
                //Create a moderator object
                Moderator moderator = new Moderator
                {
                    Username      = Context.User.Username,
                    Discriminator = Context.User.DiscriminatorValue,
                    id            = Context.User.Id
                };
                //Create a target object
                Target target = new Target
                {
                    Username      = targetFake.Username,
                    Discriminator = targetFake.DiscriminatorValue,
                    id            = targetFake.Id
                };
                //Create the muteModel object
                Mute muteModel = new Mute
                {
                    TimeMuted = System.DateTime.Now,
                    Reason    = reason,
                    Moderator = moderator,
                    Target    = target
                };
                #region Adding time stuff
                //If 2nd arg contains D
                if (time.Contains("d"))
                {
                    //Get the time string and remove the D
                    var realTime = time.Substring(0, time.Length - 1);
                    //Set the muteModel.Duration to the time string
                    muteModel.Duration = time;

                    //Create a new TimeSpam for the duration of the mute
                    System.TimeSpan duration = new System.TimeSpan(int.Parse(realTime), 0, 0, 0);
                    //Create a DateTime for when the mute is scheduled to end
                    DateTime endMute = System.DateTime.Now.Add(duration);
                    //Set muteModel.MuteFinished to endMute
                    muteModel.MuteFinished = endMute;
                }
                //If 2nd arg contains H
                else if (time.Contains("h"))
                {
                    //Get the time string and remove the H
                    var realTime = time.Substring(0, time.Length - 1);
                    //Set the muteModel.Duration to the time string
                    muteModel.Duration = time;
                    //Create a new TimeSpam for the duration of the mute
                    System.TimeSpan duration = new System.TimeSpan(0, int.Parse(realTime), 0, 0);
                    //Create a DateTime for when the mute is scheduled to end
                    DateTime endMute = System.DateTime.Now.Add(duration);
                    //Set muteModel.MuteFinished to endMute
                    muteModel.MuteFinished = endMute;
                }
                //If 2nd arg contains M
                else if (time.Contains("m"))
                {
                    //Get the time string and remove the M
                    var realTime = time.Substring(0, time.Length - 1);
                    //Set the muteModel.Duration to the time string
                    muteModel.Duration = time;
                    //Create a new TimeSpam for the duration of the mute
                    System.TimeSpan duration = new System.TimeSpan(0, 0, int.Parse(realTime), 0);
                    //Create a DateTime for when the mute is scheduled to end
                    DateTime endMute = System.DateTime.Now.Add(duration);
                    //Set muteModel.MuteFinished to endMute
                    muteModel.MuteFinished = endMute;
                }
                #endregion
                //Add the mute to the mutes array inside the ServerRec
                serverRecs[index].Mutes.Add(muteModel);
                //Update the records
                MongoCRUD.Instance.UpdateRecord("Servers", serverRecs[index].GuildID.ToString(), serverRecs[index]);

                //Get the muteRole object from the guild
                var muteRole = Context.Guild.Roles.FirstOrDefault(r => r.Name == "Muted");

                //Add the muteRole to the user
                await targetFake.AddRoleAsync(muteRole);

                //Create the EmbedBuilder object
                EmbedBuilder builder = new EmbedBuilder();

                //Add information to the builder object
                builder.WithTitle($"**You have been muted in {Context.Guild.Name}**").WithDescription($"Duration: {time}\nReason: {reason}").WithColor(Discord.Color.Red)
                .WithFooter("If you think this was an error, please contact a server moderator.");

                //Send the target a direct message with the embed
                await targetFake.SendMessageAsync("", false, builder.Build());

                //Reply to the user
                await ReplyAsync($"<@{targetFake.Id}> was muted by <@{Context.User.Id}>.\n" +
                                 $"Duration: {time}\n" +
                                 $"Reason: {reason}");
            }
            //If the user doesn't have the staff role
            else
            {
                //Reply to the user
                await ReplyAsync("You do not have permission to use this command.");
            }
        }
Exemple #14
0
 public AVMuteCommand(Mute setting)
 {
     _cmdDetail = setting;
 }
        public async Task <RuntimeResult> MuteUser(IGuildUser user, params string[] arguments)
        {
            if (user.IsBot)
            {
                return(CustomResult.FromError("You can't mute bots."));
            }

            if (user.GuildPermissions.PrioritySpeaker)
            {
                return(CustomResult.FromError("You can't mute staff."));
            }

            if (arguments.Length < 1)
            {
                return(CustomResult.FromError("The correct usage is `;mute <duration> <reason>`"));
            }

            string   durationStr = arguments[0];
            TimeSpan span        = Extensions.GetTimeSpanFromString(durationStr);
            var      now         = DateTime.Now;
            DateTime targetTime  = now.Add(span);

            string reason;

            if (arguments.Length > 1)
            {
                string[] reasons = new string[arguments.Length - 1];
                Array.Copy(arguments, 1, reasons, 0, arguments.Length - 1);
                reason = string.Join(" ", reasons);
            }
            else
            {
                return(CustomResult.FromError("You need to provide a reason."));
            }

            var author = Context.Message.Author;

            var guild         = Context.Guild;
            var mutedRoleName = "textmuted";

            if (!Global.Roles.ContainsKey(mutedRoleName))
            {
                return(CustomResult.FromError("Text mute role has not been configured. Check your DB entry!"));
            }

            mutedRoleName = "voicemuted";
            if (!Global.Roles.ContainsKey(mutedRoleName))
            {
                return(CustomResult.FromError("Voice mute role has not been configured. Check your DB entry!"));
            }

            await Extensions.MuteUser(user);

            await user.ModifyAsync(x => x.Channel = null);

            try
            {
                const string muteMessage = "You were muted on r/OnePlus for the following reason: {0} until {1} {2}.";
                await user.SendMessageAsync(string.Format(muteMessage, reason, targetTime, TimeZoneInfo.Local));
            }
            catch (HttpException)
            {
                Console.WriteLine("Seems like user disabled the DMs, cannot send message about the mute.");
            }

            var muteData = new Mute
            {
                MuteDate    = now,
                UnmuteDate  = targetTime,
                MutedUser   = user.Username + '#' + user.Discriminator,
                MutedUserID = user.Id,
                MutedByID   = author.Id,
                MutedBy     = author.Username + '#' + author.Discriminator,
                Reason      = reason,
                MuteEnded   = false
            };

            using (var db = new Database())
            {
                db.Mutes.Add(muteData);
                db.SaveChanges();
            }

            var builder = new EmbedBuilder();

            builder.Title = "A user has been muted!";
            builder.Color = Color.Red;

            builder.Timestamp = Context.Message.Timestamp;

            builder.ThumbnailUrl = user.GetAvatarUrl();

            const string discordUrl = "https://discordapp.com/channels/{0}/{1}/{2}";

            builder.AddField("Muted User", Extensions.FormatUserName(user))
            .AddField("Muted by", Extensions.FormatUserName(author))
            .AddField("Location of the mute",
                      $"[#{Context.Message.Channel.Name}]({string.Format(discordUrl, Context.Guild.Id, Context.Channel.Id, Context.Message.Id)})")
            .AddField("Reason", reason ?? "No reason was provided.")
            .AddField("Muted until", $"{ targetTime:dd.MM.yyyy HH:mm}")
            .AddField("Mute id", muteData.ID);

            await guild.GetTextChannel(Global.PostTargets[PostTarget.MUTE_LOG]).SendMessageAsync(embed: builder.Build());

            // in case the mute is shorter than the timer defined in Mutetimer.cs, we better just start the unmuting process directly
            if (targetTime <= DateTime.Now.AddMinutes(60))
            {
                var difference = targetTime - DateTime.Now;
                MuteTimerManager.UnmuteUserIn(user.Id, difference, muteData.ID);
                using (var db = new Database())
                {
                    db.Mutes.Where(m => m.ID == muteData.ID).First().UnmuteScheduled = true;
                    db.SaveChanges();
                }
            }

            return(CustomResult.FromSuccess());
        }
 public void Visit(Mute mute)
 {
     throw new NotImplementedException();
 }
Exemple #17
0
        private object DoAdminActionOnUser(
            Func <Tuple <Client, User> > fetch,
            Func <HttpResponseMessage> onError,
            AdminActions adminAction,
            AdminActionParameters actionParameters
            )
        {
            var(client, user) = fetch();

            if (user == null)
            {
                return(onError());
            }

            var player   = client?.Entity;
            var targetIp = client?.GetIp() ?? "";

            switch (adminAction)
            {
            case AdminActions.Ban:
                if (string.IsNullOrEmpty(Ban.CheckBan(user, "")))
                {
                    Ban.Add(
                        user.Id, actionParameters.Duration, actionParameters.Reason ?? "",
                        actionParameters.Moderator ?? @"api", actionParameters.Ip ? targetIp : ""
                        );

                    client?.Disconnect();
                    PacketSender.SendGlobalMsg(Strings.Account.banned.ToString(user.Name));

                    return(Request.CreateMessageResponse(
                               HttpStatusCode.OK, Strings.Account.banned.ToString(user.Name)
                               ));
                }
                else
                {
                    return(Request.CreateMessageResponse(
                               HttpStatusCode.BadRequest, Strings.Account.alreadybanned.ToString(user.Name)
                               ));
                }

            case AdminActions.UnBan:
                Ban.Remove(user.Id);
                PacketSender.SendGlobalMsg(Strings.Account.unbanned.ToString(user.Name));

                return(Request.CreateMessageResponse(
                           HttpStatusCode.OK, Strings.Account.unbanned.ToString(user.Name)
                           ));

            case AdminActions.Mute:
                if (string.IsNullOrEmpty(Mute.FindMuteReason(user.Id, "")))
                {
                    Mute.Add(
                        user, actionParameters.Duration, actionParameters.Reason ?? "",
                        actionParameters.Moderator ?? @"api", actionParameters.Ip ? targetIp : ""
                        );

                    PacketSender.SendGlobalMsg(Strings.Account.muted.ToString(user.Name));

                    return(Request.CreateMessageResponse(
                               HttpStatusCode.OK, Strings.Account.muted.ToString(user.Name)
                               ));
                }
                else
                {
                    return(Request.CreateMessageResponse(
                               HttpStatusCode.BadRequest, Strings.Account.alreadymuted.ToString(user.Name)
                               ));
                }

            case AdminActions.UnMute:
                Mute.Remove(user);
                PacketSender.SendGlobalMsg(Strings.Account.unmuted.ToString(user.Name));

                return(Request.CreateMessageResponse(
                           HttpStatusCode.OK, Strings.Account.unmuted.ToString(user.Name)
                           ));

            case AdminActions.WarpTo:
                if (player != null)
                {
                    var mapId = actionParameters.MapId == Guid.Empty ? player.MapId : actionParameters.MapId;
                    player.Warp(mapId, (byte)player.X, (byte)player.Y);

                    return(Request.CreateMessageResponse(
                               HttpStatusCode.OK, $@"Warped '{player.Name}' to {mapId} ({player.X}, {player.Y})."
                               ));
                }

                break;

            case AdminActions.WarpToLoc:
                if (player != null)
                {
                    var mapId = actionParameters.MapId == Guid.Empty ? player.MapId : actionParameters.MapId;
                    player.Warp(mapId, actionParameters.X, actionParameters.Y, true);

                    return(Request.CreateMessageResponse(
                               HttpStatusCode.OK,
                               $@"Warped '{player.Name}' to {mapId} ({actionParameters.X}, {actionParameters.Y})."
                               ));
                }

                break;

            case AdminActions.Kick:
                if (client != null)
                {
                    client.Disconnect(actionParameters.Reason);
                    PacketSender.SendGlobalMsg(Strings.Player.serverkicked.ToString(player?.Name));

                    return(Request.CreateMessageResponse(
                               HttpStatusCode.OK, Strings.Player.serverkicked.ToString(player?.Name)
                               ));
                }

                break;

            case AdminActions.Kill:
                if (client != null && client.Entity != null)
                {
                    lock (client.Entity.EntityLock)
                    {
                        client.Entity.Die();
                    }

                    PacketSender.SendGlobalMsg(Strings.Player.serverkilled.ToString(player?.Name));

                    return(Request.CreateMessageResponse(
                               HttpStatusCode.OK, Strings.Commandoutput.killsuccess.ToString(player?.Name)
                               ));
                }

                break;

            case AdminActions.WarpMeTo:
            case AdminActions.WarpToMe:
                return(Request.CreateErrorResponse(
                           HttpStatusCode.BadRequest, $@"'{adminAction.ToString()}' not supported by the API."
                           ));

            case AdminActions.SetSprite:
            case AdminActions.SetFace:
            case AdminActions.SetAccess:
            default:
                return(Request.CreateErrorResponse(HttpStatusCode.NotImplemented, adminAction.ToString()));
            }

            return(Request.CreateErrorResponse(HttpStatusCode.NotFound, Strings.Player.offline));
        }
Exemple #18
0
 public async Task Unmute(SocketGuildUser mentionedUser)
 {
     var mute = new Mute();
     await mute.Unmute(Context, mentionedUser);
 }
Exemple #19
0
 public async Task SetMuteRole(SocketRole role)
 {
     var mute = new Mute();
     await mute.SetMuteRole(Context, role);
 }
Exemple #20
0
 public async Task Mute(SocketGuildUser mentionedUser, string mutePeriod, [Remainder] string reason)
 {
     var mute = new Mute();
     await mute.AddMute(Context, mentionedUser, mutePeriod, reason);
 }
Exemple #21
0
 public static E TriggerRelease(double t0, double e0, Amplitude sustainLevel, double release)
 => (t)
 => !HasElapsed(t0, t, release)
             ? Release(t0, e0 > Normalize(sustainLevel) ? e0 : Normalize(sustainLevel), release)(t)
             : Mute()(t);
Exemple #22
0
 public static void ToggleMute()
 {
     Mute.Click();
 }
Exemple #23
0
        public static async Task OnWarn(IModeratorEventArgs warnArgs)
        {
            var currentSettings = await DatabaseQueries.GetFirstForServerAsync <WarnSetting>(warnArgs.Server.ServerId);

            if (currentSettings == null)
            {
                return;
            }

            List <WarnedUser> currentWarnings = await DatabaseQueries.GetAllForServerAndUserAsync <WarnedUser>(warnArgs.ActionedUser.Id, warnArgs.Server.ServerId);

            int warnCount = currentWarnings.Count;

            SocketGuildUser guildUser = ConfigProperties.Client.GetGuild(warnArgs.ActionedUser.Id).GetUser(warnArgs.ActionedUser.Id);

            int?muteNum      = currentSettings.Mute;
            int?kickNum      = currentSettings.Kick;
            int?shadowbanNum = currentSettings.Shadowban;
            int?banNum       = currentSettings.Ban;

            if (warnCount == banNum)
            {
                var ban = new Ban();

                try
                {
                    await ban.AutoBanUserAsync(guildUser, "User has been automatically banned due to " +
                                               $"reaching the specified warning threshold for bans " +
                                               $"({warnCount} warnings).");

                    await ConsoleLogger.LogAsync($"User [{guildUser} | {guildUser.Id}] has been " +
                                                 $"automatically banned in guild " +
                                                 $"[{guildUser.Guild} | {guildUser.Guild.Id}]", LogLvl.DEBUG);
                }
                catch (Exception e)
                {
                    await ConsoleLogger.LogAsync($"An attempt was made to auto-ban a user " +
                                                 $"who hit the warn threshold for this event " +
                                                 $"to take place. This failed due to an exception.\n" +
                                                 $"Exception Message: {e.Message}\n" +
                                                 $"Inner Exception Message: {e.InnerException?.Message}\n" +
                                                 $"Guild: {warnArgs.Server.ServerId}", LogLvl.WARN);
                }

                return;
            }

            if (warnCount == shadowbanNum)
            {
                var shadowban = new Shadowban();

                try
                {
                    await shadowban.AutoShadowbanUserAsync(guildUser);

                    await ConsoleLogger.LogAsync($"User [{guildUser} | {guildUser.Id}] has been " +
                                                 $"automatically shadowbanned in guild " +
                                                 $"[{guildUser.Guild} | {guildUser.Guild.Id}]", LogLvl.DEBUG);
                }
                catch (Exception e)
                {
                    await ConsoleLogger.LogAsync($"An attempt was made to auto-shadowban a user " +
                                                 $"who hit the warn threshold for this event " +
                                                 $"to take place. This failed due to an exception.\n" +
                                                 $"Exception Message: {e.Message}\n" +
                                                 $"Inner Exception Message: {e.InnerException?.Message}\n" +
                                                 $"Guild: {warnArgs.Server.ServerId}", LogLvl.WARN);
                }

                return;
            }

            if (warnCount == kickNum)
            {
                var kick = new Kick();

                try
                {
                    await kick.AutoKickUserAsync(guildUser, $"User has been automatically kicked due to " +
                                                 $"reaching the specified warning threshold for kicks " +
                                                 $"({warnCount} warnings).");

                    await ConsoleLogger.LogAsync($"User [{guildUser} | {guildUser.Id}] has been " +
                                                 $"automatically kicked in guild " +
                                                 $"[{guildUser.Guild} | {guildUser.Guild.Id}]", LogLvl.DEBUG);
                }
                catch (Exception e)
                {
                    await ConsoleLogger.LogAsync($"An attempt was made to auto-kick a user " +
                                                 $"who hit the warn threshold for this event " +
                                                 $"to take place. This failed due to an exception.\n" +
                                                 $"Exception Message: {e.Message}\n" +
                                                 $"Inner Exception Message: {e.InnerException?.Message}\n" +
                                                 $"Guild: {warnArgs.Server.ServerId}", LogLvl.WARN);
                }

                return;
            }

            if (warnCount == muteNum)
            {
                var mute = new Mute();

                try
                {
                    await mute.AutoMute(guildUser);

                    await ConsoleLogger.LogAsync($"User [{guildUser} | {guildUser.Id}] has been " +
                                                 $"automatically muted in guild " +
                                                 $"[{guildUser.Guild} | {guildUser.Guild.Id}]", LogLvl.DEBUG);
                }
                catch (Exception e)
                {
                    await ConsoleLogger.LogAsync($"An attempt was made to auto-mute a user " +
                                                 $"who hit the warn threshold for this event " +
                                                 $"to take place. This failed due to an exception.\n" +
                                                 $"Exception Message: {e.Message}\n" +
                                                 $"Inner Exception Message: {e.InnerException?.Message}\n" +
                                                 $"Guild: {warnArgs.Server.ServerId}", LogLvl.WARN);
                }
            }
        }
Exemple #24
-1
    // Use this for initialization
    void Start()
    {
        // Audio component
        bgm = Audio.mainbgm.GetComponent<AudioSource> ();

        // Check if a mute gameobject exists, if so delete this gameobject
        if (mutecur == null) {
            DontDestroyOnLoad (gameObject); //this gameobject will persist from scene to scene
            mutecur = this;
        } else if (mutecur != this) {
            Destroy (gameObject);
        }

        // UI button components
        mute = GetComponent<Button> ();
        // Add listener to button
        mute.onClick.AddListener (() => {
            VolControl ();});
        // Retrieve past mute info from persistent data
        muted = StatsManager.stats.muted;

        // Initial button text according to previous game data
        text = mute.GetComponentInChildren<Text> ();
        if (muted == 1) {
            text.text = "UNMUTE";
            bgm.volume = 0;
        } else {
            text.text = "MUTE";
            bgm.volume = 0.7f;
        }
        // Disallow multiple clicks until sound fully fades in or out
        clicked = false;
    }
Exemple #25
-1
        private async Task _client_MessageReceived_Blacklist(SocketMessage m)
        {
            if (m.Author.Id == _client.CurrentUser.Id)
            {
                return;
            }
            var author = m.Author as SocketGuildUser;

            if (author == null)
            {
                return;
            }
            var guild = (m.Channel as SocketGuildChannel)?.Guild;

            if (guild == null)
            {
                return;
            }
            if (author.Roles.Select(r => r.Id).Any(x => _config.BypassIds.Contains(x)))
            {
                return;
            }
            var violation = CheckViolation(m);

            if (!violation.IsViolating)
            {
                return;
            }

            var muteRole = guild.GetRole(_config.MuteRoleId);
            await m.DeleteAsync();

            await author.AddRoleAsync(muteRole);

            var dmChannel = await author.GetOrCreateDMChannelAsync();

            Mute mute = null;

            if (violation.Blacklist == null)
            {
                await dmChannel.SendMessageAsync($"You've been muted for {GlobalBlacklist.MuteTime.Humanize(5)} for violating the world blacklist: `{m.Content}`");

                var name = author.Nickname == null
                    ? author.Username
                    : $"{author.Username} (nickname: {author.Nickname})";
                await _log.LogModMessageAsync($"I automatically muted **{name} ({author.Id})** for {GlobalBlacklist.MuteTime.Humanize(5)} for violating the word blacklist in {(m.Channel as SocketTextChannel).Mention}: `{m.Content}`");

                mute = await _records.AddMuteAsync(new Mute
                {
                    GuildId     = guild.Id,
                    SubjectId   = author.Id,
                    ModeratorId = 0,
                    Timestamp   = DateTime.UtcNow,
                    UnmuteAt    = DateTime.UtcNow.Add(GlobalBlacklist.MuteTime),
                    Reason      = "N/A (BLACKLIST AUTO-MUTE)",
                    Active      = true
                });
            }
            else
            {
                await dmChannel.SendMessageAsync($"You've been muted for {violation.Blacklist.MuteTime.Humanize(5)} for violating the world blacklist: `{m.Content}`");

                var name = author.Nickname == null
                    ? author.Username
                    : $"{author.Username} (nickname: {author.Nickname})";
                await _log.LogModMessageAsync($"I automatically muted **{name} ({author.Id})** for {violation.Blacklist.MuteTime.Humanize(5)} for violating the word blacklist in {(m.Channel as SocketTextChannel).Mention}: `{m.Content}`");

                mute = await _records.AddMuteAsync(new Mute
                {
                    GuildId     = guild.Id,
                    SubjectId   = author.Id,
                    ModeratorId = 0,
                    Timestamp   = DateTime.UtcNow,
                    UnmuteAt    = DateTime.UtcNow.Add(violation.Blacklist.MuteTime),
                    Reason      = "N/A (BLACKLIST AUTO-MUTE)",
                    Active      = true
                });
            }
            _records.DisposeContext();
            _unpunish.Mutes.Add(mute);
        }