Exemple #1
0
        public Task ExecuteAsync(SocketUserMessage msg, string[] parameters)
        {
            Task.Run(async() =>
            {
                if (Program.Configuration.Instance.Registered.Contains(msg.Author.Mention))

                {
                    await msg.Author.GetOrCreateDMChannelAsync();
                    await msg.Author.SendMessageAsync("You have already applied!");

                    await msg.DeleteAsync();

                    return;
                }
                else
                {
                    await msg.Author.GetOrCreateDMChannelAsync();
                    await msg.Author.SendMessageAsync("You have been registered!");

                    Program.Configuration.Instance.Registered.Add(msg.Author.Username);

                    Program.Configuration.Save();

                    await msg.DeleteAsync();
                }
            });
            return(Task.CompletedTask);
        }
Exemple #2
0
        public async Task Exit()
        {
            _forcedExit = true;

            if (lastBotMsg != null)
            {
                await lastBotMsg.DeleteAsync();
            }
        }
Exemple #3
0
        protected override async Task _MessegeResive(SocketUserMessage message)
        {
            bool res = await CheckForCommands(message);

            if (_IsDeleting || res || !users.Any(x => x.Id == message.Author.Id))
            {
                await message.DeleteAsync();

                return;
            }

            if (message.Author.Id != SelecedUserID)
            {
                await message.DeleteAsync();

                return;
            }

            if (message.Content.ToLower() == _Word.ToLower())
            {
                _HasGuessed = true;
                await PrintGame($"Your guess the word, the word was **{_Word}**");

                return;
            }

            if (message.Content.Length != 1)
            {
                await message.DeleteAsync();

                return;
            }

            timeouts[message.Author.Id] = 0;
            if (!_HasGuessed)
            {
                if (!Regex.IsMatch(message.Content.ToUpper(), @"[A-Zæøå]+"))
                {
                    await message.DeleteAsync();

                    return;
                }
                GuessLetter(message.Content.ToUpper()[0]);

                NextUser();
                SendMessege($"<@{SelecedUserID}> turn");
            }
        }
Exemple #4
0
        public Task ExecuteAsync(SocketUserMessage msg, string[] parameters)
        {
            Task.Run(async() =>
            {
                var randomObject = new Random();

                var sentMsg = await msg.Channel.SendMessageAsync("Rolling Chamber...");
                string msg1 = "";
                await Task.Delay(2000);

                switch (randomObject.Next(1, 6 + 1))
                {
                case 5:
                    msg1 = $"*click* {msg.Author.Mention} Gets to live another day!";
                    break;

                default:
                    msg1 = $"**BOOM** {msg.Author.Mention} Will forever be missed!";
                    break;
                }
                var sentMsg1 = await msg.Channel.SendMessageAsync(msg1);

                await Task.Delay(10000);

                await sentMsg.DeleteAsync();
                await sentMsg1.DeleteAsync();
                await msg.DeleteAsync();
            });
            return(Task.CompletedTask);
        }
        private async Task DeleteMsgAndInfractUser(SocketUserMessage s, string message)
        {
            SocketGuildUser target = s.Author as SocketGuildUser;

            IReadOnlyCollection <SocketMessage> nearbyMessages = s.Channel.GetCachedMessages(s, Direction.Before, 1);
            SocketUserMessage linkMessage = nearbyMessages.Any() ? nearbyMessages.Last() as SocketUserMessage : s;
            string            url         = linkMessage.GetJumpUrl();

            // Delete message before creating infractions and notifying moderators because
            //  if something fails during infraction creation or notifying the moderators we
            //  are at least certain the message got deleted.
            await s.DeleteAsync();

            _moderationService.AddInfraction(target,
                                             Infraction.Create(_moderationService.RequestInfractionID())
                                             .WithType(InfractionType.Warning)
                                             .WithModerator(_discord.CurrentUser)
                                             .WithAdditionalInfo($"[Go near message]({url})\n**{message}**")
                                             .WithDescription("Used filtered word"));

            await _loggingService.CreateEntry(ModerationLogEntry.New
                                              .WithActionType(ModerationActionType.Filtered)
                                              .WithTarget(target)
                                              .WithReason($"[Go near message]({url})\n**{message}**")
                                              .WithTime(DateTimeOffset.Now)
                                              .WithModerator(_discord.CurrentUser));

            NotifyUser(s);
        }
