public static async Task UserJoined(SocketGuildUser user)
        {
            #region Database

            var  dbUser        = Core.GetUserFromGuild(user.Id, user.Guild.Id);
            bool alreadyJoined = dbUser.Usernames != null;
            dbUser.AddUsername(user.Username);
            dbUser.IsPresent = true;
            Core.SaveUserToGuild(dbUser, user.Guild.Id);

            #endregion Databasae

            var guildConfig = Core.GetGuildConfig(user.Guild.Id);

            #region JoinMessage

            if (guildConfig.JoinMessageChannelId != 0 && !string.IsNullOrEmpty(guildConfig.JoinMessage) && user.Guild.Channels.Any(r => r.Id == guildConfig.JoinMessageChannelId))
            {
                await user.Guild.GetTextChannel(guildConfig.JoinMessageChannelId).SendMessageAsync(
                    VerificationEngine.ConstructWelcomeMessage(guildConfig.JoinMessage, user));
            }

            #endregion JoinMessage

            #region Logging


            if (!(guildConfig.VerifiedRole == 0 || (string.IsNullOrEmpty(guildConfig.VerifiedMessage) || guildConfig.VerifiedMessage.Split().Length < 32 || !user.Guild.Roles.Any(r => r.Id == guildConfig.VerifiedRole))))
            {
                string vMessage = $"Hey {user.Username}! To get verified on **{user.Guild.Name}** reply to this message with the hidden code in the message below\n\n"
                                  + guildConfig.VerifiedMessage;

                string verificationMessage =
                    VerificationEngine.InsertCodeInMessage(vMessage, VerificationEngine.GetVerificationCode(user.Id, user.Guild.Id));

                try
                {
                    await user.GetOrCreateDMChannelAsync().Result.SendMessageAsync(verificationMessage);
                }
                catch
                {
                    await Core.Logger.LogErrorMessage(new Exception($"Could not send verification DM to {user} ({user.Id}) on {user.Guild} ({user.Guild.Id})"), null);
                }
            }
            if (guildConfig.MutedUsers.Contains(user.Id))
            {
                try
                {
                    await user.AddRoleAsync(user.Guild.GetRole(guildConfig.MutedRoleId));
                }
                catch (Exception ex)
                {
                    await Core.Logger.LogErrorMessage(ex, null);
                }
            }
            if (guildConfig.AutoRoleIds != null && guildConfig.AutoRoleIds.Any())
            {
                foreach (var role in guildConfig.AutoRoleIds)
                {
                    try
                    {
                        await user.AddRoleAsync(user.Guild.GetRole(role));
                    }
                    catch (Exception ex)
                    {
                        await Core.Logger.LogErrorMessage(ex, null);
                    }
                }
            }

            if (guildConfig.LoggingChannelId == 0)
            {
                return;
            }

            EmbedBuilder log = new EmbedBuilder()
                               .WithAuthor(new EmbedAuthorBuilder().WithName("User Joined")
                                           .WithIconUrl(user.GetAvatarUrl()).WithUrl(user.GetAvatarUrl()))
                               .WithColor(114, 137, 218)
                               .AddField(new EmbedFieldBuilder().WithName("Username").WithValue(user.ToString().Escape()).WithIsInline(true))
                               .AddField(new EmbedFieldBuilder().WithName("UserId").WithValue(user.Id).WithIsInline(true))
                               .AddField(new EmbedFieldBuilder().WithName("Mention").WithValue(user.Mention).WithIsInline(true))
                               .AddField(new EmbedFieldBuilder().WithName("User Number").WithValue(user.Guild.MemberCount + (!alreadyJoined ? " (New Member)" : "")).WithIsInline(true))
                               //.AddField(new EmbedFieldBuilder().WithName("Database Number").WithValue(guildDb.Users.Count + (alreadyJoined ? " (Previous Member)" : "")).WithIsInline(true))
                               .WithFooter($"{DateTime.UtcNow.ToString(@"yyyy-MM-dd HH:mm tt")} GMT");

            if ((DateTimeOffset.Now - user.CreatedAt).TotalDays < 7)
            {
                log.AddField(new EmbedFieldBuilder().WithName("New User")
                             .WithValue($"Account made {(DateTimeOffset.Now - user.CreatedAt).Nice()} ago").WithIsInline(true));
            }

            try
            {
                if (!dbUser.Warnings.IsEmpty())
                {
                    string warns = "";
                    for (int i = 0; i < dbUser.Warnings.Count; i++)
                    {
                        warns += $"{i + 1}: {dbUser.Warnings.ElementAt(i)}\n";
                    }
                    log.AddField(new EmbedFieldBuilder().WithName($"{dbUser.Warnings.Count} Warnings")
                                 .WithValue(warns));
                }
            }
            catch (Exception ex)
            {
                await Core.Logger.LogErrorMessage(ex, null);
            }

            await user.Guild.GetTextChannel(guildConfig.LoggingChannelId).SendMessageAsync("", embed: log.Build());

            #endregion Logging
        }