Exemple #6
0
        private async Task HandleIntroMessage(SocketUserMessage message)
        {
            var guild = (message.Channel as SocketGuildChannel)?.Guild;

            if (guild == null)
            {
                return;
            }
            var introChannel = await _database.GetValue <ulong>(Keys.IntroductionChannel(guild));

            if (!introChannel.HasValue || introChannel.Value != message.Channel.Id)
            {
                return;
            }

            var introKey        = Keys.UserIntroduction(guild, message.Author);
            var previousIntroId = await _database.GetValue <ulong>(introKey);

            if (previousIntroId.HasValue)
            {
                await message.DeleteAsync();

                return;
            }
            await _database.SetValue(introKey, message.Id);
        }
Exemple #7
0
        async Task WarnUserAsync(SocketUserMessage message, GuildModel config, string warning)
        {
            var guild = (message.Author as SocketGuildUser).Guild;

            if (config.Mod.MaxWarnings == 0 || message.Author.Id == guild.OwnerId)
            {
                return;
            }
            await message.DeleteAsync();

            var profile = GuildHelper.GetProfile(guild.Id, message.Author.Id);

            if (profile.Warnings >= config.Mod.MaxWarnings)
            {
                await(message.Author as SocketGuildUser).KickAsync("Kicked By AutoMod.");
                await guild.GetTextChannel(config.Mod.TextChannel).SendMessageAsync(
                    $"**Kick** | Case {config.Mod.Cases.Count + 1}\n**User:** {message.Author} ({message.Author.Id})\n**Reason:** Reached max warnings.\n" +
                    $"**Responsible Moderator:** {Client.CurrentUser}"
                    );
            }
            else
            {
                profile.Warnings++;
                GuildHelper.SaveProfile(guild.Id, message.Author.Id, profile);
            }
            await message.Channel.SendMessageAsync(warning);
        }
Exemple #8
0
        internal async static Task HandleProfanity(SocketUserMessage message, Server server, IApiService apiService)
        {
            var checkString = message.Content.Replace(".", String.Empty).Replace('!', 'i').Replace("-", String.Empty).Replace("*", String.Empty);
            var badWords    = await GetProfanity(server, checkString);

            if (badWords.Count > 0)
            {
                var filter = await GetProfanityFilterForServer(server);

                var channel        = message.Channel as SocketGuildChannel;
                var guild          = channel.Guild;
                var loggingChannel = guild.GetChannel(server.LoggingChannel);
                var badWordsJoined = String.Join(", ", badWords);

                await message.DeleteAsync();

                if (loggingChannel != null)
                {
                    await(loggingChannel as SocketTextChannel).SendLogAsync("Profanity Filter", $"{message.Author.Mention} said a bad word: {message.Content}\nin {channel.Guild.Name}/{channel.Name}.\nWords: `{badWordsJoined}`",
                                                                            ColorHelper.GetColor(server), apiService, ImageLookupUtility.GetImageUrl("LOGGING_IMAGES"));
                }

                if (server.ProfanityFilterMode == ProfanityFilterMode.FilterCensor)
                {
                    var censored = filter.CensorString(checkString);
                    await(channel as SocketTextChannel).SendMessageAsync($"{message.Author.Mention}, please don't swear. {message.Author.Username}'s Censored message:\n{censored.Replace("*", "#")}");
                }
                else
                {
                    await(channel as SocketTextChannel).SendMessageAsync($"{message.Author.Mention}, please don't swear.");
                }
            }
        }
Exemple #9
0
        static async Task <bool> FilterHeadings(SocketUserMessage message)
        {
            if (!message.Content.StartsWith("```"))
            {
                if (message.Author.Id == botId)
                {
                    return(true);
                }

                ITextChannel channel    = (message.Channel as ITextChannel);
                ITextChannel discussion = await channel.Guild.GetChannelAsync(449033901168656403) as ITextChannel;

                await discussion.SendMessageAsync($@"Hi {message.Author.Mention} - Messages in {channel.Mention} require a heading!

To help, I've created a template for you to copy & paste. Be sure to change the placeholder text!
If you were simply trying to discuss someone elses message, this is the place to do so.
Alternatively react with a :thumbsup: to show your support.

` ```Your Heading```
{message.Content}`");

                await message.DeleteAsync();

                await ReplyAndDelete(message, $"Hi {message.Author.Mention}! Your message needs a heading! Let me help you out in {discussion.Mention}.", 10);

                return(false);
            }

            return(true);
        }
        async Task <bool> FilterScreenshots(ChannelFilter filter, SocketUserMessage message)
        {
            if (message.Attachments.Count == 0 && !message.Content.Contains(".jpg") && !message.Content.Contains(".png") && !message.Content.Contains(".gif") && !message.Content.Contains(".jpeg"))
            {
                if (filter.AlertChannel != 0)
                {
                    ITextChannel discussion = await(message.Channel as IGuildChannel).Guild.GetChannelAsync(filter.AlertChannel) as ITextChannel;

                    await discussion.SendMessageAsync(message.Author.Mention + " said in " + (message.Channel as ITextChannel).Mention + " : " + message.Content);

                    await ReplyAndDelete(message, $"Hi {message.Author.Mention}! I've copied your message to {discussion.Mention}. If you move the discussion there, we can keep this channel filled with screenshots!", 10);
                }
                else
                {
                    await ReplyAndDelete(message, $"Hi {message.Author.Mention}! Only images are allowed here!", 10);
                }

                await message.DeleteAsync();

                return(false);
            }
            else if (!CheckIfAboveMinimum(message))
            {
                // Joel, I don't know what to put here, edit it pls.
                await ReplyAndDelete(message, $"Hi {message.Author.Mention}! Make sure your image size is above 640x360!", 10);

                return(false);
            }

            return(true);
        }
Exemple #11
0
        private async Task <bool> CheckMessageDeletion(SocketUserMessage msg)
        {
            // Create a Command Context.
            var context = new SocketCommandContext(_client, msg);

            var usrId = msg.Author.Id;

            if (!Globals.Bot.Config.DeleteNonCommands || context.IsPrivate || msg.Author.IsBot || Globals.Bot.Config.CanUseSudo(usrId) || msg.Author.Id == Owner)
            {
                return(false);
            }
            if (Globals.Bot.Config.Channels.Count < 1 || !Globals.Bot.Config.Channels.Contains(context.Channel.Id))
            {
                return(false);
            }

            var msgText = msg.Content;
            var mention = msg.Author.Mention;

            var guild = msg.Channel is SocketGuildChannel g ? g.Guild.Name : "Unknown Guild";

            await Log(new LogMessage(LogSeverity.Info, "Command", $"Possible spam detected in {guild}#{msg.Channel.Name}:@{msg.Author.Username}. Content: {msg}")).ConfigureAwait(false);

            await msg.DeleteAsync(RequestOptions.Default).ConfigureAwait(false);

            await msg.Channel.SendMessageAsync($"{mention} - The order channels are for bot commands only.\nDeleted Message:```\n{msgText}\n```").ConfigureAwait(false);

            return(true);
        }
Exemple #12
0
        /// <summary>
        /// Process emote mode for a message.
        /// </summary>
        /// <param name="message">Message to process.</param>
        /// <returns>True if message was deleted.</returns>
        private static async Task <bool> ProcessMessageEmotesAsync(SocketUserMessage message)
        {
            (EmoteModeTracker.Mode mode, object args) = EmoteModeTracker.GetMode(message.Channel.Id);

            if (mode != EmoteModeTracker.Mode.Off)
            {
                if (message.Attachments.Count > 0)
                {
                    return(await DeleteMessageAsync());
                }

                List <EmoteOrEmoji> emotes = message.Content.ParseDiscordMessageEmotes();

                if (mode == EmoteModeTracker.Mode.TextOnly)
                {
                    if (emotes.Count > 0)
                    {
                        return(await DeleteMessageAsync());
                    }
                }
                else if (mode == EmoteModeTracker.Mode.EmoteOnly)
                {
                    string content = message.Content;

                    foreach (EmoteOrEmoji emote in emotes)
                    {
                        content = content.Replace(emote.ToString(), "");
                    }

                    if (!string.IsNullOrWhiteSpace(content))
                    {
                        return(await DeleteMessageAsync());
                    }
                }
                else if (mode == EmoteModeTracker.Mode.Exactly)
                {
                    if (args is string argString)
                    {
                        if (!string.Equals(message.Content, argString, StringComparison.InvariantCultureIgnoreCase))
                        {
                            return(await DeleteMessageAsync());
                        }
                    }
                }

                async Task <bool> DeleteMessageAsync()
                {
                    await message.DeleteAsync();

                    if (EmoteModeTracker.ShouldSendNotification(message.Channel.Id))
                    {
                        await message.Channel.SendMessageAsync($"The channel is currently in **{mode.Humanize().ToLower()}** mode.");
                    }

                    return(true);
                }
            }

            return(false);
        }
Exemple #13
0
        public async Task JoinGame(SocketUserMessage message)
        {
            var user = message.Author.Id;

            if (_gameStatus != GameStatus.Lobby)
            {
                await SendGeneral("Excited? Please wait until the next game starts.");

                return;
            }

            if (Players.Exists(x => x.GetId() == user))
            {
                await SendGeneral("You're already part of this game! Wait a minute.");

                return;
            }

            Players.Add(new MafiaPlayer(Client, user));
            await RefreshLobby();

            // The Send/Delete approach here is used to prevent channel clutter but also give feedback to the user.
            await message.Channel.SendMessageAsync($"<@{user}> joined the lobby.");

            await message.DeleteAsync();
        }
Exemple #14
0
        // This code is messy as heck.
        public static async Task CheckOuija(SocketUserMessage message)
        {
            if (message.Channel.Id == OuijaId)
            {
                if (message.Content.Length == 1)
                {
                    await _openOuija.AddCharacter(message.Author.Id, message.Content[0]);
                }
                else if (message.Content.ToLower().Contains("goodbye"))
                {
                    if (_openOuija != null)
                    {
                        await message.Channel.SendMessageAsync(_openOuija.GetResult());

                        _openOuija = null;
                    }
                }
                else if (message.Content.Contains("_"))
                {
                    if (_openOuija == null)
                    {
                        await message.DeleteAsync();

                        _openOuija = new Ouija(message.Author.Id, message.Content);
                        var krispyMessage = await message.Channel.SendMessageAsync(_openOuija.GetTemplate());

                        _openOuija.SetMessage(krispyMessage);
                    }
                }
            }
        }
Exemple #15
0
        /// <summary>
        /// Checks the message for spam, and if the user is muted
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="context"></param>
        /// <param name="user"></param>
        /// <returns></returns>
        private bool CheckMessageSpam(SocketUserMessage msg, SocketCommandContext context, UserAccount user)
        {
            //TODO: Better muting system
            //Check if the user is muted, if so delete the message, oh and make sure it ISN'T the owner of the guild
            if (user.GetOrCreateServer(context.Guild.Id).IsMuted&& user.Id != context.Guild.OwnerId)
            {
                msg.DeleteAsync().GetAwaiter().GetResult();
                return(false);
            }

            //Someone has mention more than 2 users, check with the anti-spam
            if (msg.MentionedUsers.Count >= 2)
            {
                if (antiSpam.CheckMentionUsers(msg, context.Guild))
                {
                    return(false);
                }
            }

            //There are role mentions
            if (msg.MentionedRoles.Count >= 1)
            {
                if (antiSpam.CheckRoleMentions(msg, (SocketGuildUser)msg.Author))
                {
                    return(false);
                }
            }

            return(true);
        }
Exemple #16
0
        public async Task LeaveGame(SocketUserMessage message)
        {
            var user = message.Author.Id;

            if (_gameStatus != GameStatus.Lobby && _gameStatus != GameStatus.InGame)
            {
                await SendGeneral("There isn't any game to leave!");

                return;
            }

            if (!Players.Exists(x => x.GetId() == user))
            {
                await SendGeneral("You aren't a part of this game.");

                return;
            }

            Players.RemoveAll(x => x.GetId() == user);
            await RefreshLobby();

            // Send/Delete approach explained above.
            await message.Channel.SendMessageAsync($"<@{user}> left the lobby.");

            await message.DeleteAsync();
        }
Exemple #17
0
        private async Task <bool> WordFiltered(IGuild guild, SocketUserMessage usrMsg)
        {
            var filteredChannelWords = Permissions.FilterCommands.FilteredWordsForChannel(usrMsg.Channel.Id, guild.Id);
            var filteredServerWords  = Permissions.FilterCommands.FilteredWordsForServer(guild.Id);
            var wordsInMessage       = usrMsg.Content.ToLowerInvariant().Split(' ');

            if (filteredChannelWords.Count != 0 || filteredServerWords.Count != 0)
            {
                foreach (var word in wordsInMessage)
                {
                    if (filteredChannelWords.Contains(word) ||
                        filteredServerWords.Contains(word))
                    {
                        try
                        {
                            await usrMsg.DeleteAsync().ConfigureAwait(false);
                        }
                        catch (HttpException ex)
                        {
                            _log.Warn("I do not have permission to filter words in channel with id " + usrMsg.Channel.Id, ex);
                        }
                        return(true);
                    }
                }
            }
            return(false);
        }
Exemple #18
0
        public static async Task Reply(SocketUserMessage userMsg, bool allowPublic, string text, Embed embed = null)
        {
            try
            {
                if (text == null)
                {
                    text = string.Empty;
                }

                if (allowPublic)
                {
                    await userMsg.Channel.SendMessageAsync(text, false, embed);
                }
                else
                {
                    await Discord.UserExtensions.SendMessageAsync(userMsg.Author, text, false, embed);

                    if (!IsPrivateMessage(userMsg))
                    {
                        await userMsg.DeleteAsync();
                    }
                }
            }
            catch (Exception)
            {
                await Nerva.Bots.Helpers.Log.Write(Log_Severity.Warning, $"Sending message to {userMsg.Author.Username} failed");
            }
        }
Exemple #19
0
        async Task WarnUserAsync(SocketUserMessage Message, GuildModel Config, string Warning)
        {
            var Guild = (Message.Author as SocketGuildUser).Guild;

            if (Config.Mod.MaxWarnings == 0 || Message.Author.Id == Guild.OwnerId)
            {
                return;
            }
            await Message.DeleteAsync();

            var Profile = GuildHelper.GetProfile(Guild.Id, Message.Author.Id);

            if (Profile.Warnings >= Config.Mod.MaxWarnings)
            {
                await(Message.Author as SocketGuildUser).KickAsync("Kicked By AutoMod.");
                await Guild.GetTextChannel(Config.Mod.TextChannel).SendMessageAsync(
                    $"**Kick** | Case {Config.Mod.Cases.Count + 1}\n**User:** {Message.Author} ({Message.Author.Id})\n**Reason:** Reached Max Warnings.\n" +
                    $"**Responsible Moderator:** {Client.CurrentUser}");

                await GuildHelper.LogAsync(Guild, Message.Author, Client.CurrentUser, CaseType.Kick, Warning);
            }
            else
            {
                Profile.Warnings++;
                GuildHelper.SaveProfile(Guild.Id, Message.Author.Id, Profile);
                await GuildHelper.LogAsync(Guild, Message.Author, Client.CurrentUser, CaseType.Warning, Warning);
            }
            await Message.Channel.SendMessageAsync(Warning);
        }
        public async Task DeleteBannedWords(SocketMessage message)
        {
            if (message is SocketSystemMessage)
            {
                return;
            }
            SocketUserMessage Message = message as SocketUserMessage;

            if (Message.Author.IsBot)
            {
                return;
            }
            if (!(Message.Channel is SocketGuildChannel))
            {
                return;
            }
            if ((Message.Author as SocketGuildUser).IsModerator())
            {
                return;
            }
            foreach (string phrase in Config.BannedWords)
            {
                if (Message.Content.Contains(phrase))
                {
                    await Message.DeleteAsync();
                    await LogAutomodAction(new AutomodAction(message, "Banned word"));

                    return;
                }
            }
            return;
        }
Exemple #21
0
        private async Task ActionsHandler(SocketUserMessage message)
        {
            try {
                string         message_lower = message.Content.ToLower();
                string         commandName   = message_lower.Split(' ')[0];
                Actions.Action action        = DataManager.actions.GetValueOrDefault(commandName);

                if (action?.CheckChannelAccessibility(message) == false)
                {
                    await message.Channel.SendMessageAsync("Commande non accessible d'ici.");

                    return;
                }
                switch (action?.Accessibility)
                {
                case Actions.Action.AccessibilityType.Usable:
                    if (action.Type == Actions.Action.ActionType.Delete)
                    {
                        await message.DeleteAsync();
                    }
                    action.Use(message);
                    break;

                case Actions.Action.AccessibilityType.Visible:
                    if (message.Author.IsAdmin())
                    {
                        action.Use(message);
                    }
                    else
                    {
                        await message.Channel.SendMessageAsync("Il faut être admin pour utiliser cette commande.");
                    }
                    break;

                case Actions.Action.AccessibilityType.Invisible:
                    if (message.Author.Id == DataManager.master_id)
                    {
                        action.Use(message);
                    }
                    break;
                }

                if (action == null)
                {
                    foreach (var action_ in DataManager.otherActions)
                    {
                        Regex regex = new Regex(action_.Regex);
                        if (regex.Match(message_lower).Success)
                        {
                            action_.Use(message);
                        }
                    }
                }
            }
            catch (System.Exception e) {
                e.DisplayException("Nouveau mode de commande => " + System.Reflection.MethodBase.GetCurrentMethod().ToString());
            }
        }
Exemple #22
0
        }; // Languages supported by Perspective API. Others message are translated to english
        public static async Task <List <string> > CheckText(SocketUserMessage msg, SocketMessage arg, ITextChannel reportChan)
        {
            if (msg.Content.Length == 0)
            {
                return(null);
            }
            var detection = await Program.P.translationClient.DetectLanguageAsync(msg.Content);

            string finalMsg            = msg.Content;
            bool   useTranslationDb    = Program.P.db.GetTranslation(((ITextChannel)msg.Channel).GuildId) == "O";
            bool   finalUseTranslation = useTranslationDb || (!allowedLanguage.Contains(detection.Language) && !useTranslationDb);

            if (finalUseTranslation)
            {
                finalMsg = (await Program.P.translationClient.TranslateTextAsync(msg.Content, "en")).TranslatedText;
            }
            using (HttpClient hc = new HttpClient())
            {
                HttpResponseMessage post = await hc.PostAsync("https://commentanalyzer.googleapis.com/v1alpha1/comments:analyze?key=" + Program.P.perspectiveApi, new StringContent(
                                                                  JsonConvert.DeserializeObject("{comment: {text: \"" + Utils.EscapeString(finalMsg) + "\"},"
                                                                                                + "languages: [\"en\"],"
                                                                                                + "requestedAttributes: {" + string.Join(":{}, ", categories.Select(x => x.Item1)) + ":{}} }").ToString(), Encoding.UTF8, "application/json"));

                dynamic      json  = JsonConvert.DeserializeObject(await post.Content.ReadAsStringAsync());
                EmbedBuilder embed = new EmbedBuilder()
                {
                    Title = "Identification"
                };
                List <string> flags = new List <string>();
                foreach (var s in categories)
                {
                    double value = json.attributeScores[s.Item1].summaryScore.value;
                    if (value >= s.Item2)
                    {
                        flags.Add(s.Item1 + "(" + value.ToString("0.00") + ")");
                    }
                }
                if (flags.Count > 0)
                {
                    string word = (reportChan == null) ? "deleted" : "reported";
                    string text = "The message of " + arg.Author.ToString() + " was " + word + " because it trigger the following flags: " + string.Join(", ", flags) + Environment.NewLine + Environment.NewLine +
                                  "Original message: ||" + msg.Content.Replace("|", "\\|") + "||";
                    if (reportChan == null)
                    {
                        await msg.DeleteAsync();

                        await arg.Channel.SendMessageAsync(text);
                    }
                    else
                    {
                        await reportChan.SendMessageAsync(text);
                    }
                }
                return(flags.Select(x => x.Split('(')[0]).ToList());
            }
        }
Exemple #23
0
        private async Task OnMessageReceived(SocketMessage message)
        {
            SocketUserMessage userMessage = (SocketUserMessage)message;

            // ensures we don't process system/other bot messages
            if (userMessage == null || message.Source != MessageSource.User)
            {
                return;
            }

            string messageString = userMessage.ToString();

            if (_commandHandler.DoesMsgContainCommandPrefix(messageString))
            {
                await _commandHandler.SelectCommandFromMessage(userMessage);
            }
            else
            {
                SocketGuildChannel guildChannel = (SocketGuildChannel)userMessage.Channel;
                if (guildChannel != null)
                {
                    List <GuildSettingsTracker.SettingsToTrack.ChannelMessageCombo> activeFilters = _settingsTracker.GetActiveFiltersForGuild(guildChannel.Guild.Id);

                    if (activeFilters != null && activeFilters.Count > 0)
                    {
                        ulong  leadingChannel = 0;
                        string leadingFilter  = string.Empty;
                        bool   foundFilter    = false;

                        foreach (var filter in activeFilters)
                        {
                            if (messageString.Contains(filter._messageToTrack))
                            {
                                if (filter._messageToTrack.Length >= leadingFilter.Length)
                                {
                                    leadingChannel = filter._channelId;
                                    leadingFilter  = filter._messageToTrack;
                                    foundFilter    = true;
                                }
                            }
                        }

                        if (foundFilter && leadingChannel != userMessage.Channel.Id)
                        {
                            string fullMessage = "**" + userMessage.Author.Username + ": **" + messageString;
                            // Don't care about the tasks, don't depend on them in any way.Also, we don't depend on any data from the methods, just care about the possible exceptions.
                            Task sendMsg = ChannelHelper.SendMessageToGuildChannel(guildChannel.Guild, leadingChannel, fullMessage).ContinueWith(t => Console.WriteLine(t.Exception), TaskContinuationOptions.OnlyOnFaulted);
                            Task dltMsg  = userMessage.DeleteAsync().ContinueWith(t => Console.WriteLine(t.Exception), TaskContinuationOptions.OnlyOnFaulted);

                            Console.WriteLine("Attempting to reroute message: \"" + fullMessage + "\"");
                        }
                    }
                }
            }
        }
Exemple #24
0
        public static async Task <List <string> > CheckImageUrl(string url, SocketUserMessage msg, SocketMessage arg, ITextChannel reportChan)
        {
            if (Utils.IsImage(url.Split('.').Last()))
            {
                var image = await Google.Cloud.Vision.V1.Image.FetchFromUriAsync(url);

                List <string>        flags    = new List <string>();
                SafeSearchAnnotation response = await Program.P.imageClient.DetectSafeSearchAsync(image);

                if (response.Adult > Likelihood.Possible || response.Medical > Likelihood.Possible ||
                    response.Racy > Likelihood.Possible || response.Violence > Likelihood.Possible)
                {
                    if (response.Adult > Likelihood.Possible)
                    {
                        flags.Add("Adult(" + response.Adult.ToString() + ")");
                    }
                    if (response.Medical > Likelihood.Possible)
                    {
                        flags.Add("Medical(" + response.Medical.ToString() + ")");
                    }
                    if (response.Racy > Likelihood.Possible)
                    {
                        flags.Add("Racy(" + response.Racy.ToString() + ")");
                    }
                    if (response.Violence > Likelihood.Possible)
                    {
                        flags.Add("Violence(" + response.Violence.ToString() + ")");
                    }
                    string fileName = "SPOILER_" + GenerateFileName() + "." + url.Split('.').Last();
                    using (HttpClient hc = new HttpClient())
                        File.WriteAllBytes(fileName, await hc.GetByteArrayAsync(url));
                    string word = (reportChan == null) ? "deleted" : "reported";
                    string text = "The message of " + arg.Author.ToString() + " was " + word + " because it trigger the following flags: " + string.Join(", ", flags);
                    if (reportChan == null)
                    {
                        await msg.Channel.SendMessageAsync(text);

                        await msg.Channel.SendFileAsync(fileName);

                        await msg.DeleteAsync();
                    }
                    else
                    {
                        await reportChan.SendMessageAsync(text);

                        await reportChan.SendFileAsync(fileName);
                    }
                    File.Delete(fileName);
                    return(flags.Select(x => x.Split('(')[0]).ToList());
                }
                flags.Add("SAFE");
                return(flags);
            }
            return(null);
        }
Exemple #25
0
        private async Task MessageReceivedHandler(SocketMessage msg)
        {
            SocketUserMessage message = msg as SocketUserMessage;

            if (message == null)
            {
                return;
            }
            SocketCommandContext context = new SocketCommandContext(_client, message);

            if (context.User.IsBot)
            {
                return;
            }
            var  server       = _main.ServerList.FirstOrDefault(x => x.ServerId == context.Guild.Id);
            bool admin        = false;
            var  hasAdminRole = context.Guild.Users.FirstOrDefault(x => x.Id == context.User.Id).Roles.FirstOrDefault(y => y.Id == server.AdminRole);

            if (hasAdminRole != null && hasAdminRole.Id == server.AdminRole)
            {
                admin = true;
            }
            int argPos = 0;

            if (message.HasStringPrefix(((Char)server.Prefix).ToString(), ref argPos) ||
                message.HasMentionPrefix(_client.CurrentUser, ref argPos))
            {
                if ((server.BotChannel != 0 && msg.Channel.Id == server.BotChannel) || server.BotChannel == 0 || admin)
                {
                    var res = await _service.ExecuteAsync(context, argPos, null);

                    if (!res.IsSuccess && res.Error != CommandError.UnknownCommand)
                    {
                        BotFrame.consoleOut($"Command Handler Error: {res.ErrorReason}");
                        return;
                    }
                    if (!res.IsSuccess && res.Error == CommandError.UnknownCommand)
                    {
                        await Task.Delay(200);

                        await message.DeleteAsync();

                        BotFrame.consoleOut($"Unknown command! Deleted message from user {context.User} in channel {context.Channel.Name}{Environment.NewLine}Message: {message.Content}");
                        return;
                    }
                }
                else
                {
                    BotFrame.consoleOut($"Delete message from user {context.User} in channel {context.Channel.Name}{Environment.NewLine}Message: {context.Message.Content}");
                    return;
                }
            }
        }
Exemple #26
0
        public Task ExecuteAsync(SocketUserMessage msg, string[] parameters)
        {
            Task.Run(async() =>
            {
                Program.Configuration.Instance.Registered.Clear();

                Program.Configuration.Save();

                await msg.DeleteAsync();
            });
            return(Task.CompletedTask);
        }
Exemple #27
0
        public Task ExecuteAsync(SocketUserMessage msg, string[] parameters)
        {
            Task.Run(async() =>
            {
                await msg.Author.GetOrCreateDMChannelAsync();
                await msg.Author.SendMessageAsync(Program.Configuration.Instance.Registered.Count > 0 ? string.Join("\n", Program.Configuration.Instance.Registered) : "No one is registered");

                Program.Configuration.Save();

                await msg.DeleteAsync();
            });
            return(Task.CompletedTask);
        }
        public async Task Execute(SocketUserMessage userMessage, int argsPos)
        {
            var context = userMessage.GetMessageContext(_client);
            var stat    = await _rouletteStore.GetGuildStats(context.Guild.Id, 10);

            var countArg = argsPos >= userMessage.Content.Length ? "" : userMessage.Content.Substring(argsPos + 1);

            if (string.IsNullOrWhiteSpace(countArg))
            {
                countArg = "5";
            }

            string message = null;

            if (!int.TryParse(countArg, out var count))
            {
                await userMessage.DeleteAsync();

                return;
            }

            count = Math.Max(5, count);
            if (stat.Count > 0)
            {
                var z = stat
                        .Where(s => s.Value.Wins + s.Value.Loses >= 3)
                        .Select(s => (s.Value, context.Guild.GetUser(s.Key)))
                        .Where(s => s.Item2 != null)
                        .OrderByDescending(s => Math.Round((double)s.Value.Wins / (s.Value.Wins + s.Value.Loses), 1))
                        .ThenByDescending(s => s.Value.Wins + s.Value.Loses)
                        .ThenByDescending(s => s.Value.Wins)
                        .ThenBy(s => s.Item2.Id)
                        .Take(count)
                        .Select(s =>
                {
                    var((wins, loses), user) = s;
                    var c = wins + loses;
                    return($"**{user.GetUserDisplayName()}** застрелился {wins} {wins.ToTimesString()}! ({100.0 * wins / c:f1}% от {c})");
                });
                message = string.Join(Environment.NewLine, z);
            }

            if (string.IsNullOrWhiteSpace(message))
            {
                message = $"Пусто... сыграйте \"{_client.CurrentUser.Mention} рулетка!\"";
            }

            var reply = await userMessage.Channel.SendMessageAsync(message);

            await MessageUtilities.DeleteMessagesAsync(15, userMessage, reply);
        }
Exemple #29
0
        public static async Task Reply(SocketUserMessage msg, bool privateOnly = false, string text = null, Embed embed = null)
        {
            try
            {
                if (text == null)
                {
                    text = string.Empty;
                }

                if (msg.Channel.GetType() != typeof(SocketDMChannel))
                {
                    bool isRole    = false;
                    var  userRoles = ((SocketGuildUser)msg.Author).Roles;
                    foreach (SocketRole role in userRoles)
                    {
                        if (Globals.Bot.Config.DevRoleIds.Contains(role.Id))
                        {
                            isRole = true;
                            break;
                        }
                    }

                    if (isRole)
                    {
                        await msg.Channel.SendMessageAsync(text, false, embed);

                        return;
                    }

                    if (Globals.Bot.Config.BotChannelIds.Contains(msg.Channel.Id) && !privateOnly)
                    {
                        await msg.Channel.SendMessageAsync(text, false, embed);
                    }
                    else
                    {
                        await Discord.UserExtensions.SendMessageAsync(msg.Author, text, false, embed);

                        await msg.DeleteAsync();
                    }
                }
                else
                {
                    await Discord.UserExtensions.SendMessageAsync(msg.Author, text, false, embed);
                }
            }
            catch (Exception)
            {
                await Log.Write($"Count not send reply to {msg.Author.Username}");
            }
        }
Exemple #30
0
        public async Task QueueSong(string query, SocketUser usr, IMessageChannel channel, IGuild guild, SocketUserMessage usrmsg)
        {
            if ((usr as IVoiceState).VoiceChannel == null)
            {
                await channel.SendMessageAsync(usr.Mention + " você não está conectado em nenhum canal de voz");

                return;
            }
            Video video = YTVideoOperation.YoutubeSearch(query);

            if (video == null)
            {
                var embedL = new EmbedBuilder()
                             .WithColor(new Color(240, 230, 231))
                             .WithDescription("Nenhum resultado encontrado para: " + query);
                await channel.SendMessageAsync("", false, embedL);

                return;
            }

            //Attempts to get the audio URI either by YoutubeExplode or youtube-dl
            //First attempt is with YoutubeExplode
            string uri = YTVideoOperation.GetVideoURIExplode(video.Id).Result;


            if (uri == null)
            {
                uri = YTVideoOperation.GetVideoAudioURI("https://www.youtube.com/watch?v=" + video.Id);
            }

            YTSong song = new YTSong(video, uri, query, SongOrder(), usr);

            mp.Enqueue(song);
            var embedQueue = new EmbedBuilder()
                             .WithColor(new Color(240, 230, 231))
                             .WithTitle("#" + song.Order + "  " + song.Title)
                             .WithDescription("Busca: " + query)
                             .WithUrl(song.Url)
                             .WithImageUrl(song.DefaultThumbnailUrl)
                             .WithFooter(new EmbedFooterBuilder().WithText(song.RequestAuthor.Username + " | " + song.Duration));

            var msg = await channel.SendMessageAsync("", false, embedQueue);

            await Task.Delay(6000);

            await usrmsg.DeleteAsync().ConfigureAwait(false);

            await msg.DeleteAsync().ConfigureAwait(false);
        }