Example #2
0
        public static async Task UserJoined(SocketGuildUser user)
        {
            #region Database

            var  guildDb       = new DBGuild(user.Guild.Id);
            bool alreadyJoined = false;
            if (guildDb.Users.Any(u => u.ID.Equals(user.Id))) // if already exists
            {
                guildDb.Users.Find(u => u.ID.Equals(user.Id)).AddUsername(user.Username);
                alreadyJoined = true;
            }
            else
            {
                guildDb.Users.Add(new DBUser(user));
            }
            guildDb.Save();

            #endregion Databasae

            #region Logging

            var guildConfig = GenericBot.GuildConfigs[user.Guild.Id];

            if (!(guildConfig.VerifiedRole == 0 || (string.IsNullOrEmpty(guildConfig.VerifiedMessage) || guildConfig.VerifiedMessage.Split().Length < 32 || !user.Guild.Roles.Any(r => r.Id == guildConfig.VerifiedRole))))
            {
                string vMessage = $"Hey {user.Username}! To get verified on **{user.Guild.Name}** reply to this message with the hidden code in the message below\n\n"
                                  + GenericBot.GuildConfigs[user.Guild.Id].VerifiedMessage;

                string verificationMessage =
                    VerificationEngine.InsertCodeInMessage(vMessage, VerificationEngine.GetVerificationCode(user.Id, user.Guild.Id));

                try
                {
                    await user.GetOrCreateDMChannelAsync().Result.SendMessageAsync(verificationMessage);
                }
                catch
                {
                    await GenericBot.Logger.LogErrorMessage($"Could not send verification DM to {user} ({user.Id}) on {user.Guild} ({user.Guild.Id})");
                }
            }
            if (guildConfig.ProbablyMutedUsers.Contains(user.Id))
            {
                try { await user.AddRoleAsync(user.Guild.GetRole(guildConfig.MutedRoleId)); }
                catch { }
            }
            if (guildConfig.AutoRoleIds != null && guildConfig.AutoRoleIds.Any())
            {
                foreach (var role in guildConfig.AutoRoleIds)
                {
                    try
                    {
                        await user.AddRoleAsync(user.Guild.GetRole(role));
                    }
                    catch
                    {
                        // Supress
                    }
                }
            }

            if (guildConfig.UserLogChannelId == 0)
            {
                return;
            }

            EmbedBuilder log = new EmbedBuilder()
                               .WithAuthor(new EmbedAuthorBuilder().WithName("User Joined")
                                           .WithIconUrl(user.GetAvatarUrl()).WithUrl(user.GetAvatarUrl()))
                               .WithColor(114, 137, 218)
                               .AddField(new EmbedFieldBuilder().WithName("Username").WithValue(user.ToString().Escape()).WithIsInline(true))
                               .AddField(new EmbedFieldBuilder().WithName("UserId").WithValue(user.Id).WithIsInline(true))
                               .AddField(new EmbedFieldBuilder().WithName("Mention").WithValue(user.Mention).WithIsInline(true))
                               .AddField(new EmbedFieldBuilder().WithName("User Number").WithValue(user.Guild.MemberCount + (!alreadyJoined ? " (New Member)" : "")).WithIsInline(true))
                               .AddField(new EmbedFieldBuilder().WithName("Database Number").WithValue(guildDb.Users.Count + (alreadyJoined ? " (Previous Member)" : "")).WithIsInline(true))
                               .WithFooter($"{DateTime.UtcNow.ToString(@"yyyy-MM-dd HH:mm tt")} GMT");

            if ((DateTimeOffset.Now - user.CreatedAt).TotalDays < 7)
            {
                log.AddField(new EmbedFieldBuilder().WithName("New User")
                             .WithValue($"Account made {(DateTimeOffset.Now - user.CreatedAt).Nice()} ago").WithIsInline(true));
            }

            try
            {
                DBUser usr = guildDb.Users.First(u => u.ID.Equals(user.Id));

                if (!usr.Warnings.Empty())
                {
                    string warns = "";
                    for (int i = 0; i < usr.Warnings.Count; i++)
                    {
                        warns += $"{i + 1}: {usr.Warnings.ElementAt(i)}\n";
                    }
                    log.AddField(new EmbedFieldBuilder().WithName($"{usr.Warnings.Count} Warnings")
                                 .WithValue(warns));
                }
            }
            catch
            {
            }

            await user.Guild.GetTextChannel(guildConfig.UserLogChannelId).SendMessageAsync("", embed: log.Build());

            #endregion Logging

            #region Antispam

            if (guildConfig.AntispamLevel >= GuildConfig.AntiSpamLevel.Advanced)
            {
                var inviteLink = new Regex(@"(?:https?:\/\/)?(?:www\.)?(discord\.gg|discord\.io|discord\.me|discordapp\.com\/invite|paypal\.me|twitter\.com|youtube\.com|bit\.ly|twitch\.tv)\/(\S+)");
                if (inviteLink.Matches(user.Username).Any())
                {
                    if (guildConfig.AntispamLevel == GuildConfig.AntiSpamLevel.Advanced)
                    {
                        await user.KickAsync("Username Contains Discord Spam Invite");

                        var builder = new EmbedBuilder()
                                      .WithTitle("User Kicked")
                                      .WithDescription("Discord Invite in Username (Antispam)")
                                      .WithColor(new Color(0xFFFF00))
                                      .WithFooter(footer => {
                            footer
                            .WithText($"By {GenericBot.DiscordClient.CurrentUser} at {DateTime.UtcNow.ToString(@"yyyy-MM-dd HH:mm tt")} GMT");
                        })
                                      .WithAuthor(author => {
                            author
                            .WithName(user.ToString())
                            .WithIconUrl(user.GetAvatarUrl());
                        });

                        var guilddb     = new DBGuild(user.Guild.Id);
                        var guildconfig = GenericBot.GuildConfigs[user.Guild.Id];
                        guilddb.GetUser(user.Id)
                        .AddWarning(
                            $"Kicked for `Username Contains Discord Spam Invite` (By `{GenericBot.DiscordClient.CurrentUser}` At `{DateTime.UtcNow.ToString(@"yyyy-MM-dd HH:mm tt")} GMT`)");
                        guilddb.Save();

                        if (guildconfig.UserLogChannelId != 0)
                        {
                            await(GenericBot.DiscordClient.GetChannel(guildconfig.UserLogChannelId) as SocketTextChannel)
                            .SendMessageAsync("", embed: builder.Build());
                        }
                    }
                    else if (guildConfig.AntispamLevel >= GuildConfig.AntiSpamLevel.Aggressive)
                    {
                        await user.BanAsync(0, "Username Contains Discord Spam Invite");

                        var builder = new EmbedBuilder()
                                      .WithTitle("User Banned")
                                      .WithDescription("Discord Invite in Username (Antispam)")
                                      .WithColor(new Color(0xFFFF00))
                                      .WithFooter(footer => {
                            footer
                            .WithText($"By {GenericBot.DiscordClient.CurrentUser} at {DateTime.UtcNow.ToString(@"yyyy-MM-dd HH:mm tt")} GMT");
                        })
                                      .WithAuthor(author => {
                            author
                            .WithName(user.ToString())
                            .WithIconUrl(user.GetAvatarUrl());
                        });

                        var guilddb     = new DBGuild(user.Guild.Id);
                        var guildconfig = GenericBot.GuildConfigs[user.Guild.Id];
                        guilddb.GetUser(user.Id)
                        .AddWarning(
                            $"Banned for `Username Contains Discord Spam Invite` (By `{GenericBot.DiscordClient.CurrentUser}` At `{DateTime.UtcNow.ToString(@"yyyy-MM-dd HH:mm tt")} GMT`)");
                        guilddb.Save();

                        if (guildconfig.UserLogChannelId != 0)
                        {
                            await(GenericBot.DiscordClient.GetChannel(guildconfig.UserLogChannelId) as SocketTextChannel)
                            .SendMessageAsync("", embed: builder.Build());
                        }
                    }
                }
            }

            #endregion Antispam
        }
        public static async Task MessageRecieved(SocketMessage parameterMessage, bool edited = false)
        {
            Core.Messages++;
            // Don't do stuff if the user is blacklisted
            if (Core.CheckBlacklisted(parameterMessage.Author.Id))
            {
                return;
            }
            // Ignore self
            if (parameterMessage.Author.Id == Core.GetCurrentUserId())
            {
                return;
            }

            // Handle me saying "open an issue"
            try
            {
                if (parameterMessage.Content.ToLower().Contains("open an issue") && parameterMessage.Author.Id == Core.DiscordClient.GetApplicationInfoAsync().Result.Owner.Id)
                {
                    parameterMessage.Channel.SendMessageAsync("https://github.com/galenguyer/GenericBot/issues");
                }
            }
            catch { }
            // pluralkit logging integration
            try
            {
                if (parameterMessage.Author.IsWebhook)
                {
                    using (var client = new System.Net.WebClient())
                    {
                        var resp = client.DownloadString($"https://api.pluralkit.me/v1/msg/{parameterMessage.Id}");
                        var type = new
                        {
                            original = "string"
                        };
                        var obj = JsonConvert.DeserializeAnonymousType(resp, type);
                        Program.ClearedMessageIds.Add(ulong.Parse(obj.original));
                    }
                }
            }
            catch { }
            // viccy validation
            try
            {
                if (parameterMessage.Author.Id == 343830280131444746 && new Random().Next(50) == 1)
                {
                    await parameterMessage.ReplyAsync("<@!343830280131444746>, you're a good girl <3");
                }
            }
            catch { }
            // luko validation
            try
            {
                if (parameterMessage.Author.Id == 572532145743200256 && new Random().Next(50) == 1)
                {
                    await parameterMessage.ReplyAsync("<@!572532145743200256>, you're a good and valid enby <3");
                }
            }
            catch { }
            // points
            try
            {
                var dbUser = Core.GetUserFromGuild(parameterMessage.Author.Id, parameterMessage.GetGuild().Id);
                dbUser.IncrementPointsAndMessages();

                var dbGuild = Core.GetGuildConfig(parameterMessage.GetGuild().Id);
                if (dbGuild.TrustedRoleId != 0 && dbUser.Points > dbGuild.TrustedRolePointThreshold)
                {
                    var guild     = Core.DiscordClient.GetGuild(dbGuild.Id);
                    var guildUser = guild.GetUser(dbUser.Id);
                    if (!guildUser.Roles.Any(sr => sr.Id == dbGuild.TrustedRoleId))
                    {
                        guildUser.AddRoleAsync(guild.GetRole(dbGuild.TrustedRoleId));
                    }
                }

                Core.SaveUserToGuild(dbUser, parameterMessage.GetGuild().Id);
            }
            catch (Exception e)
            {
                await Core.Logger.LogErrorMessage(e, null);
            }

            try
            {
                ParsedCommand command;

                if (parameterMessage.Channel is SocketDMChannel)
                {
                    command = new Command("t").ParseMessage(parameterMessage);

                    Core.Logger.LogGenericMessage($"Recieved DM: {parameterMessage.Content}");

                    if (command != null && command.RawCommand != null && command.RawCommand.WorksInDms)
                    {
                        command.Execute();
                    }
                    else
                    {
                        IUserMessage alertMessage = null;
                        if (Core.GlobalConfig.CriticalLoggingChannel != 0)
                        {
                            alertMessage = ((ITextChannel)Core.DiscordClient.GetChannel(Core.GlobalConfig.CriticalLoggingChannel))
                                           .SendMessageAsync($"```\nDM from: {parameterMessage.Author}({parameterMessage.Author.Id})\nContent: {parameterMessage.Content}\n```").Result;
                        }
                        if (parameterMessage.Content.Trim().Split().Length == 1)
                        {
                            var guild = VerificationEngine.GetGuildFromCode(parameterMessage.Content, parameterMessage.Author.Id);
                            if (guild == null)
                            {
                                parameterMessage.ReplyAsync("Invalid verification code");
                            }
                            else
                            {
                                guild.GetUser(parameterMessage.Author.Id)
                                .AddRoleAsync(guild.GetRole(Core.GetGuildConfig(guild.Id).VerifiedRole));
                                if (guild.TextChannels.HasElement(c => c.Id == (Core.GetGuildConfig(guild.Id).LoggingChannelId), out SocketTextChannel logChannel))
                                {
                                    logChannel.SendMessageAsync($"`{DateTime.UtcNow.ToString(@"yyyy-MM-dd HH:mm tt")}`:  `{parameterMessage.Author}` (`{parameterMessage.Author.Id}`) just verified");
                                }
                                parameterMessage.ReplyAsync($"You've been verified on **{guild.Name}**!");
                                if (alertMessage != null)
                                {
                                    alertMessage.ModifyAsync(m =>
                                                             m.Content = $"```\nDM from: {parameterMessage.Author}({parameterMessage.Author.Id})\nContent: {parameterMessage.Content.SafeSubstring(1900)}\nVerified on {guild.Name}\n```");
                                }
                            }
                        }
                    }
                }
                else
                {
                    ulong guildId = parameterMessage.GetGuild().Id;
                    command = new Command("t").ParseMessage(parameterMessage);

                    if (Core.GetCustomCommands(guildId).HasElement(c => c.Name == command.Name,
                                                                   out CustomCommand customCommand))
                    {
                        Core.AddToCommandLog(command, guildId);
                        if (customCommand.Delete)
                        {
                            parameterMessage.DeleteAsync();
                        }
                        parameterMessage.ReplyAsync(customCommand.Response);
                    }

                    if (command != null && command.RawCommand != null)
                    {
                        Core.AddToCommandLog(command, guildId);
                        command.Execute();
                    }
                }
            }
            catch (Exception ex)
            {
                if (parameterMessage.Author.Id == Core.GetOwnerId())
                {
                    parameterMessage.ReplyAsync("```\n" + $"{ex.Message}\n{ex.StackTrace}".SafeSubstring(1000) + "\n```");
                }
                Core.Logger.LogErrorMessage(ex, new Command("t").ParseMessage(parameterMessage));
            }
        }
Example #4
0
        public static async Task MessageRecieved(SocketMessage parameterMessage, bool edited = false)
        {
            // Don't handle the command if it is a system message
            var message = parameterMessage;

            if (GenericBot.GlobalConfiguration.BlacklistedIds.Contains(message.Author.Id))
            {
                return;
            }

            if (parameterMessage.Author.Id == GenericBot.DiscordClient.CurrentUser.Id)
            {
                return;
            }

            if (parameterMessage.Channel.GetType().FullName.ToLower().Contains("dmchannel"))
            {
                var msg = GenericBot.DiscordClient.GetApplicationInfoAsync().Result.Owner.GetOrCreateDMChannelAsync().Result
                          .SendMessageAsync($"```\nDM from: {message.Author}({message.Author.Id})\nContent: {message.Content}\n```").Result;
                if (parameterMessage.Content.Trim().Split().Length == 1)
                {
                    var guild = VerificationEngine.GetGuildFromCode(parameterMessage.Content, message.Author.Id);
                    if (guild == null)
                    {
                        await message.ReplyAsync("Invalid verification code");
                    }
                    else
                    {
                        await guild.GetUser(message.Author.Id)
                        .AddRoleAsync(guild.GetRole(GenericBot.GuildConfigs[guild.Id].VerifiedRole));

                        if (guild.TextChannels.HasElement(c => c.Id == (GenericBot.GuildConfigs[guild.Id].UserLogChannelId), out SocketTextChannel logChannel))
                        {
                            logChannel.SendMessageAsync($"`{DateTime.UtcNow.ToString(@"yyyy-MM-dd HH:mm tt")}`:  `{message.Author}` (`{message.Author.Id}`) just verified");
                        }
                        await message.ReplyAsync($"You've been verified on **{guild.Name}**!");

                        await msg.ModifyAsync(m =>
                                              m.Content = $"```\nDM from: {message.Author}({message.Author.Id})\nContent: {message.Content.SafeSubstring(1900)}\nVerified on {guild.Name}\n```");
                    }
                }
            }

            new DBGuild(message.GetGuild().Id).Users.Find(u => u.ID.Equals(message.Author.Id)).AddUsername(message.Author.Username);
            new DBGuild(message.GetGuild().Id).Users.Find(u => u.ID.Equals(message.Author.Id)).AddNickname(message.Author as SocketGuildUser);

            if (!edited)
            {
                //new GuildMessageStats(parameterMessage.GetGuild().Id).AddMessage(parameterMessage.Author.Id).Save();
            }

            if (parameterMessage.Author.Id != GenericBot.DiscordClient.CurrentUser.Id &&
                GenericBot.GuildConfigs[parameterMessage.GetGuild().Id].FourChannelId == parameterMessage.Channel.Id)
            {
                await parameterMessage.DeleteAsync();

                await parameterMessage.ReplyAsync(
                    $"**[Anonymous]** {string.Format("{0:yyyy-MM-dd HH\\:mm\\:ss}", DateTimeOffset.UtcNow)}\n{parameterMessage.Content}");
            }

            System.Threading.Thread pointThread = new System.Threading.Thread(() =>
            {
                try
                {
                    lock (message.GetGuild().Id.ToString())
                    {
                        DBGuild db = new DBGuild(message.GetGuild().Id);
                        if (db.Users == null)
                        {
                            return;
                        }
                        if (!edited)
                        {
                            db.GetUser(message.Author.Id).PointsCount += (decimal)(.01);
                            if (GenericBot.GuildConfigs[message.GetGuild().Id].Levels.Any(kvp => kvp.Key <= db.GetUser(message.Author.Id).PointsCount))
                            {
                                foreach (var level in GenericBot.GuildConfigs[message.GetGuild().Id].Levels
                                         .Where(kvp => kvp.Key <= db.GetUser(message.Author.Id).PointsCount)
                                         .Where(kvp => !(message.Author as SocketGuildUser).Roles.Any(r => r.Id.Equals(kvp.Value))))
                                {
                                    (message.Author as SocketGuildUser).AddRoleAsync(message.GetGuild().GetRole(level.Value));
                                }
                            }
                        }
                        var thanksRegex = new Regex(@"(\b)((thanks?)|(thx)|(ty))(\b)", RegexOptions.IgnoreCase);
                        if (thanksRegex.IsMatch(message.Content) && GenericBot.GuildConfigs[message.GetGuild().Id].PointsEnabled && message.MentionedUsers.Any())
                        {
                            if (new DBGuild(message.GetGuild().Id).GetUser(message.Author.Id).LastThanks.AddMinutes(1) < DateTimeOffset.UtcNow)
                            {
                                List <IUser> givenUsers = new List <IUser>();
                                foreach (var user in message.MentionedUsers)
                                {
                                    if (user.Id == message.Author.Id)
                                    {
                                        continue;
                                    }

                                    db.GetUser(user.Id).PointsCount++;
                                    givenUsers.Add(user);
                                }
                                if (givenUsers.Any())
                                {
                                    message.ReplyAsync($"{givenUsers.Select(us => $"**{(us as SocketGuildUser).GetDisplayName()}**").ToList().SumAnd()} recieved a {GenericBot.GuildConfigs[message.GetGuild().Id].PointsName} of thanks from **{(message.Author as SocketGuildUser).GetDisplayName()}**");
                                    db.GetUser(message.Author.Id).LastThanks = DateTimeOffset.UtcNow;
                                }
                                else
                                {
                                    message.ReplyAsync("You can't give yourself a point!");
                                }
                            }
                        }
                        db.Save();
                    }
                }
                catch (Exception ex)
                {
                    //GenericBot.Logger.LogErrorMessage($"{ex.Message}\nGuild:{message.GetGuild().Name} | {message.GetGuild().Id}\nChannel:{message.Channel.Name} | {message.Channel.Id}\nUser:{message.Author} | {message.Author.Id}\n{message.Content}");
                }
            });
            pointThread.IsBackground = true;
            pointThread.Start();


            GenericBot.QuickWatch.Restart();
            try
            {
                var commandInfo = CommandHandler.ParseMessage(parameterMessage);

                CustomCommand custom = new CustomCommand();

                if (parameterMessage.Channel is IDMChannel)
                {
                    goto DMChannel;
                }

                if (GenericBot.GuildConfigs[parameterMessage.GetGuild().Id].CustomCommands
                    .HasElement(c => c.Name == commandInfo.Name, out custom) ||
                    GenericBot.GuildConfigs[parameterMessage.GetGuild().Id].CustomCommands
                    .HasElement(c => c.Aliases.Any(a => a.Equals(commandInfo.Name)), out custom))
                {
                    if (custom.Delete)
                    {
                        await parameterMessage.DeleteAsync();
                    }
                    await parameterMessage.ReplyAsync(custom.Response);

                    //new GuildMessageStats(parameterMessage.GetGuild().Id).AddCommand(parameterMessage.Author.Id, custom.Name).Save();
                }

DMChannel:
                GenericBot.LastCommand = commandInfo;
                commandInfo.Command.ExecuteCommand(GenericBot.DiscordClient, message, commandInfo.Parameters).FireAndForget();
                GenericBot.Logger.LogGenericMessage($"Guild: {parameterMessage.GetGuild().Name} ({parameterMessage.GetGuild().Id}) Channel: {parameterMessage.Channel.Name} ({parameterMessage.Channel.Id}) User: {parameterMessage.Author} ({parameterMessage.Author.Id}) Command: {commandInfo.Command.Name} Parameters {JsonConvert.SerializeObject(commandInfo.Parameters)}");
                //new GuildMessageStats(parameterMessage.GetGuild().Id).AddCommand(parameterMessage.Author.Id, commandInfo.Command.Name).Save();
            }
            catch (NullReferenceException nullRefEx)
            {
            }
            catch (Exception ex)
            {
                if (parameterMessage.Author.Id == GenericBot.GlobalConfiguration.OwnerId)
                {
                    await parameterMessage.ReplyAsync("```\n" + $"{ex.Message}\n{ex.StackTrace}".SafeSubstring(1000) +
                                                      "\n```");
                }
                await GenericBot.Logger.LogErrorMessage(ex.Message);

                //else Console.WriteLine($"{ex.Message}\n{ex.StackTrace}");
            }
        }
Example #5
0
        public static async Task UserJoined(SocketGuildUser user)
        {
            #region Database

            var  guildDb       = new DBGuild(user.Guild.Id);
            bool alreadyJoined = false;
            if (guildDb.Users.Any(u => u.ID.Equals(user.Id))) // if already exists
            {
                guildDb.Users.Find(u => u.ID.Equals(user.Id)).AddUsername(user.Username);
                alreadyJoined = true;
            }
            else
            {
                guildDb.Users.Add(new DBUser(user));
            }
            lock ("db")
            {
                guildDb.Save();
            }

            #endregion Databasae

            #region Logging

            var guildConfig = GenericBot.GuildConfigs[user.Guild.Id];

            if (!(guildConfig.VerifiedRole == 0 || (string.IsNullOrEmpty(guildConfig.VerifiedMessage) || guildConfig.VerifiedMessage.Split().Length < 32 || !user.Guild.Roles.Any(r => r.Id == guildConfig.VerifiedRole))))
            {
                string vMessage = $"Hey {user.Username}! To get verified on **{user.Guild.Name}** reply to this message with the hidden code in the message below\n\n"
                                  + GenericBot.GuildConfigs[user.Guild.Id].VerifiedMessage;

                string verificationMessage =
                    VerificationEngine.InsertCodeInMessage(vMessage, VerificationEngine.GetVerificationCode(user.Id, user.Guild.Id));

                try
                {
                    await user.GetOrCreateDMChannelAsync().Result.SendMessageAsync(verificationMessage);
                }
                catch (Exception ex)
                {
                }
            }
            if (guildConfig.ProbablyMutedUsers.Contains(user.Id))
            {
                try { user.AddRoleAsync(user.Guild.GetRole(guildConfig.MutedRoleId)); }
                catch { }
            }
            if (guildConfig.AutoRoleIds != null && guildConfig.AutoRoleIds.Any())
            {
                foreach (var role in guildConfig.AutoRoleIds)
                {
                    try
                    {
                        await user.AddRoleAsync(user.Guild.GetRole(role));
                    }
                    catch
                    {
                        // Supress
                    }
                }
            }

            if (guildConfig.UserLogChannelId == 0)
            {
                return;
            }

            EmbedBuilder log = new EmbedBuilder()
                               .WithAuthor(new EmbedAuthorBuilder().WithName("User Joined")
                                           .WithIconUrl(user.GetAvatarUrl()).WithUrl(user.GetAvatarUrl()))
                               .WithColor(114, 137, 218)
                               .AddField(new EmbedFieldBuilder().WithName("Username").WithValue(user.ToString().Escape()).WithIsInline(true))
                               .AddField(new EmbedFieldBuilder().WithName("UserId").WithValue(user.Id).WithIsInline(true))
                               .AddField(new EmbedFieldBuilder().WithName("Mention").WithValue(user.Mention).WithIsInline(true))
                               .AddField(new EmbedFieldBuilder().WithName("User Number").WithValue(user.Guild.MemberCount + (!alreadyJoined ? " (New Member)" : "")).WithIsInline(true))
                               .AddField(new EmbedFieldBuilder().WithName("Database Number").WithValue(guildDb.Users.Count + (alreadyJoined ? " (Previous Member)" : "")).WithIsInline(true))
                               .WithFooter($"{DateTime.UtcNow.ToString(@"yyyy-MM-dd HH:mm tt")} GMT");

            if ((DateTimeOffset.Now - user.CreatedAt).TotalDays < 7)
            {
                log.AddField(new EmbedFieldBuilder().WithName("New User")
                             .WithValue($"Account made {(DateTimeOffset.Now - user.CreatedAt).Nice()} ago").WithIsInline(true));
            }

            try
            {
                DBUser usr = guildDb.Users.First(u => u.ID.Equals(user.Id));

                if (!usr.Warnings.Empty())
                {
                    string warns = "";
                    for (int i = 0; i < usr.Warnings.Count; i++)
                    {
                        warns += $"{i + 1}: {usr.Warnings.ElementAt(i)}\n";
                    }
                    log.AddField(new EmbedFieldBuilder().WithName($"{usr.Warnings.Count} Warnings")
                                 .WithValue(warns));
                }
            }
            catch
            {
            }

            await user.Guild.GetTextChannel(guildConfig.UserLogChannelId).SendMessageAsync("", embed: log.Build());

            #endregion Logging
        }
        public static async Task MessageRecieved(SocketMessage parameterMessage, bool edited = false)
        {
            Core.Messages++;
            // Don't do stuff if the user is blacklisted
            if (Core.CheckBlacklisted(parameterMessage.Author.Id))
            {
                return;
            }
            // Ignore self
            if (parameterMessage.Author.Id == Core.GetCurrentUserId())
            {
                return;
            }

            // Handle me saying "open an issue"
            try
            {
                if (parameterMessage.Content.ToLower().Contains("open an issue") && parameterMessage.Author.Id == Core.DiscordClient.GetApplicationInfoAsync().Result.Owner.Id)
                {
                    parameterMessage.Channel.SendMessageAsync("https://github.com/galenguyer/GenericBot/issues");
                }
            }
            catch { }

            try
            {
                ParsedCommand command;

                if (parameterMessage.Channel is SocketDMChannel)
                {
                    command = new Command("t").ParseMessage(parameterMessage);

                    Core.Logger.LogGenericMessage($"Recieved DM: {parameterMessage.Content}");

                    if (command != null && command.RawCommand != null && command.RawCommand.WorksInDms)
                    {
                        command.Execute();
                    }
                    else
                    {
                        IUserMessage alertMessage = null;
                        if (Core.GlobalConfig.CriticalLoggingChannel != 0)
                        {
                            alertMessage = ((ITextChannel)Core.DiscordClient.GetChannel(Core.GlobalConfig.CriticalLoggingChannel))
                                           .SendMessageAsync($"```\nDM from: {parameterMessage.Author}({parameterMessage.Author.Id})\nContent: {parameterMessage.Content}\n```").Result;
                        }
                        if (parameterMessage.Content.Trim().Split().Length == 1)
                        {
                            var guild = VerificationEngine.GetGuildFromCode(parameterMessage.Content, parameterMessage.Author.Id);
                            if (guild == null)
                            {
                                parameterMessage.ReplyAsync("Invalid verification code");
                            }
                            else
                            {
                                guild.GetUser(parameterMessage.Author.Id)
                                .AddRoleAsync(guild.GetRole(Core.GetGuildConfig(guild.Id).VerifiedRole));
                                if (guild.TextChannels.HasElement(c => c.Id == (Core.GetGuildConfig(guild.Id).LoggingChannelId), out SocketTextChannel logChannel))
                                {
                                    logChannel.SendMessageAsync($"`{DateTime.UtcNow.ToString(@"yyyy-MM-dd HH:mm tt")}`:  `{parameterMessage.Author}` (`{parameterMessage.Author.Id}`) just verified");
                                }
                                parameterMessage.ReplyAsync($"You've been verified on **{guild.Name}**!");
                                if (alertMessage != null)
                                {
                                    alertMessage.ModifyAsync(m =>
                                                             m.Content = $"```\nDM from: {parameterMessage.Author}({parameterMessage.Author.Id})\nContent: {parameterMessage.Content.SafeSubstring(1900)}\nVerified on {guild.Name}\n```");
                                }
                            }
                        }
                    }
                }
                else
                {
                    ulong guildId = parameterMessage.GetGuild().Id;
                    command = new Command("t").ParseMessage(parameterMessage);

                    if (Core.GetCustomCommands(guildId).HasElement(c => c.Name == command.Name,
                                                                   out CustomCommand customCommand))
                    {
                        if (customCommand.Delete)
                        {
                            parameterMessage.DeleteAsync();
                        }
                        parameterMessage.ReplyAsync(customCommand.Response);
                    }

                    if (command != null && command.RawCommand != null)
                    {
                        command.Execute();
                    }
                }
            }
            catch (Exception ex)
            {
                if (parameterMessage.Author.Id == Core.GetOwnerId())
                {
                    parameterMessage.ReplyAsync("```\n" + $"{ex.Message}\n{ex.StackTrace}".SafeSubstring(1000) +
                                                "\n```");
                }
                Core.Logger.LogErrorMessage(ex, new Command("t").ParseMessage(parameterMessage));
            }
        }